id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_1162_0 | /* Copyright 2011-2014 Autronica Fire and Security AS
*
* 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.
*
* Author(s):
* 2011-2014 Arvid Brodin, arvid.brodin@alten.se
*
* This file contains device methods for creating, using and destroying
* virtual HSR devices.
*/
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/etherdevice.h>
#include <linux/rtnetlink.h>
#include <linux/pkt_sched.h>
#include "hsr_device.h"
#include "hsr_slave.h"
#include "hsr_framereg.h"
#include "hsr_main.h"
#include "hsr_forward.h"
static bool is_admin_up(struct net_device *dev)
{
return dev && (dev->flags & IFF_UP);
}
static bool is_slave_up(struct net_device *dev)
{
return dev && is_admin_up(dev) && netif_oper_up(dev);
}
static void __hsr_set_operstate(struct net_device *dev, int transition)
{
write_lock_bh(&dev_base_lock);
if (dev->operstate != transition) {
dev->operstate = transition;
write_unlock_bh(&dev_base_lock);
netdev_state_change(dev);
} else {
write_unlock_bh(&dev_base_lock);
}
}
static void hsr_set_operstate(struct hsr_port *master, bool has_carrier)
{
if (!is_admin_up(master->dev)) {
__hsr_set_operstate(master->dev, IF_OPER_DOWN);
return;
}
if (has_carrier)
__hsr_set_operstate(master->dev, IF_OPER_UP);
else
__hsr_set_operstate(master->dev, IF_OPER_LOWERLAYERDOWN);
}
static bool hsr_check_carrier(struct hsr_port *master)
{
struct hsr_port *port;
bool has_carrier;
has_carrier = false;
rcu_read_lock();
hsr_for_each_port(master->hsr, port)
if ((port->type != HSR_PT_MASTER) && is_slave_up(port->dev)) {
has_carrier = true;
break;
}
rcu_read_unlock();
if (has_carrier)
netif_carrier_on(master->dev);
else
netif_carrier_off(master->dev);
return has_carrier;
}
static void hsr_check_announce(struct net_device *hsr_dev,
unsigned char old_operstate)
{
struct hsr_priv *hsr;
hsr = netdev_priv(hsr_dev);
if ((hsr_dev->operstate == IF_OPER_UP)
&& (old_operstate != IF_OPER_UP)) {
/* Went up */
hsr->announce_count = 0;
hsr->announce_timer.expires = jiffies +
msecs_to_jiffies(HSR_ANNOUNCE_INTERVAL);
add_timer(&hsr->announce_timer);
}
if ((hsr_dev->operstate != IF_OPER_UP) && (old_operstate == IF_OPER_UP))
/* Went down */
del_timer(&hsr->announce_timer);
}
void hsr_check_carrier_and_operstate(struct hsr_priv *hsr)
{
struct hsr_port *master;
unsigned char old_operstate;
bool has_carrier;
master = hsr_port_get_hsr(hsr, HSR_PT_MASTER);
/* netif_stacked_transfer_operstate() cannot be used here since
* it doesn't set IF_OPER_LOWERLAYERDOWN (?)
*/
old_operstate = master->dev->operstate;
has_carrier = hsr_check_carrier(master);
hsr_set_operstate(master, has_carrier);
hsr_check_announce(master->dev, old_operstate);
}
int hsr_get_max_mtu(struct hsr_priv *hsr)
{
unsigned int mtu_max;
struct hsr_port *port;
mtu_max = ETH_DATA_LEN;
rcu_read_lock();
hsr_for_each_port(hsr, port)
if (port->type != HSR_PT_MASTER)
mtu_max = min(port->dev->mtu, mtu_max);
rcu_read_unlock();
if (mtu_max < HSR_HLEN)
return 0;
return mtu_max - HSR_HLEN;
}
static int hsr_dev_change_mtu(struct net_device *dev, int new_mtu)
{
struct hsr_priv *hsr;
struct hsr_port *master;
hsr = netdev_priv(dev);
master = hsr_port_get_hsr(hsr, HSR_PT_MASTER);
if (new_mtu > hsr_get_max_mtu(hsr)) {
netdev_info(master->dev, "A HSR master's MTU cannot be greater than the smallest MTU of its slaves minus the HSR Tag length (%d octets).\n",
HSR_HLEN);
return -EINVAL;
}
dev->mtu = new_mtu;
return 0;
}
static int hsr_dev_open(struct net_device *dev)
{
struct hsr_priv *hsr;
struct hsr_port *port;
char designation;
hsr = netdev_priv(dev);
designation = '\0';
rcu_read_lock();
hsr_for_each_port(hsr, port) {
if (port->type == HSR_PT_MASTER)
continue;
switch (port->type) {
case HSR_PT_SLAVE_A:
designation = 'A';
break;
case HSR_PT_SLAVE_B:
designation = 'B';
break;
default:
designation = '?';
}
if (!is_slave_up(port->dev))
netdev_warn(dev, "Slave %c (%s) is not up; please bring it up to get a fully working HSR network\n",
designation, port->dev->name);
}
rcu_read_unlock();
if (designation == '\0')
netdev_warn(dev, "No slave devices configured\n");
return 0;
}
static int hsr_dev_close(struct net_device *dev)
{
/* Nothing to do here. */
return 0;
}
static netdev_features_t hsr_features_recompute(struct hsr_priv *hsr,
netdev_features_t features)
{
netdev_features_t mask;
struct hsr_port *port;
mask = features;
/* Mask out all features that, if supported by one device, should be
* enabled for all devices (see NETIF_F_ONE_FOR_ALL).
*
* Anything that's off in mask will not be enabled - so only things
* that were in features originally, and also is in NETIF_F_ONE_FOR_ALL,
* may become enabled.
*/
features &= ~NETIF_F_ONE_FOR_ALL;
hsr_for_each_port(hsr, port)
features = netdev_increment_features(features,
port->dev->features,
mask);
return features;
}
static netdev_features_t hsr_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct hsr_priv *hsr = netdev_priv(dev);
return hsr_features_recompute(hsr, features);
}
static int hsr_dev_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct hsr_priv *hsr = netdev_priv(dev);
struct hsr_port *master;
master = hsr_port_get_hsr(hsr, HSR_PT_MASTER);
skb->dev = master->dev;
hsr_forward_skb(skb, master);
return NETDEV_TX_OK;
}
static const struct header_ops hsr_header_ops = {
.create = eth_header,
.parse = eth_header_parse,
};
static void send_hsr_supervision_frame(struct hsr_port *master,
u8 type, u8 hsrVer)
{
struct sk_buff *skb;
int hlen, tlen;
struct hsr_tag *hsr_tag;
struct hsr_sup_tag *hsr_stag;
struct hsr_sup_payload *hsr_sp;
unsigned long irqflags;
hlen = LL_RESERVED_SPACE(master->dev);
tlen = master->dev->needed_tailroom;
skb = dev_alloc_skb(
sizeof(struct hsr_tag) +
sizeof(struct hsr_sup_tag) +
sizeof(struct hsr_sup_payload) + hlen + tlen);
if (skb == NULL)
return;
skb_reserve(skb, hlen);
skb->dev = master->dev;
skb->protocol = htons(hsrVer ? ETH_P_HSR : ETH_P_PRP);
skb->priority = TC_PRIO_CONTROL;
if (dev_hard_header(skb, skb->dev, (hsrVer ? ETH_P_HSR : ETH_P_PRP),
master->hsr->sup_multicast_addr,
skb->dev->dev_addr, skb->len) <= 0)
goto out;
skb_reset_mac_header(skb);
if (hsrVer > 0) {
hsr_tag = skb_put(skb, sizeof(struct hsr_tag));
hsr_tag->encap_proto = htons(ETH_P_PRP);
set_hsr_tag_LSDU_size(hsr_tag, HSR_V1_SUP_LSDUSIZE);
}
hsr_stag = skb_put(skb, sizeof(struct hsr_sup_tag));
set_hsr_stag_path(hsr_stag, (hsrVer ? 0x0 : 0xf));
set_hsr_stag_HSR_Ver(hsr_stag, hsrVer);
/* From HSRv1 on we have separate supervision sequence numbers. */
spin_lock_irqsave(&master->hsr->seqnr_lock, irqflags);
if (hsrVer > 0) {
hsr_stag->sequence_nr = htons(master->hsr->sup_sequence_nr);
hsr_tag->sequence_nr = htons(master->hsr->sequence_nr);
master->hsr->sup_sequence_nr++;
master->hsr->sequence_nr++;
} else {
hsr_stag->sequence_nr = htons(master->hsr->sequence_nr);
master->hsr->sequence_nr++;
}
spin_unlock_irqrestore(&master->hsr->seqnr_lock, irqflags);
hsr_stag->HSR_TLV_Type = type;
/* TODO: Why 12 in HSRv0? */
hsr_stag->HSR_TLV_Length = hsrVer ? sizeof(struct hsr_sup_payload) : 12;
/* Payload: MacAddressA */
hsr_sp = skb_put(skb, sizeof(struct hsr_sup_payload));
ether_addr_copy(hsr_sp->MacAddressA, master->dev->dev_addr);
if (skb_put_padto(skb, ETH_ZLEN + HSR_HLEN))
return;
hsr_forward_skb(skb, master);
return;
out:
WARN_ONCE(1, "HSR: Could not send supervision frame\n");
kfree_skb(skb);
}
/* Announce (supervision frame) timer function
*/
static void hsr_announce(struct timer_list *t)
{
struct hsr_priv *hsr;
struct hsr_port *master;
hsr = from_timer(hsr, t, announce_timer);
rcu_read_lock();
master = hsr_port_get_hsr(hsr, HSR_PT_MASTER);
if (hsr->announce_count < 3 && hsr->protVersion == 0) {
send_hsr_supervision_frame(master, HSR_TLV_ANNOUNCE,
hsr->protVersion);
hsr->announce_count++;
hsr->announce_timer.expires = jiffies +
msecs_to_jiffies(HSR_ANNOUNCE_INTERVAL);
} else {
send_hsr_supervision_frame(master, HSR_TLV_LIFE_CHECK,
hsr->protVersion);
hsr->announce_timer.expires = jiffies +
msecs_to_jiffies(HSR_LIFE_CHECK_INTERVAL);
}
if (is_admin_up(master->dev))
add_timer(&hsr->announce_timer);
rcu_read_unlock();
}
/* According to comments in the declaration of struct net_device, this function
* is "Called from unregister, can be used to call free_netdev". Ok then...
*/
static void hsr_dev_destroy(struct net_device *hsr_dev)
{
struct hsr_priv *hsr;
struct hsr_port *port;
hsr = netdev_priv(hsr_dev);
rtnl_lock();
hsr_for_each_port(hsr, port)
hsr_del_port(port);
rtnl_unlock();
del_timer_sync(&hsr->prune_timer);
del_timer_sync(&hsr->announce_timer);
synchronize_rcu();
}
static const struct net_device_ops hsr_device_ops = {
.ndo_change_mtu = hsr_dev_change_mtu,
.ndo_open = hsr_dev_open,
.ndo_stop = hsr_dev_close,
.ndo_start_xmit = hsr_dev_xmit,
.ndo_fix_features = hsr_fix_features,
};
static struct device_type hsr_type = {
.name = "hsr",
};
void hsr_dev_setup(struct net_device *dev)
{
eth_hw_addr_random(dev);
ether_setup(dev);
dev->min_mtu = 0;
dev->header_ops = &hsr_header_ops;
dev->netdev_ops = &hsr_device_ops;
SET_NETDEV_DEVTYPE(dev, &hsr_type);
dev->priv_flags |= IFF_NO_QUEUE;
dev->needs_free_netdev = true;
dev->priv_destructor = hsr_dev_destroy;
dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_HIGHDMA |
NETIF_F_GSO_MASK | NETIF_F_HW_CSUM |
NETIF_F_HW_VLAN_CTAG_TX;
dev->features = dev->hw_features;
/* Prevent recursive tx locking */
dev->features |= NETIF_F_LLTX;
/* VLAN on top of HSR needs testing and probably some work on
* hsr_header_create() etc.
*/
dev->features |= NETIF_F_VLAN_CHALLENGED;
/* Not sure about this. Taken from bridge code. netdev_features.h says
* it means "Does not change network namespaces".
*/
dev->features |= NETIF_F_NETNS_LOCAL;
}
/* Return true if dev is a HSR master; return false otherwise.
*/
inline bool is_hsr_master(struct net_device *dev)
{
return (dev->netdev_ops->ndo_start_xmit == hsr_dev_xmit);
}
/* Default multicast address for HSR Supervision frames */
static const unsigned char def_multicast_addr[ETH_ALEN] __aligned(2) = {
0x01, 0x15, 0x4e, 0x00, 0x01, 0x00
};
int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2],
unsigned char multicast_spec, u8 protocol_version)
{
struct hsr_priv *hsr;
struct hsr_port *port;
int res;
hsr = netdev_priv(hsr_dev);
INIT_LIST_HEAD(&hsr->ports);
INIT_LIST_HEAD(&hsr->node_db);
INIT_LIST_HEAD(&hsr->self_node_db);
ether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr);
/* Make sure we recognize frames from ourselves in hsr_rcv() */
res = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr,
slave[1]->dev_addr);
if (res < 0)
return res;
spin_lock_init(&hsr->seqnr_lock);
/* Overflow soon to find bugs easier: */
hsr->sequence_nr = HSR_SEQNR_START;
hsr->sup_sequence_nr = HSR_SUP_SEQNR_START;
timer_setup(&hsr->announce_timer, hsr_announce, 0);
timer_setup(&hsr->prune_timer, hsr_prune_nodes, 0);
ether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr);
hsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec;
hsr->protVersion = protocol_version;
/* FIXME: should I modify the value of these?
*
* - hsr_dev->flags - i.e.
* IFF_MASTER/SLAVE?
* - hsr_dev->priv_flags - i.e.
* IFF_EBRIDGE?
* IFF_TX_SKB_SHARING?
* IFF_HSR_MASTER/SLAVE?
*/
/* Make sure the 1st call to netif_carrier_on() gets through */
netif_carrier_off(hsr_dev);
res = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER);
if (res)
goto err_add_port;
res = register_netdevice(hsr_dev);
if (res)
goto fail;
res = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A);
if (res)
goto fail;
res = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B);
if (res)
goto fail;
mod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD));
return 0;
fail:
hsr_for_each_port(hsr, port)
hsr_del_port(port);
err_add_port:
hsr_del_node(&hsr->self_node_db);
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_1162_0 |
crossvul-cpp_data_good_653_0 | /*
* Serial Attached SCSI (SAS) Expander discovery and configuration
*
* Copyright (C) 2005 Adaptec, Inc. All rights reserved.
* Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com>
*
* This file is licensed under GPLv2.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/scatterlist.h>
#include <linux/blkdev.h>
#include <linux/slab.h>
#include "sas_internal.h"
#include <scsi/sas_ata.h>
#include <scsi/scsi_transport.h>
#include <scsi/scsi_transport_sas.h>
#include "../scsi_sas_internal.h"
static int sas_discover_expander(struct domain_device *dev);
static int sas_configure_routing(struct domain_device *dev, u8 *sas_addr);
static int sas_configure_phy(struct domain_device *dev, int phy_id,
u8 *sas_addr, int include);
static int sas_disable_routing(struct domain_device *dev, u8 *sas_addr);
/* ---------- SMP task management ---------- */
static void smp_task_timedout(struct timer_list *t)
{
struct sas_task_slow *slow = from_timer(slow, t, timer);
struct sas_task *task = slow->task;
unsigned long flags;
spin_lock_irqsave(&task->task_state_lock, flags);
if (!(task->task_state_flags & SAS_TASK_STATE_DONE))
task->task_state_flags |= SAS_TASK_STATE_ABORTED;
spin_unlock_irqrestore(&task->task_state_lock, flags);
complete(&task->slow_task->completion);
}
static void smp_task_done(struct sas_task *task)
{
if (!del_timer(&task->slow_task->timer))
return;
complete(&task->slow_task->completion);
}
/* Give it some long enough timeout. In seconds. */
#define SMP_TIMEOUT 10
static int smp_execute_task_sg(struct domain_device *dev,
struct scatterlist *req, struct scatterlist *resp)
{
int res, retry;
struct sas_task *task = NULL;
struct sas_internal *i =
to_sas_internal(dev->port->ha->core.shost->transportt);
mutex_lock(&dev->ex_dev.cmd_mutex);
for (retry = 0; retry < 3; retry++) {
if (test_bit(SAS_DEV_GONE, &dev->state)) {
res = -ECOMM;
break;
}
task = sas_alloc_slow_task(GFP_KERNEL);
if (!task) {
res = -ENOMEM;
break;
}
task->dev = dev;
task->task_proto = dev->tproto;
task->smp_task.smp_req = *req;
task->smp_task.smp_resp = *resp;
task->task_done = smp_task_done;
task->slow_task->timer.function = smp_task_timedout;
task->slow_task->timer.expires = jiffies + SMP_TIMEOUT*HZ;
add_timer(&task->slow_task->timer);
res = i->dft->lldd_execute_task(task, GFP_KERNEL);
if (res) {
del_timer(&task->slow_task->timer);
SAS_DPRINTK("executing SMP task failed:%d\n", res);
break;
}
wait_for_completion(&task->slow_task->completion);
res = -ECOMM;
if ((task->task_state_flags & SAS_TASK_STATE_ABORTED)) {
SAS_DPRINTK("smp task timed out or aborted\n");
i->dft->lldd_abort_task(task);
if (!(task->task_state_flags & SAS_TASK_STATE_DONE)) {
SAS_DPRINTK("SMP task aborted and not done\n");
break;
}
}
if (task->task_status.resp == SAS_TASK_COMPLETE &&
task->task_status.stat == SAM_STAT_GOOD) {
res = 0;
break;
}
if (task->task_status.resp == SAS_TASK_COMPLETE &&
task->task_status.stat == SAS_DATA_UNDERRUN) {
/* no error, but return the number of bytes of
* underrun */
res = task->task_status.residual;
break;
}
if (task->task_status.resp == SAS_TASK_COMPLETE &&
task->task_status.stat == SAS_DATA_OVERRUN) {
res = -EMSGSIZE;
break;
}
if (task->task_status.resp == SAS_TASK_UNDELIVERED &&
task->task_status.stat == SAS_DEVICE_UNKNOWN)
break;
else {
SAS_DPRINTK("%s: task to dev %016llx response: 0x%x "
"status 0x%x\n", __func__,
SAS_ADDR(dev->sas_addr),
task->task_status.resp,
task->task_status.stat);
sas_free_task(task);
task = NULL;
}
}
mutex_unlock(&dev->ex_dev.cmd_mutex);
BUG_ON(retry == 3 && task != NULL);
sas_free_task(task);
return res;
}
static int smp_execute_task(struct domain_device *dev, void *req, int req_size,
void *resp, int resp_size)
{
struct scatterlist req_sg;
struct scatterlist resp_sg;
sg_init_one(&req_sg, req, req_size);
sg_init_one(&resp_sg, resp, resp_size);
return smp_execute_task_sg(dev, &req_sg, &resp_sg);
}
/* ---------- Allocations ---------- */
static inline void *alloc_smp_req(int size)
{
u8 *p = kzalloc(size, GFP_KERNEL);
if (p)
p[0] = SMP_REQUEST;
return p;
}
static inline void *alloc_smp_resp(int size)
{
return kzalloc(size, GFP_KERNEL);
}
static char sas_route_char(struct domain_device *dev, struct ex_phy *phy)
{
switch (phy->routing_attr) {
case TABLE_ROUTING:
if (dev->ex_dev.t2t_supp)
return 'U';
else
return 'T';
case DIRECT_ROUTING:
return 'D';
case SUBTRACTIVE_ROUTING:
return 'S';
default:
return '?';
}
}
static enum sas_device_type to_dev_type(struct discover_resp *dr)
{
/* This is detecting a failure to transmit initial dev to host
* FIS as described in section J.5 of sas-2 r16
*/
if (dr->attached_dev_type == SAS_PHY_UNUSED && dr->attached_sata_dev &&
dr->linkrate >= SAS_LINK_RATE_1_5_GBPS)
return SAS_SATA_PENDING;
else
return dr->attached_dev_type;
}
static void sas_set_ex_phy(struct domain_device *dev, int phy_id, void *rsp)
{
enum sas_device_type dev_type;
enum sas_linkrate linkrate;
u8 sas_addr[SAS_ADDR_SIZE];
struct smp_resp *resp = rsp;
struct discover_resp *dr = &resp->disc;
struct sas_ha_struct *ha = dev->port->ha;
struct expander_device *ex = &dev->ex_dev;
struct ex_phy *phy = &ex->ex_phy[phy_id];
struct sas_rphy *rphy = dev->rphy;
bool new_phy = !phy->phy;
char *type;
if (new_phy) {
if (WARN_ON_ONCE(test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)))
return;
phy->phy = sas_phy_alloc(&rphy->dev, phy_id);
/* FIXME: error_handling */
BUG_ON(!phy->phy);
}
switch (resp->result) {
case SMP_RESP_PHY_VACANT:
phy->phy_state = PHY_VACANT;
break;
default:
phy->phy_state = PHY_NOT_PRESENT;
break;
case SMP_RESP_FUNC_ACC:
phy->phy_state = PHY_EMPTY; /* do not know yet */
break;
}
/* check if anything important changed to squelch debug */
dev_type = phy->attached_dev_type;
linkrate = phy->linkrate;
memcpy(sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE);
/* Handle vacant phy - rest of dr data is not valid so skip it */
if (phy->phy_state == PHY_VACANT) {
memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE);
phy->attached_dev_type = SAS_PHY_UNUSED;
if (!test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) {
phy->phy_id = phy_id;
goto skip;
} else
goto out;
}
phy->attached_dev_type = to_dev_type(dr);
if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state))
goto out;
phy->phy_id = phy_id;
phy->linkrate = dr->linkrate;
phy->attached_sata_host = dr->attached_sata_host;
phy->attached_sata_dev = dr->attached_sata_dev;
phy->attached_sata_ps = dr->attached_sata_ps;
phy->attached_iproto = dr->iproto << 1;
phy->attached_tproto = dr->tproto << 1;
/* help some expanders that fail to zero sas_address in the 'no
* device' case
*/
if (phy->attached_dev_type == SAS_PHY_UNUSED ||
phy->linkrate < SAS_LINK_RATE_1_5_GBPS)
memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE);
else
memcpy(phy->attached_sas_addr, dr->attached_sas_addr, SAS_ADDR_SIZE);
phy->attached_phy_id = dr->attached_phy_id;
phy->phy_change_count = dr->change_count;
phy->routing_attr = dr->routing_attr;
phy->virtual = dr->virtual;
phy->last_da_index = -1;
phy->phy->identify.sas_address = SAS_ADDR(phy->attached_sas_addr);
phy->phy->identify.device_type = dr->attached_dev_type;
phy->phy->identify.initiator_port_protocols = phy->attached_iproto;
phy->phy->identify.target_port_protocols = phy->attached_tproto;
if (!phy->attached_tproto && dr->attached_sata_dev)
phy->phy->identify.target_port_protocols = SAS_PROTOCOL_SATA;
phy->phy->identify.phy_identifier = phy_id;
phy->phy->minimum_linkrate_hw = dr->hmin_linkrate;
phy->phy->maximum_linkrate_hw = dr->hmax_linkrate;
phy->phy->minimum_linkrate = dr->pmin_linkrate;
phy->phy->maximum_linkrate = dr->pmax_linkrate;
phy->phy->negotiated_linkrate = phy->linkrate;
skip:
if (new_phy)
if (sas_phy_add(phy->phy)) {
sas_phy_free(phy->phy);
return;
}
out:
switch (phy->attached_dev_type) {
case SAS_SATA_PENDING:
type = "stp pending";
break;
case SAS_PHY_UNUSED:
type = "no device";
break;
case SAS_END_DEVICE:
if (phy->attached_iproto) {
if (phy->attached_tproto)
type = "host+target";
else
type = "host";
} else {
if (dr->attached_sata_dev)
type = "stp";
else
type = "ssp";
}
break;
case SAS_EDGE_EXPANDER_DEVICE:
case SAS_FANOUT_EXPANDER_DEVICE:
type = "smp";
break;
default:
type = "unknown";
}
/* this routine is polled by libata error recovery so filter
* unimportant messages
*/
if (new_phy || phy->attached_dev_type != dev_type ||
phy->linkrate != linkrate ||
SAS_ADDR(phy->attached_sas_addr) != SAS_ADDR(sas_addr))
/* pass */;
else
return;
/* if the attached device type changed and ata_eh is active,
* make sure we run revalidation when eh completes (see:
* sas_enable_revalidation)
*/
if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state))
set_bit(DISCE_REVALIDATE_DOMAIN, &dev->port->disc.pending);
SAS_DPRINTK("%sex %016llx phy%02d:%c:%X attached: %016llx (%s)\n",
test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state) ? "ata: " : "",
SAS_ADDR(dev->sas_addr), phy->phy_id,
sas_route_char(dev, phy), phy->linkrate,
SAS_ADDR(phy->attached_sas_addr), type);
}
/* check if we have an existing attached ata device on this expander phy */
struct domain_device *sas_ex_to_ata(struct domain_device *ex_dev, int phy_id)
{
struct ex_phy *ex_phy = &ex_dev->ex_dev.ex_phy[phy_id];
struct domain_device *dev;
struct sas_rphy *rphy;
if (!ex_phy->port)
return NULL;
rphy = ex_phy->port->rphy;
if (!rphy)
return NULL;
dev = sas_find_dev_by_rphy(rphy);
if (dev && dev_is_sata(dev))
return dev;
return NULL;
}
#define DISCOVER_REQ_SIZE 16
#define DISCOVER_RESP_SIZE 56
static int sas_ex_phy_discover_helper(struct domain_device *dev, u8 *disc_req,
u8 *disc_resp, int single)
{
struct discover_resp *dr;
int res;
disc_req[9] = single;
res = smp_execute_task(dev, disc_req, DISCOVER_REQ_SIZE,
disc_resp, DISCOVER_RESP_SIZE);
if (res)
return res;
dr = &((struct smp_resp *)disc_resp)->disc;
if (memcmp(dev->sas_addr, dr->attached_sas_addr, SAS_ADDR_SIZE) == 0) {
sas_printk("Found loopback topology, just ignore it!\n");
return 0;
}
sas_set_ex_phy(dev, single, disc_resp);
return 0;
}
int sas_ex_phy_discover(struct domain_device *dev, int single)
{
struct expander_device *ex = &dev->ex_dev;
int res = 0;
u8 *disc_req;
u8 *disc_resp;
disc_req = alloc_smp_req(DISCOVER_REQ_SIZE);
if (!disc_req)
return -ENOMEM;
disc_resp = alloc_smp_resp(DISCOVER_RESP_SIZE);
if (!disc_resp) {
kfree(disc_req);
return -ENOMEM;
}
disc_req[1] = SMP_DISCOVER;
if (0 <= single && single < ex->num_phys) {
res = sas_ex_phy_discover_helper(dev, disc_req, disc_resp, single);
} else {
int i;
for (i = 0; i < ex->num_phys; i++) {
res = sas_ex_phy_discover_helper(dev, disc_req,
disc_resp, i);
if (res)
goto out_err;
}
}
out_err:
kfree(disc_resp);
kfree(disc_req);
return res;
}
static int sas_expander_discover(struct domain_device *dev)
{
struct expander_device *ex = &dev->ex_dev;
int res = -ENOMEM;
ex->ex_phy = kzalloc(sizeof(*ex->ex_phy)*ex->num_phys, GFP_KERNEL);
if (!ex->ex_phy)
return -ENOMEM;
res = sas_ex_phy_discover(dev, -1);
if (res)
goto out_err;
return 0;
out_err:
kfree(ex->ex_phy);
ex->ex_phy = NULL;
return res;
}
#define MAX_EXPANDER_PHYS 128
static void ex_assign_report_general(struct domain_device *dev,
struct smp_resp *resp)
{
struct report_general_resp *rg = &resp->rg;
dev->ex_dev.ex_change_count = be16_to_cpu(rg->change_count);
dev->ex_dev.max_route_indexes = be16_to_cpu(rg->route_indexes);
dev->ex_dev.num_phys = min(rg->num_phys, (u8)MAX_EXPANDER_PHYS);
dev->ex_dev.t2t_supp = rg->t2t_supp;
dev->ex_dev.conf_route_table = rg->conf_route_table;
dev->ex_dev.configuring = rg->configuring;
memcpy(dev->ex_dev.enclosure_logical_id, rg->enclosure_logical_id, 8);
}
#define RG_REQ_SIZE 8
#define RG_RESP_SIZE 32
static int sas_ex_general(struct domain_device *dev)
{
u8 *rg_req;
struct smp_resp *rg_resp;
int res;
int i;
rg_req = alloc_smp_req(RG_REQ_SIZE);
if (!rg_req)
return -ENOMEM;
rg_resp = alloc_smp_resp(RG_RESP_SIZE);
if (!rg_resp) {
kfree(rg_req);
return -ENOMEM;
}
rg_req[1] = SMP_REPORT_GENERAL;
for (i = 0; i < 5; i++) {
res = smp_execute_task(dev, rg_req, RG_REQ_SIZE, rg_resp,
RG_RESP_SIZE);
if (res) {
SAS_DPRINTK("RG to ex %016llx failed:0x%x\n",
SAS_ADDR(dev->sas_addr), res);
goto out;
} else if (rg_resp->result != SMP_RESP_FUNC_ACC) {
SAS_DPRINTK("RG:ex %016llx returned SMP result:0x%x\n",
SAS_ADDR(dev->sas_addr), rg_resp->result);
res = rg_resp->result;
goto out;
}
ex_assign_report_general(dev, rg_resp);
if (dev->ex_dev.configuring) {
SAS_DPRINTK("RG: ex %llx self-configuring...\n",
SAS_ADDR(dev->sas_addr));
schedule_timeout_interruptible(5*HZ);
} else
break;
}
out:
kfree(rg_req);
kfree(rg_resp);
return res;
}
static void ex_assign_manuf_info(struct domain_device *dev, void
*_mi_resp)
{
u8 *mi_resp = _mi_resp;
struct sas_rphy *rphy = dev->rphy;
struct sas_expander_device *edev = rphy_to_expander_device(rphy);
memcpy(edev->vendor_id, mi_resp + 12, SAS_EXPANDER_VENDOR_ID_LEN);
memcpy(edev->product_id, mi_resp + 20, SAS_EXPANDER_PRODUCT_ID_LEN);
memcpy(edev->product_rev, mi_resp + 36,
SAS_EXPANDER_PRODUCT_REV_LEN);
if (mi_resp[8] & 1) {
memcpy(edev->component_vendor_id, mi_resp + 40,
SAS_EXPANDER_COMPONENT_VENDOR_ID_LEN);
edev->component_id = mi_resp[48] << 8 | mi_resp[49];
edev->component_revision_id = mi_resp[50];
}
}
#define MI_REQ_SIZE 8
#define MI_RESP_SIZE 64
static int sas_ex_manuf_info(struct domain_device *dev)
{
u8 *mi_req;
u8 *mi_resp;
int res;
mi_req = alloc_smp_req(MI_REQ_SIZE);
if (!mi_req)
return -ENOMEM;
mi_resp = alloc_smp_resp(MI_RESP_SIZE);
if (!mi_resp) {
kfree(mi_req);
return -ENOMEM;
}
mi_req[1] = SMP_REPORT_MANUF_INFO;
res = smp_execute_task(dev, mi_req, MI_REQ_SIZE, mi_resp,MI_RESP_SIZE);
if (res) {
SAS_DPRINTK("MI: ex %016llx failed:0x%x\n",
SAS_ADDR(dev->sas_addr), res);
goto out;
} else if (mi_resp[2] != SMP_RESP_FUNC_ACC) {
SAS_DPRINTK("MI ex %016llx returned SMP result:0x%x\n",
SAS_ADDR(dev->sas_addr), mi_resp[2]);
goto out;
}
ex_assign_manuf_info(dev, mi_resp);
out:
kfree(mi_req);
kfree(mi_resp);
return res;
}
#define PC_REQ_SIZE 44
#define PC_RESP_SIZE 8
int sas_smp_phy_control(struct domain_device *dev, int phy_id,
enum phy_func phy_func,
struct sas_phy_linkrates *rates)
{
u8 *pc_req;
u8 *pc_resp;
int res;
pc_req = alloc_smp_req(PC_REQ_SIZE);
if (!pc_req)
return -ENOMEM;
pc_resp = alloc_smp_resp(PC_RESP_SIZE);
if (!pc_resp) {
kfree(pc_req);
return -ENOMEM;
}
pc_req[1] = SMP_PHY_CONTROL;
pc_req[9] = phy_id;
pc_req[10]= phy_func;
if (rates) {
pc_req[32] = rates->minimum_linkrate << 4;
pc_req[33] = rates->maximum_linkrate << 4;
}
res = smp_execute_task(dev, pc_req, PC_REQ_SIZE, pc_resp,PC_RESP_SIZE);
kfree(pc_resp);
kfree(pc_req);
return res;
}
static void sas_ex_disable_phy(struct domain_device *dev, int phy_id)
{
struct expander_device *ex = &dev->ex_dev;
struct ex_phy *phy = &ex->ex_phy[phy_id];
sas_smp_phy_control(dev, phy_id, PHY_FUNC_DISABLE, NULL);
phy->linkrate = SAS_PHY_DISABLED;
}
static void sas_ex_disable_port(struct domain_device *dev, u8 *sas_addr)
{
struct expander_device *ex = &dev->ex_dev;
int i;
for (i = 0; i < ex->num_phys; i++) {
struct ex_phy *phy = &ex->ex_phy[i];
if (phy->phy_state == PHY_VACANT ||
phy->phy_state == PHY_NOT_PRESENT)
continue;
if (SAS_ADDR(phy->attached_sas_addr) == SAS_ADDR(sas_addr))
sas_ex_disable_phy(dev, i);
}
}
static int sas_dev_present_in_domain(struct asd_sas_port *port,
u8 *sas_addr)
{
struct domain_device *dev;
if (SAS_ADDR(port->sas_addr) == SAS_ADDR(sas_addr))
return 1;
list_for_each_entry(dev, &port->dev_list, dev_list_node) {
if (SAS_ADDR(dev->sas_addr) == SAS_ADDR(sas_addr))
return 1;
}
return 0;
}
#define RPEL_REQ_SIZE 16
#define RPEL_RESP_SIZE 32
int sas_smp_get_phy_events(struct sas_phy *phy)
{
int res;
u8 *req;
u8 *resp;
struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent);
struct domain_device *dev = sas_find_dev_by_rphy(rphy);
req = alloc_smp_req(RPEL_REQ_SIZE);
if (!req)
return -ENOMEM;
resp = alloc_smp_resp(RPEL_RESP_SIZE);
if (!resp) {
kfree(req);
return -ENOMEM;
}
req[1] = SMP_REPORT_PHY_ERR_LOG;
req[9] = phy->number;
res = smp_execute_task(dev, req, RPEL_REQ_SIZE,
resp, RPEL_RESP_SIZE);
if (!res)
goto out;
phy->invalid_dword_count = scsi_to_u32(&resp[12]);
phy->running_disparity_error_count = scsi_to_u32(&resp[16]);
phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]);
phy->phy_reset_problem_count = scsi_to_u32(&resp[24]);
out:
kfree(req);
kfree(resp);
return res;
}
#ifdef CONFIG_SCSI_SAS_ATA
#define RPS_REQ_SIZE 16
#define RPS_RESP_SIZE 60
int sas_get_report_phy_sata(struct domain_device *dev, int phy_id,
struct smp_resp *rps_resp)
{
int res;
u8 *rps_req = alloc_smp_req(RPS_REQ_SIZE);
u8 *resp = (u8 *)rps_resp;
if (!rps_req)
return -ENOMEM;
rps_req[1] = SMP_REPORT_PHY_SATA;
rps_req[9] = phy_id;
res = smp_execute_task(dev, rps_req, RPS_REQ_SIZE,
rps_resp, RPS_RESP_SIZE);
/* 0x34 is the FIS type for the D2H fis. There's a potential
* standards cockup here. sas-2 explicitly specifies the FIS
* should be encoded so that FIS type is in resp[24].
* However, some expanders endian reverse this. Undo the
* reversal here */
if (!res && resp[27] == 0x34 && resp[24] != 0x34) {
int i;
for (i = 0; i < 5; i++) {
int j = 24 + (i*4);
u8 a, b;
a = resp[j + 0];
b = resp[j + 1];
resp[j + 0] = resp[j + 3];
resp[j + 1] = resp[j + 2];
resp[j + 2] = b;
resp[j + 3] = a;
}
}
kfree(rps_req);
return res;
}
#endif
static void sas_ex_get_linkrate(struct domain_device *parent,
struct domain_device *child,
struct ex_phy *parent_phy)
{
struct expander_device *parent_ex = &parent->ex_dev;
struct sas_port *port;
int i;
child->pathways = 0;
port = parent_phy->port;
for (i = 0; i < parent_ex->num_phys; i++) {
struct ex_phy *phy = &parent_ex->ex_phy[i];
if (phy->phy_state == PHY_VACANT ||
phy->phy_state == PHY_NOT_PRESENT)
continue;
if (SAS_ADDR(phy->attached_sas_addr) ==
SAS_ADDR(child->sas_addr)) {
child->min_linkrate = min(parent->min_linkrate,
phy->linkrate);
child->max_linkrate = max(parent->max_linkrate,
phy->linkrate);
child->pathways++;
sas_port_add_phy(port, phy->phy);
}
}
child->linkrate = min(parent_phy->linkrate, child->max_linkrate);
child->pathways = min(child->pathways, parent->pathways);
}
static struct domain_device *sas_ex_discover_end_dev(
struct domain_device *parent, int phy_id)
{
struct expander_device *parent_ex = &parent->ex_dev;
struct ex_phy *phy = &parent_ex->ex_phy[phy_id];
struct domain_device *child = NULL;
struct sas_rphy *rphy;
int res;
if (phy->attached_sata_host || phy->attached_sata_ps)
return NULL;
child = sas_alloc_device();
if (!child)
return NULL;
kref_get(&parent->kref);
child->parent = parent;
child->port = parent->port;
child->iproto = phy->attached_iproto;
memcpy(child->sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE);
sas_hash_addr(child->hashed_sas_addr, child->sas_addr);
if (!phy->port) {
phy->port = sas_port_alloc(&parent->rphy->dev, phy_id);
if (unlikely(!phy->port))
goto out_err;
if (unlikely(sas_port_add(phy->port) != 0)) {
sas_port_free(phy->port);
goto out_err;
}
}
sas_ex_get_linkrate(parent, child, phy);
sas_device_set_phy(child, phy->port);
#ifdef CONFIG_SCSI_SAS_ATA
if ((phy->attached_tproto & SAS_PROTOCOL_STP) || phy->attached_sata_dev) {
res = sas_get_ata_info(child, phy);
if (res)
goto out_free;
sas_init_dev(child);
res = sas_ata_init(child);
if (res)
goto out_free;
rphy = sas_end_device_alloc(phy->port);
if (!rphy)
goto out_free;
child->rphy = rphy;
get_device(&rphy->dev);
list_add_tail(&child->disco_list_node, &parent->port->disco_list);
res = sas_discover_sata(child);
if (res) {
SAS_DPRINTK("sas_discover_sata() for device %16llx at "
"%016llx:0x%x returned 0x%x\n",
SAS_ADDR(child->sas_addr),
SAS_ADDR(parent->sas_addr), phy_id, res);
goto out_list_del;
}
} else
#endif
if (phy->attached_tproto & SAS_PROTOCOL_SSP) {
child->dev_type = SAS_END_DEVICE;
rphy = sas_end_device_alloc(phy->port);
/* FIXME: error handling */
if (unlikely(!rphy))
goto out_free;
child->tproto = phy->attached_tproto;
sas_init_dev(child);
child->rphy = rphy;
get_device(&rphy->dev);
sas_fill_in_rphy(child, rphy);
list_add_tail(&child->disco_list_node, &parent->port->disco_list);
res = sas_discover_end_dev(child);
if (res) {
SAS_DPRINTK("sas_discover_end_dev() for device %16llx "
"at %016llx:0x%x returned 0x%x\n",
SAS_ADDR(child->sas_addr),
SAS_ADDR(parent->sas_addr), phy_id, res);
goto out_list_del;
}
} else {
SAS_DPRINTK("target proto 0x%x at %016llx:0x%x not handled\n",
phy->attached_tproto, SAS_ADDR(parent->sas_addr),
phy_id);
goto out_free;
}
list_add_tail(&child->siblings, &parent_ex->children);
return child;
out_list_del:
sas_rphy_free(child->rphy);
list_del(&child->disco_list_node);
spin_lock_irq(&parent->port->dev_list_lock);
list_del(&child->dev_list_node);
spin_unlock_irq(&parent->port->dev_list_lock);
out_free:
sas_port_delete(phy->port);
out_err:
phy->port = NULL;
sas_put_device(child);
return NULL;
}
/* See if this phy is part of a wide port */
static bool sas_ex_join_wide_port(struct domain_device *parent, int phy_id)
{
struct ex_phy *phy = &parent->ex_dev.ex_phy[phy_id];
int i;
for (i = 0; i < parent->ex_dev.num_phys; i++) {
struct ex_phy *ephy = &parent->ex_dev.ex_phy[i];
if (ephy == phy)
continue;
if (!memcmp(phy->attached_sas_addr, ephy->attached_sas_addr,
SAS_ADDR_SIZE) && ephy->port) {
sas_port_add_phy(ephy->port, phy->phy);
phy->port = ephy->port;
phy->phy_state = PHY_DEVICE_DISCOVERED;
return true;
}
}
return false;
}
static struct domain_device *sas_ex_discover_expander(
struct domain_device *parent, int phy_id)
{
struct sas_expander_device *parent_ex = rphy_to_expander_device(parent->rphy);
struct ex_phy *phy = &parent->ex_dev.ex_phy[phy_id];
struct domain_device *child = NULL;
struct sas_rphy *rphy;
struct sas_expander_device *edev;
struct asd_sas_port *port;
int res;
if (phy->routing_attr == DIRECT_ROUTING) {
SAS_DPRINTK("ex %016llx:0x%x:D <--> ex %016llx:0x%x is not "
"allowed\n",
SAS_ADDR(parent->sas_addr), phy_id,
SAS_ADDR(phy->attached_sas_addr),
phy->attached_phy_id);
return NULL;
}
child = sas_alloc_device();
if (!child)
return NULL;
phy->port = sas_port_alloc(&parent->rphy->dev, phy_id);
/* FIXME: better error handling */
BUG_ON(sas_port_add(phy->port) != 0);
switch (phy->attached_dev_type) {
case SAS_EDGE_EXPANDER_DEVICE:
rphy = sas_expander_alloc(phy->port,
SAS_EDGE_EXPANDER_DEVICE);
break;
case SAS_FANOUT_EXPANDER_DEVICE:
rphy = sas_expander_alloc(phy->port,
SAS_FANOUT_EXPANDER_DEVICE);
break;
default:
rphy = NULL; /* shut gcc up */
BUG();
}
port = parent->port;
child->rphy = rphy;
get_device(&rphy->dev);
edev = rphy_to_expander_device(rphy);
child->dev_type = phy->attached_dev_type;
kref_get(&parent->kref);
child->parent = parent;
child->port = port;
child->iproto = phy->attached_iproto;
child->tproto = phy->attached_tproto;
memcpy(child->sas_addr, phy->attached_sas_addr, SAS_ADDR_SIZE);
sas_hash_addr(child->hashed_sas_addr, child->sas_addr);
sas_ex_get_linkrate(parent, child, phy);
edev->level = parent_ex->level + 1;
parent->port->disc.max_level = max(parent->port->disc.max_level,
edev->level);
sas_init_dev(child);
sas_fill_in_rphy(child, rphy);
sas_rphy_add(rphy);
spin_lock_irq(&parent->port->dev_list_lock);
list_add_tail(&child->dev_list_node, &parent->port->dev_list);
spin_unlock_irq(&parent->port->dev_list_lock);
res = sas_discover_expander(child);
if (res) {
sas_rphy_delete(rphy);
spin_lock_irq(&parent->port->dev_list_lock);
list_del(&child->dev_list_node);
spin_unlock_irq(&parent->port->dev_list_lock);
sas_put_device(child);
return NULL;
}
list_add_tail(&child->siblings, &parent->ex_dev.children);
return child;
}
static int sas_ex_discover_dev(struct domain_device *dev, int phy_id)
{
struct expander_device *ex = &dev->ex_dev;
struct ex_phy *ex_phy = &ex->ex_phy[phy_id];
struct domain_device *child = NULL;
int res = 0;
/* Phy state */
if (ex_phy->linkrate == SAS_SATA_SPINUP_HOLD) {
if (!sas_smp_phy_control(dev, phy_id, PHY_FUNC_LINK_RESET, NULL))
res = sas_ex_phy_discover(dev, phy_id);
if (res)
return res;
}
/* Parent and domain coherency */
if (!dev->parent && (SAS_ADDR(ex_phy->attached_sas_addr) ==
SAS_ADDR(dev->port->sas_addr))) {
sas_add_parent_port(dev, phy_id);
return 0;
}
if (dev->parent && (SAS_ADDR(ex_phy->attached_sas_addr) ==
SAS_ADDR(dev->parent->sas_addr))) {
sas_add_parent_port(dev, phy_id);
if (ex_phy->routing_attr == TABLE_ROUTING)
sas_configure_phy(dev, phy_id, dev->port->sas_addr, 1);
return 0;
}
if (sas_dev_present_in_domain(dev->port, ex_phy->attached_sas_addr))
sas_ex_disable_port(dev, ex_phy->attached_sas_addr);
if (ex_phy->attached_dev_type == SAS_PHY_UNUSED) {
if (ex_phy->routing_attr == DIRECT_ROUTING) {
memset(ex_phy->attached_sas_addr, 0, SAS_ADDR_SIZE);
sas_configure_routing(dev, ex_phy->attached_sas_addr);
}
return 0;
} else if (ex_phy->linkrate == SAS_LINK_RATE_UNKNOWN)
return 0;
if (ex_phy->attached_dev_type != SAS_END_DEVICE &&
ex_phy->attached_dev_type != SAS_FANOUT_EXPANDER_DEVICE &&
ex_phy->attached_dev_type != SAS_EDGE_EXPANDER_DEVICE &&
ex_phy->attached_dev_type != SAS_SATA_PENDING) {
SAS_DPRINTK("unknown device type(0x%x) attached to ex %016llx "
"phy 0x%x\n", ex_phy->attached_dev_type,
SAS_ADDR(dev->sas_addr),
phy_id);
return 0;
}
res = sas_configure_routing(dev, ex_phy->attached_sas_addr);
if (res) {
SAS_DPRINTK("configure routing for dev %016llx "
"reported 0x%x. Forgotten\n",
SAS_ADDR(ex_phy->attached_sas_addr), res);
sas_disable_routing(dev, ex_phy->attached_sas_addr);
return res;
}
if (sas_ex_join_wide_port(dev, phy_id)) {
SAS_DPRINTK("Attaching ex phy%d to wide port %016llx\n",
phy_id, SAS_ADDR(ex_phy->attached_sas_addr));
return res;
}
switch (ex_phy->attached_dev_type) {
case SAS_END_DEVICE:
case SAS_SATA_PENDING:
child = sas_ex_discover_end_dev(dev, phy_id);
break;
case SAS_FANOUT_EXPANDER_DEVICE:
if (SAS_ADDR(dev->port->disc.fanout_sas_addr)) {
SAS_DPRINTK("second fanout expander %016llx phy 0x%x "
"attached to ex %016llx phy 0x%x\n",
SAS_ADDR(ex_phy->attached_sas_addr),
ex_phy->attached_phy_id,
SAS_ADDR(dev->sas_addr),
phy_id);
sas_ex_disable_phy(dev, phy_id);
break;
} else
memcpy(dev->port->disc.fanout_sas_addr,
ex_phy->attached_sas_addr, SAS_ADDR_SIZE);
/* fallthrough */
case SAS_EDGE_EXPANDER_DEVICE:
child = sas_ex_discover_expander(dev, phy_id);
break;
default:
break;
}
if (child) {
int i;
for (i = 0; i < ex->num_phys; i++) {
if (ex->ex_phy[i].phy_state == PHY_VACANT ||
ex->ex_phy[i].phy_state == PHY_NOT_PRESENT)
continue;
/*
* Due to races, the phy might not get added to the
* wide port, so we add the phy to the wide port here.
*/
if (SAS_ADDR(ex->ex_phy[i].attached_sas_addr) ==
SAS_ADDR(child->sas_addr)) {
ex->ex_phy[i].phy_state= PHY_DEVICE_DISCOVERED;
if (sas_ex_join_wide_port(dev, i))
SAS_DPRINTK("Attaching ex phy%d to wide port %016llx\n",
i, SAS_ADDR(ex->ex_phy[i].attached_sas_addr));
}
}
}
return res;
}
static int sas_find_sub_addr(struct domain_device *dev, u8 *sub_addr)
{
struct expander_device *ex = &dev->ex_dev;
int i;
for (i = 0; i < ex->num_phys; i++) {
struct ex_phy *phy = &ex->ex_phy[i];
if (phy->phy_state == PHY_VACANT ||
phy->phy_state == PHY_NOT_PRESENT)
continue;
if ((phy->attached_dev_type == SAS_EDGE_EXPANDER_DEVICE ||
phy->attached_dev_type == SAS_FANOUT_EXPANDER_DEVICE) &&
phy->routing_attr == SUBTRACTIVE_ROUTING) {
memcpy(sub_addr, phy->attached_sas_addr,SAS_ADDR_SIZE);
return 1;
}
}
return 0;
}
static int sas_check_level_subtractive_boundary(struct domain_device *dev)
{
struct expander_device *ex = &dev->ex_dev;
struct domain_device *child;
u8 sub_addr[8] = {0, };
list_for_each_entry(child, &ex->children, siblings) {
if (child->dev_type != SAS_EDGE_EXPANDER_DEVICE &&
child->dev_type != SAS_FANOUT_EXPANDER_DEVICE)
continue;
if (sub_addr[0] == 0) {
sas_find_sub_addr(child, sub_addr);
continue;
} else {
u8 s2[8];
if (sas_find_sub_addr(child, s2) &&
(SAS_ADDR(sub_addr) != SAS_ADDR(s2))) {
SAS_DPRINTK("ex %016llx->%016llx-?->%016llx "
"diverges from subtractive "
"boundary %016llx\n",
SAS_ADDR(dev->sas_addr),
SAS_ADDR(child->sas_addr),
SAS_ADDR(s2),
SAS_ADDR(sub_addr));
sas_ex_disable_port(child, s2);
}
}
}
return 0;
}
/**
* sas_ex_discover_devices -- discover devices attached to this expander
* dev: pointer to the expander domain device
* single: if you want to do a single phy, else set to -1;
*
* Configure this expander for use with its devices and register the
* devices of this expander.
*/
static int sas_ex_discover_devices(struct domain_device *dev, int single)
{
struct expander_device *ex = &dev->ex_dev;
int i = 0, end = ex->num_phys;
int res = 0;
if (0 <= single && single < end) {
i = single;
end = i+1;
}
for ( ; i < end; i++) {
struct ex_phy *ex_phy = &ex->ex_phy[i];
if (ex_phy->phy_state == PHY_VACANT ||
ex_phy->phy_state == PHY_NOT_PRESENT ||
ex_phy->phy_state == PHY_DEVICE_DISCOVERED)
continue;
switch (ex_phy->linkrate) {
case SAS_PHY_DISABLED:
case SAS_PHY_RESET_PROBLEM:
case SAS_SATA_PORT_SELECTOR:
continue;
default:
res = sas_ex_discover_dev(dev, i);
if (res)
break;
continue;
}
}
if (!res)
sas_check_level_subtractive_boundary(dev);
return res;
}
static int sas_check_ex_subtractive_boundary(struct domain_device *dev)
{
struct expander_device *ex = &dev->ex_dev;
int i;
u8 *sub_sas_addr = NULL;
if (dev->dev_type != SAS_EDGE_EXPANDER_DEVICE)
return 0;
for (i = 0; i < ex->num_phys; i++) {
struct ex_phy *phy = &ex->ex_phy[i];
if (phy->phy_state == PHY_VACANT ||
phy->phy_state == PHY_NOT_PRESENT)
continue;
if ((phy->attached_dev_type == SAS_FANOUT_EXPANDER_DEVICE ||
phy->attached_dev_type == SAS_EDGE_EXPANDER_DEVICE) &&
phy->routing_attr == SUBTRACTIVE_ROUTING) {
if (!sub_sas_addr)
sub_sas_addr = &phy->attached_sas_addr[0];
else if (SAS_ADDR(sub_sas_addr) !=
SAS_ADDR(phy->attached_sas_addr)) {
SAS_DPRINTK("ex %016llx phy 0x%x "
"diverges(%016llx) on subtractive "
"boundary(%016llx). Disabled\n",
SAS_ADDR(dev->sas_addr), i,
SAS_ADDR(phy->attached_sas_addr),
SAS_ADDR(sub_sas_addr));
sas_ex_disable_phy(dev, i);
}
}
}
return 0;
}
static void sas_print_parent_topology_bug(struct domain_device *child,
struct ex_phy *parent_phy,
struct ex_phy *child_phy)
{
static const char *ex_type[] = {
[SAS_EDGE_EXPANDER_DEVICE] = "edge",
[SAS_FANOUT_EXPANDER_DEVICE] = "fanout",
};
struct domain_device *parent = child->parent;
sas_printk("%s ex %016llx phy 0x%x <--> %s ex %016llx "
"phy 0x%x has %c:%c routing link!\n",
ex_type[parent->dev_type],
SAS_ADDR(parent->sas_addr),
parent_phy->phy_id,
ex_type[child->dev_type],
SAS_ADDR(child->sas_addr),
child_phy->phy_id,
sas_route_char(parent, parent_phy),
sas_route_char(child, child_phy));
}
static int sas_check_eeds(struct domain_device *child,
struct ex_phy *parent_phy,
struct ex_phy *child_phy)
{
int res = 0;
struct domain_device *parent = child->parent;
if (SAS_ADDR(parent->port->disc.fanout_sas_addr) != 0) {
res = -ENODEV;
SAS_DPRINTK("edge ex %016llx phy S:0x%x <--> edge ex %016llx "
"phy S:0x%x, while there is a fanout ex %016llx\n",
SAS_ADDR(parent->sas_addr),
parent_phy->phy_id,
SAS_ADDR(child->sas_addr),
child_phy->phy_id,
SAS_ADDR(parent->port->disc.fanout_sas_addr));
} else if (SAS_ADDR(parent->port->disc.eeds_a) == 0) {
memcpy(parent->port->disc.eeds_a, parent->sas_addr,
SAS_ADDR_SIZE);
memcpy(parent->port->disc.eeds_b, child->sas_addr,
SAS_ADDR_SIZE);
} else if (((SAS_ADDR(parent->port->disc.eeds_a) ==
SAS_ADDR(parent->sas_addr)) ||
(SAS_ADDR(parent->port->disc.eeds_a) ==
SAS_ADDR(child->sas_addr)))
&&
((SAS_ADDR(parent->port->disc.eeds_b) ==
SAS_ADDR(parent->sas_addr)) ||
(SAS_ADDR(parent->port->disc.eeds_b) ==
SAS_ADDR(child->sas_addr))))
;
else {
res = -ENODEV;
SAS_DPRINTK("edge ex %016llx phy 0x%x <--> edge ex %016llx "
"phy 0x%x link forms a third EEDS!\n",
SAS_ADDR(parent->sas_addr),
parent_phy->phy_id,
SAS_ADDR(child->sas_addr),
child_phy->phy_id);
}
return res;
}
/* Here we spill over 80 columns. It is intentional.
*/
static int sas_check_parent_topology(struct domain_device *child)
{
struct expander_device *child_ex = &child->ex_dev;
struct expander_device *parent_ex;
int i;
int res = 0;
if (!child->parent)
return 0;
if (child->parent->dev_type != SAS_EDGE_EXPANDER_DEVICE &&
child->parent->dev_type != SAS_FANOUT_EXPANDER_DEVICE)
return 0;
parent_ex = &child->parent->ex_dev;
for (i = 0; i < parent_ex->num_phys; i++) {
struct ex_phy *parent_phy = &parent_ex->ex_phy[i];
struct ex_phy *child_phy;
if (parent_phy->phy_state == PHY_VACANT ||
parent_phy->phy_state == PHY_NOT_PRESENT)
continue;
if (SAS_ADDR(parent_phy->attached_sas_addr) != SAS_ADDR(child->sas_addr))
continue;
child_phy = &child_ex->ex_phy[parent_phy->attached_phy_id];
switch (child->parent->dev_type) {
case SAS_EDGE_EXPANDER_DEVICE:
if (child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) {
if (parent_phy->routing_attr != SUBTRACTIVE_ROUTING ||
child_phy->routing_attr != TABLE_ROUTING) {
sas_print_parent_topology_bug(child, parent_phy, child_phy);
res = -ENODEV;
}
} else if (parent_phy->routing_attr == SUBTRACTIVE_ROUTING) {
if (child_phy->routing_attr == SUBTRACTIVE_ROUTING) {
res = sas_check_eeds(child, parent_phy, child_phy);
} else if (child_phy->routing_attr != TABLE_ROUTING) {
sas_print_parent_topology_bug(child, parent_phy, child_phy);
res = -ENODEV;
}
} else if (parent_phy->routing_attr == TABLE_ROUTING) {
if (child_phy->routing_attr == SUBTRACTIVE_ROUTING ||
(child_phy->routing_attr == TABLE_ROUTING &&
child_ex->t2t_supp && parent_ex->t2t_supp)) {
/* All good */;
} else {
sas_print_parent_topology_bug(child, parent_phy, child_phy);
res = -ENODEV;
}
}
break;
case SAS_FANOUT_EXPANDER_DEVICE:
if (parent_phy->routing_attr != TABLE_ROUTING ||
child_phy->routing_attr != SUBTRACTIVE_ROUTING) {
sas_print_parent_topology_bug(child, parent_phy, child_phy);
res = -ENODEV;
}
break;
default:
break;
}
}
return res;
}
#define RRI_REQ_SIZE 16
#define RRI_RESP_SIZE 44
static int sas_configure_present(struct domain_device *dev, int phy_id,
u8 *sas_addr, int *index, int *present)
{
int i, res = 0;
struct expander_device *ex = &dev->ex_dev;
struct ex_phy *phy = &ex->ex_phy[phy_id];
u8 *rri_req;
u8 *rri_resp;
*present = 0;
*index = 0;
rri_req = alloc_smp_req(RRI_REQ_SIZE);
if (!rri_req)
return -ENOMEM;
rri_resp = alloc_smp_resp(RRI_RESP_SIZE);
if (!rri_resp) {
kfree(rri_req);
return -ENOMEM;
}
rri_req[1] = SMP_REPORT_ROUTE_INFO;
rri_req[9] = phy_id;
for (i = 0; i < ex->max_route_indexes ; i++) {
*(__be16 *)(rri_req+6) = cpu_to_be16(i);
res = smp_execute_task(dev, rri_req, RRI_REQ_SIZE, rri_resp,
RRI_RESP_SIZE);
if (res)
goto out;
res = rri_resp[2];
if (res == SMP_RESP_NO_INDEX) {
SAS_DPRINTK("overflow of indexes: dev %016llx "
"phy 0x%x index 0x%x\n",
SAS_ADDR(dev->sas_addr), phy_id, i);
goto out;
} else if (res != SMP_RESP_FUNC_ACC) {
SAS_DPRINTK("%s: dev %016llx phy 0x%x index 0x%x "
"result 0x%x\n", __func__,
SAS_ADDR(dev->sas_addr), phy_id, i, res);
goto out;
}
if (SAS_ADDR(sas_addr) != 0) {
if (SAS_ADDR(rri_resp+16) == SAS_ADDR(sas_addr)) {
*index = i;
if ((rri_resp[12] & 0x80) == 0x80)
*present = 0;
else
*present = 1;
goto out;
} else if (SAS_ADDR(rri_resp+16) == 0) {
*index = i;
*present = 0;
goto out;
}
} else if (SAS_ADDR(rri_resp+16) == 0 &&
phy->last_da_index < i) {
phy->last_da_index = i;
*index = i;
*present = 0;
goto out;
}
}
res = -1;
out:
kfree(rri_req);
kfree(rri_resp);
return res;
}
#define CRI_REQ_SIZE 44
#define CRI_RESP_SIZE 8
static int sas_configure_set(struct domain_device *dev, int phy_id,
u8 *sas_addr, int index, int include)
{
int res;
u8 *cri_req;
u8 *cri_resp;
cri_req = alloc_smp_req(CRI_REQ_SIZE);
if (!cri_req)
return -ENOMEM;
cri_resp = alloc_smp_resp(CRI_RESP_SIZE);
if (!cri_resp) {
kfree(cri_req);
return -ENOMEM;
}
cri_req[1] = SMP_CONF_ROUTE_INFO;
*(__be16 *)(cri_req+6) = cpu_to_be16(index);
cri_req[9] = phy_id;
if (SAS_ADDR(sas_addr) == 0 || !include)
cri_req[12] |= 0x80;
memcpy(cri_req+16, sas_addr, SAS_ADDR_SIZE);
res = smp_execute_task(dev, cri_req, CRI_REQ_SIZE, cri_resp,
CRI_RESP_SIZE);
if (res)
goto out;
res = cri_resp[2];
if (res == SMP_RESP_NO_INDEX) {
SAS_DPRINTK("overflow of indexes: dev %016llx phy 0x%x "
"index 0x%x\n",
SAS_ADDR(dev->sas_addr), phy_id, index);
}
out:
kfree(cri_req);
kfree(cri_resp);
return res;
}
static int sas_configure_phy(struct domain_device *dev, int phy_id,
u8 *sas_addr, int include)
{
int index;
int present;
int res;
res = sas_configure_present(dev, phy_id, sas_addr, &index, &present);
if (res)
return res;
if (include ^ present)
return sas_configure_set(dev, phy_id, sas_addr, index,include);
return res;
}
/**
* sas_configure_parent -- configure routing table of parent
* parent: parent expander
* child: child expander
* sas_addr: SAS port identifier of device directly attached to child
*/
static int sas_configure_parent(struct domain_device *parent,
struct domain_device *child,
u8 *sas_addr, int include)
{
struct expander_device *ex_parent = &parent->ex_dev;
int res = 0;
int i;
if (parent->parent) {
res = sas_configure_parent(parent->parent, parent, sas_addr,
include);
if (res)
return res;
}
if (ex_parent->conf_route_table == 0) {
SAS_DPRINTK("ex %016llx has self-configuring routing table\n",
SAS_ADDR(parent->sas_addr));
return 0;
}
for (i = 0; i < ex_parent->num_phys; i++) {
struct ex_phy *phy = &ex_parent->ex_phy[i];
if ((phy->routing_attr == TABLE_ROUTING) &&
(SAS_ADDR(phy->attached_sas_addr) ==
SAS_ADDR(child->sas_addr))) {
res = sas_configure_phy(parent, i, sas_addr, include);
if (res)
return res;
}
}
return res;
}
/**
* sas_configure_routing -- configure routing
* dev: expander device
* sas_addr: port identifier of device directly attached to the expander device
*/
static int sas_configure_routing(struct domain_device *dev, u8 *sas_addr)
{
if (dev->parent)
return sas_configure_parent(dev->parent, dev, sas_addr, 1);
return 0;
}
static int sas_disable_routing(struct domain_device *dev, u8 *sas_addr)
{
if (dev->parent)
return sas_configure_parent(dev->parent, dev, sas_addr, 0);
return 0;
}
/**
* sas_discover_expander -- expander discovery
* @ex: pointer to expander domain device
*
* See comment in sas_discover_sata().
*/
static int sas_discover_expander(struct domain_device *dev)
{
int res;
res = sas_notify_lldd_dev_found(dev);
if (res)
return res;
res = sas_ex_general(dev);
if (res)
goto out_err;
res = sas_ex_manuf_info(dev);
if (res)
goto out_err;
res = sas_expander_discover(dev);
if (res) {
SAS_DPRINTK("expander %016llx discovery failed(0x%x)\n",
SAS_ADDR(dev->sas_addr), res);
goto out_err;
}
sas_check_ex_subtractive_boundary(dev);
res = sas_check_parent_topology(dev);
if (res)
goto out_err;
return 0;
out_err:
sas_notify_lldd_dev_gone(dev);
return res;
}
static int sas_ex_level_discovery(struct asd_sas_port *port, const int level)
{
int res = 0;
struct domain_device *dev;
list_for_each_entry(dev, &port->dev_list, dev_list_node) {
if (dev->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
dev->dev_type == SAS_FANOUT_EXPANDER_DEVICE) {
struct sas_expander_device *ex =
rphy_to_expander_device(dev->rphy);
if (level == ex->level)
res = sas_ex_discover_devices(dev, -1);
else if (level > 0)
res = sas_ex_discover_devices(port->port_dev, -1);
}
}
return res;
}
static int sas_ex_bfs_disc(struct asd_sas_port *port)
{
int res;
int level;
do {
level = port->disc.max_level;
res = sas_ex_level_discovery(port, level);
mb();
} while (level < port->disc.max_level);
return res;
}
int sas_discover_root_expander(struct domain_device *dev)
{
int res;
struct sas_expander_device *ex = rphy_to_expander_device(dev->rphy);
res = sas_rphy_add(dev->rphy);
if (res)
goto out_err;
ex->level = dev->port->disc.max_level; /* 0 */
res = sas_discover_expander(dev);
if (res)
goto out_err2;
sas_ex_bfs_disc(dev->port);
return res;
out_err2:
sas_rphy_remove(dev->rphy);
out_err:
return res;
}
/* ---------- Domain revalidation ---------- */
static int sas_get_phy_discover(struct domain_device *dev,
int phy_id, struct smp_resp *disc_resp)
{
int res;
u8 *disc_req;
disc_req = alloc_smp_req(DISCOVER_REQ_SIZE);
if (!disc_req)
return -ENOMEM;
disc_req[1] = SMP_DISCOVER;
disc_req[9] = phy_id;
res = smp_execute_task(dev, disc_req, DISCOVER_REQ_SIZE,
disc_resp, DISCOVER_RESP_SIZE);
if (res)
goto out;
else if (disc_resp->result != SMP_RESP_FUNC_ACC) {
res = disc_resp->result;
goto out;
}
out:
kfree(disc_req);
return res;
}
static int sas_get_phy_change_count(struct domain_device *dev,
int phy_id, int *pcc)
{
int res;
struct smp_resp *disc_resp;
disc_resp = alloc_smp_resp(DISCOVER_RESP_SIZE);
if (!disc_resp)
return -ENOMEM;
res = sas_get_phy_discover(dev, phy_id, disc_resp);
if (!res)
*pcc = disc_resp->disc.change_count;
kfree(disc_resp);
return res;
}
static int sas_get_phy_attached_dev(struct domain_device *dev, int phy_id,
u8 *sas_addr, enum sas_device_type *type)
{
int res;
struct smp_resp *disc_resp;
struct discover_resp *dr;
disc_resp = alloc_smp_resp(DISCOVER_RESP_SIZE);
if (!disc_resp)
return -ENOMEM;
dr = &disc_resp->disc;
res = sas_get_phy_discover(dev, phy_id, disc_resp);
if (res == 0) {
memcpy(sas_addr, disc_resp->disc.attached_sas_addr, 8);
*type = to_dev_type(dr);
if (*type == 0)
memset(sas_addr, 0, 8);
}
kfree(disc_resp);
return res;
}
static int sas_find_bcast_phy(struct domain_device *dev, int *phy_id,
int from_phy, bool update)
{
struct expander_device *ex = &dev->ex_dev;
int res = 0;
int i;
for (i = from_phy; i < ex->num_phys; i++) {
int phy_change_count = 0;
res = sas_get_phy_change_count(dev, i, &phy_change_count);
switch (res) {
case SMP_RESP_PHY_VACANT:
case SMP_RESP_NO_PHY:
continue;
case SMP_RESP_FUNC_ACC:
break;
default:
return res;
}
if (phy_change_count != ex->ex_phy[i].phy_change_count) {
if (update)
ex->ex_phy[i].phy_change_count =
phy_change_count;
*phy_id = i;
return 0;
}
}
return 0;
}
static int sas_get_ex_change_count(struct domain_device *dev, int *ecc)
{
int res;
u8 *rg_req;
struct smp_resp *rg_resp;
rg_req = alloc_smp_req(RG_REQ_SIZE);
if (!rg_req)
return -ENOMEM;
rg_resp = alloc_smp_resp(RG_RESP_SIZE);
if (!rg_resp) {
kfree(rg_req);
return -ENOMEM;
}
rg_req[1] = SMP_REPORT_GENERAL;
res = smp_execute_task(dev, rg_req, RG_REQ_SIZE, rg_resp,
RG_RESP_SIZE);
if (res)
goto out;
if (rg_resp->result != SMP_RESP_FUNC_ACC) {
res = rg_resp->result;
goto out;
}
*ecc = be16_to_cpu(rg_resp->rg.change_count);
out:
kfree(rg_resp);
kfree(rg_req);
return res;
}
/**
* sas_find_bcast_dev - find the device issue BROADCAST(CHANGE).
* @dev:domain device to be detect.
* @src_dev: the device which originated BROADCAST(CHANGE).
*
* Add self-configuration expander support. Suppose two expander cascading,
* when the first level expander is self-configuring, hotplug the disks in
* second level expander, BROADCAST(CHANGE) will not only be originated
* in the second level expander, but also be originated in the first level
* expander (see SAS protocol SAS 2r-14, 7.11 for detail), it is to say,
* expander changed count in two level expanders will all increment at least
* once, but the phy which chang count has changed is the source device which
* we concerned.
*/
static int sas_find_bcast_dev(struct domain_device *dev,
struct domain_device **src_dev)
{
struct expander_device *ex = &dev->ex_dev;
int ex_change_count = -1;
int phy_id = -1;
int res;
struct domain_device *ch;
res = sas_get_ex_change_count(dev, &ex_change_count);
if (res)
goto out;
if (ex_change_count != -1 && ex_change_count != ex->ex_change_count) {
/* Just detect if this expander phys phy change count changed,
* in order to determine if this expander originate BROADCAST,
* and do not update phy change count field in our structure.
*/
res = sas_find_bcast_phy(dev, &phy_id, 0, false);
if (phy_id != -1) {
*src_dev = dev;
ex->ex_change_count = ex_change_count;
SAS_DPRINTK("Expander phy change count has changed\n");
return res;
} else
SAS_DPRINTK("Expander phys DID NOT change\n");
}
list_for_each_entry(ch, &ex->children, siblings) {
if (ch->dev_type == SAS_EDGE_EXPANDER_DEVICE || ch->dev_type == SAS_FANOUT_EXPANDER_DEVICE) {
res = sas_find_bcast_dev(ch, src_dev);
if (*src_dev)
return res;
}
}
out:
return res;
}
static void sas_unregister_ex_tree(struct asd_sas_port *port, struct domain_device *dev)
{
struct expander_device *ex = &dev->ex_dev;
struct domain_device *child, *n;
list_for_each_entry_safe(child, n, &ex->children, siblings) {
set_bit(SAS_DEV_GONE, &child->state);
if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
child->dev_type == SAS_FANOUT_EXPANDER_DEVICE)
sas_unregister_ex_tree(port, child);
else
sas_unregister_dev(port, child);
}
sas_unregister_dev(port, dev);
}
static void sas_unregister_devs_sas_addr(struct domain_device *parent,
int phy_id, bool last)
{
struct expander_device *ex_dev = &parent->ex_dev;
struct ex_phy *phy = &ex_dev->ex_phy[phy_id];
struct domain_device *child, *n, *found = NULL;
if (last) {
list_for_each_entry_safe(child, n,
&ex_dev->children, siblings) {
if (SAS_ADDR(child->sas_addr) ==
SAS_ADDR(phy->attached_sas_addr)) {
set_bit(SAS_DEV_GONE, &child->state);
if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
child->dev_type == SAS_FANOUT_EXPANDER_DEVICE)
sas_unregister_ex_tree(parent->port, child);
else
sas_unregister_dev(parent->port, child);
found = child;
break;
}
}
sas_disable_routing(parent, phy->attached_sas_addr);
}
memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE);
if (phy->port) {
sas_port_delete_phy(phy->port, phy->phy);
sas_device_set_phy(found, phy->port);
if (phy->port->num_phys == 0)
sas_port_delete(phy->port);
phy->port = NULL;
}
}
static int sas_discover_bfs_by_root_level(struct domain_device *root,
const int level)
{
struct expander_device *ex_root = &root->ex_dev;
struct domain_device *child;
int res = 0;
list_for_each_entry(child, &ex_root->children, siblings) {
if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) {
struct sas_expander_device *ex =
rphy_to_expander_device(child->rphy);
if (level > ex->level)
res = sas_discover_bfs_by_root_level(child,
level);
else if (level == ex->level)
res = sas_ex_discover_devices(child, -1);
}
}
return res;
}
static int sas_discover_bfs_by_root(struct domain_device *dev)
{
int res;
struct sas_expander_device *ex = rphy_to_expander_device(dev->rphy);
int level = ex->level+1;
res = sas_ex_discover_devices(dev, -1);
if (res)
goto out;
do {
res = sas_discover_bfs_by_root_level(dev, level);
mb();
level += 1;
} while (level <= dev->port->disc.max_level);
out:
return res;
}
static int sas_discover_new(struct domain_device *dev, int phy_id)
{
struct ex_phy *ex_phy = &dev->ex_dev.ex_phy[phy_id];
struct domain_device *child;
int res;
SAS_DPRINTK("ex %016llx phy%d new device attached\n",
SAS_ADDR(dev->sas_addr), phy_id);
res = sas_ex_phy_discover(dev, phy_id);
if (res)
return res;
if (sas_ex_join_wide_port(dev, phy_id))
return 0;
res = sas_ex_discover_devices(dev, phy_id);
if (res)
return res;
list_for_each_entry(child, &dev->ex_dev.children, siblings) {
if (SAS_ADDR(child->sas_addr) ==
SAS_ADDR(ex_phy->attached_sas_addr)) {
if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
child->dev_type == SAS_FANOUT_EXPANDER_DEVICE)
res = sas_discover_bfs_by_root(child);
break;
}
}
return res;
}
static bool dev_type_flutter(enum sas_device_type new, enum sas_device_type old)
{
if (old == new)
return true;
/* treat device directed resets as flutter, if we went
* SAS_END_DEVICE to SAS_SATA_PENDING the link needs recovery
*/
if ((old == SAS_SATA_PENDING && new == SAS_END_DEVICE) ||
(old == SAS_END_DEVICE && new == SAS_SATA_PENDING))
return true;
return false;
}
static int sas_rediscover_dev(struct domain_device *dev, int phy_id, bool last)
{
struct expander_device *ex = &dev->ex_dev;
struct ex_phy *phy = &ex->ex_phy[phy_id];
enum sas_device_type type = SAS_PHY_UNUSED;
u8 sas_addr[8];
int res;
memset(sas_addr, 0, 8);
res = sas_get_phy_attached_dev(dev, phy_id, sas_addr, &type);
switch (res) {
case SMP_RESP_NO_PHY:
phy->phy_state = PHY_NOT_PRESENT;
sas_unregister_devs_sas_addr(dev, phy_id, last);
return res;
case SMP_RESP_PHY_VACANT:
phy->phy_state = PHY_VACANT;
sas_unregister_devs_sas_addr(dev, phy_id, last);
return res;
case SMP_RESP_FUNC_ACC:
break;
case -ECOMM:
break;
default:
return res;
}
if ((SAS_ADDR(sas_addr) == 0) || (res == -ECOMM)) {
phy->phy_state = PHY_EMPTY;
sas_unregister_devs_sas_addr(dev, phy_id, last);
return res;
} else if (SAS_ADDR(sas_addr) == SAS_ADDR(phy->attached_sas_addr) &&
dev_type_flutter(type, phy->attached_dev_type)) {
struct domain_device *ata_dev = sas_ex_to_ata(dev, phy_id);
char *action = "";
sas_ex_phy_discover(dev, phy_id);
if (ata_dev && phy->attached_dev_type == SAS_SATA_PENDING)
action = ", needs recovery";
SAS_DPRINTK("ex %016llx phy 0x%x broadcast flutter%s\n",
SAS_ADDR(dev->sas_addr), phy_id, action);
return res;
}
/* delete the old link */
if (SAS_ADDR(phy->attached_sas_addr) &&
SAS_ADDR(sas_addr) != SAS_ADDR(phy->attached_sas_addr)) {
SAS_DPRINTK("ex %016llx phy 0x%x replace %016llx\n",
SAS_ADDR(dev->sas_addr), phy_id,
SAS_ADDR(phy->attached_sas_addr));
sas_unregister_devs_sas_addr(dev, phy_id, last);
}
return sas_discover_new(dev, phy_id);
}
/**
* sas_rediscover - revalidate the domain.
* @dev:domain device to be detect.
* @phy_id: the phy id will be detected.
*
* NOTE: this process _must_ quit (return) as soon as any connection
* errors are encountered. Connection recovery is done elsewhere.
* Discover process only interrogates devices in order to discover the
* domain.For plugging out, we un-register the device only when it is
* the last phy in the port, for other phys in this port, we just delete it
* from the port.For inserting, we do discovery when it is the
* first phy,for other phys in this port, we add it to the port to
* forming the wide-port.
*/
static int sas_rediscover(struct domain_device *dev, const int phy_id)
{
struct expander_device *ex = &dev->ex_dev;
struct ex_phy *changed_phy = &ex->ex_phy[phy_id];
int res = 0;
int i;
bool last = true; /* is this the last phy of the port */
SAS_DPRINTK("ex %016llx phy%d originated BROADCAST(CHANGE)\n",
SAS_ADDR(dev->sas_addr), phy_id);
if (SAS_ADDR(changed_phy->attached_sas_addr) != 0) {
for (i = 0; i < ex->num_phys; i++) {
struct ex_phy *phy = &ex->ex_phy[i];
if (i == phy_id)
continue;
if (SAS_ADDR(phy->attached_sas_addr) ==
SAS_ADDR(changed_phy->attached_sas_addr)) {
SAS_DPRINTK("phy%d part of wide port with "
"phy%d\n", phy_id, i);
last = false;
break;
}
}
res = sas_rediscover_dev(dev, phy_id, last);
} else
res = sas_discover_new(dev, phy_id);
return res;
}
/**
* sas_revalidate_domain -- revalidate the domain
* @port: port to the domain of interest
*
* NOTE: this process _must_ quit (return) as soon as any connection
* errors are encountered. Connection recovery is done elsewhere.
* Discover process only interrogates devices in order to discover the
* domain.
*/
int sas_ex_revalidate_domain(struct domain_device *port_dev)
{
int res;
struct domain_device *dev = NULL;
res = sas_find_bcast_dev(port_dev, &dev);
while (res == 0 && dev) {
struct expander_device *ex = &dev->ex_dev;
int i = 0, phy_id;
do {
phy_id = -1;
res = sas_find_bcast_phy(dev, &phy_id, i, true);
if (phy_id == -1)
break;
res = sas_rediscover(dev, phy_id);
i = phy_id + 1;
} while (i < ex->num_phys);
dev = NULL;
res = sas_find_bcast_dev(port_dev, &dev);
}
return res;
}
void sas_smp_handler(struct bsg_job *job, struct Scsi_Host *shost,
struct sas_rphy *rphy)
{
struct domain_device *dev;
unsigned int reslen = 0;
int ret = -EINVAL;
/* no rphy means no smp target support (ie aic94xx host) */
if (!rphy)
return sas_smp_host_handler(job, shost);
switch (rphy->identify.device_type) {
case SAS_EDGE_EXPANDER_DEVICE:
case SAS_FANOUT_EXPANDER_DEVICE:
break;
default:
printk("%s: can we send a smp request to a device?\n",
__func__);
goto out;
}
dev = sas_find_dev_by_rphy(rphy);
if (!dev) {
printk("%s: fail to find a domain_device?\n", __func__);
goto out;
}
/* do we need to support multiple segments? */
if (job->request_payload.sg_cnt > 1 ||
job->reply_payload.sg_cnt > 1) {
printk("%s: multiple segments req %u, rsp %u\n",
__func__, job->request_payload.payload_len,
job->reply_payload.payload_len);
goto out;
}
ret = smp_execute_task_sg(dev, job->request_payload.sg_list,
job->reply_payload.sg_list);
if (ret > 0) {
/* positive number is the untransferred residual */
reslen = ret;
ret = 0;
}
out:
bsg_job_done(job, ret, reslen);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_653_0 |
crossvul-cpp_data_bad_2830_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Y Y U U V V %
% Y Y U U V V %
% Y U U V V %
% Y U U V V %
% Y UUU V %
% %
% %
% Read/Write Raw CCIR 601 4:1:1 or 4:2:2 Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/resize.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/utility.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteYUVImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadYUVImage() reads an image with digital YUV (CCIR 601 4:1:1, plane
% or partition interlaced, or 4:2:2 plane, partition interlaced or
% noninterlaced) bytes and returns it. It allocates the memory necessary
% for the new Image structure and returns a pointer to the new image.
%
% The format of the ReadYUVImage method is:
%
% Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*chroma_image,
*image,
*resize_image;
InterlaceType
interlace;
MagickBooleanType
status;
register const Quantum
*chroma_pixels;
register ssize_t
x;
register Quantum
*q;
register unsigned char
*p;
ssize_t
count,
horizontal_factor,
vertical_factor,
y;
size_t
length,
quantum;
unsigned char
*scanline;
/*
Allocate image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
quantum=(ssize_t) (image->depth <= 8 ? 1 : 2);
interlace=image_info->interlace;
horizontal_factor=2;
vertical_factor=2;
if (image_info->sampling_factor != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(image_info->sampling_factor,&geometry_info);
horizontal_factor=(ssize_t) geometry_info.rho;
vertical_factor=(ssize_t) geometry_info.sigma;
if ((flags & SigmaValue) == 0)
vertical_factor=horizontal_factor;
if ((horizontal_factor != 1) && (horizontal_factor != 2) &&
(vertical_factor != 1) && (vertical_factor != 2))
ThrowReaderException(CorruptImageError,"UnexpectedSamplingFactor");
}
if ((interlace == UndefinedInterlace) ||
((interlace == NoInterlace) && (vertical_factor == 2)))
{
interlace=NoInterlace; /* CCIR 4:2:2 */
if (vertical_factor == 2)
interlace=PlaneInterlace; /* CCIR 4:1:1 */
}
if (interlace != PartitionInterlace)
{
/*
Open image file.
*/
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
/*
Allocate memory for a scanline.
*/
if (interlace == NoInterlace)
scanline=(unsigned char *) AcquireQuantumMemory((size_t) (2UL*
image->columns+2UL),(size_t) quantum*sizeof(*scanline));
else
scanline=(unsigned char *) AcquireQuantumMemory(image->columns,
(size_t) quantum*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=MagickTrue;
do
{
chroma_image=CloneImage(image,(image->columns+horizontal_factor-1)/
horizontal_factor,(image->rows+vertical_factor-1)/vertical_factor,
MagickTrue,exception);
if (chroma_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert raster image to pixel packets.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if (interlace == PartitionInterlace)
{
AppendImageFormat("Y",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*chroma_pixels;
if (interlace == NoInterlace)
{
if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))
{
length=2*quantum*image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
}
p=scanline;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
chroma_pixels=QueueAuthenticPixels(chroma_image,0,y,
chroma_image->columns,1,exception);
if (chroma_pixels == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=2)
{
SetPixelRed(chroma_image,0,chroma_pixels);
if (quantum == 1)
SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++),
chroma_pixels);
else
{
SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),chroma_pixels);
p+=2;
}
if (quantum == 1)
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);
p+=2;
}
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
q+=GetPixelChannels(image);
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
if (quantum == 1)
SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),chroma_pixels);
else
{
SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),chroma_pixels);
p+=2;
}
if (quantum == 1)
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);
p+=2;
}
chroma_pixels+=GetPixelChannels(chroma_image);
q+=GetPixelChannels(image);
}
}
else
{
if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))
{
length=quantum*image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
}
p=scanline;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (quantum == 1)
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);
p+=2;
}
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
q+=GetPixelChannels(image);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (interlace == NoInterlace)
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("U",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (interlace != NoInterlace)
{
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
length=quantum*chroma_image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
p=scanline;
q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
SetPixelRed(chroma_image,0,q);
if (quantum == 1)
SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),q);
p+=2;
}
SetPixelBlue(chroma_image,0,q);
q+=GetPixelChannels(chroma_image);
}
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
}
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("V",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
}
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
length=quantum*chroma_image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
p=scanline;
q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
if (quantum == 1)
SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),q);
p+=2;
}
q+=GetPixelChannels(chroma_image);
}
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
}
}
/*
Scale image.
*/
resize_image=ResizeImage(chroma_image,image->columns,image->rows,
TriangleFilter,exception);
chroma_image=DestroyImage(chroma_image);
if (resize_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1,
exception);
if ((q == (Quantum *) NULL) ||
(chroma_pixels == (const Quantum *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGreen(image,GetPixelGreen(resize_image,chroma_pixels),q);
SetPixelBlue(image,GetPixelBlue(resize_image,chroma_pixels),q);
chroma_pixels+=GetPixelChannels(resize_image);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
resize_image=DestroyImage(resize_image);
if (SetImageColorspace(image,YCbCrColorspace,exception) == MagickFalse)
break;
if (interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (interlace == NoInterlace)
count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline);
else
count=ReadBlob(image,(size_t) quantum*image->columns,scanline);
if (count != 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (count != 0);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterYUVImage() adds attributes for the YUV image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterYUVImage method is:
%
% size_t RegisterYUVImage(void)
%
*/
ModuleExport size_t RegisterYUVImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("YUV","YUV","CCIR 601 4:1:1 or 4:2:2");
entry->decoder=(DecodeImageHandler *) ReadYUVImage;
entry->encoder=(EncodeImageHandler *) WriteYUVImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderRawSupportFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterYUVImage() removes format registrations made by the
% YUV module from the list of supported formats.
%
% The format of the UnregisterYUVImage method is:
%
% UnregisterYUVImage(void)
%
*/
ModuleExport void UnregisterYUVImage(void)
{
(void) UnregisterMagickInfo("YUV");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteYUVImage() writes an image to a file in the digital YUV
% (CCIR 601 4:1:1, plane or partition interlaced, or 4:2:2 plane, partition
% interlaced or noninterlaced) bytes and returns it.
%
% The format of the WriteYUVImage method is:
%
% MagickBooleanType WriteYUVImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WriteYUVImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
Image
*chroma_image,
*yuv_image;
InterlaceType
interlace;
MagickBooleanType
status;
MagickOffsetType
scene;
register const Quantum
*p,
*s;
register ssize_t
x;
size_t
height,
quantum,
width;
ssize_t
horizontal_factor,
vertical_factor,
y;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
quantum=(size_t) (image->depth <= 8 ? 1 : 2);
interlace=image->interlace;
horizontal_factor=2;
vertical_factor=2;
if (image_info->sampling_factor != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(image_info->sampling_factor,&geometry_info);
horizontal_factor=(ssize_t) geometry_info.rho;
vertical_factor=(ssize_t) geometry_info.sigma;
if ((flags & SigmaValue) == 0)
vertical_factor=horizontal_factor;
if ((horizontal_factor != 1) && (horizontal_factor != 2) &&
(vertical_factor != 1) && (vertical_factor != 2))
ThrowWriterException(CorruptImageError,"UnexpectedSamplingFactor");
}
if ((interlace == UndefinedInterlace) ||
((interlace == NoInterlace) && (vertical_factor == 2)))
{
interlace=NoInterlace; /* CCIR 4:2:2 */
if (vertical_factor == 2)
interlace=PlaneInterlace; /* CCIR 4:1:1 */
}
if (interlace != PartitionInterlace)
{
/*
Open output image file.
*/
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
else
{
AppendImageFormat("Y",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
scene=0;
do
{
/*
Sample image to an even width and height, if necessary.
*/
image->depth=(size_t) (quantum == 1 ? 8 : 16);
width=image->columns+(image->columns & (horizontal_factor-1));
height=image->rows+(image->rows & (vertical_factor-1));
yuv_image=ResizeImage(image,width,height,TriangleFilter,exception);
if (yuv_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
(void) TransformImageColorspace(yuv_image,YCbCrColorspace,exception);
/*
Downsample image.
*/
chroma_image=ResizeImage(image,width/horizontal_factor,
height/vertical_factor,TriangleFilter,exception);
if (chroma_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
(void) TransformImageColorspace(chroma_image,YCbCrColorspace,exception);
if (interlace == NoInterlace)
{
/*
Write noninterlaced YUV.
*/
for (y=0; y < (ssize_t) yuv_image->rows; y++)
{
p=GetVirtualPixels(yuv_image,0,y,yuv_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
s=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (s == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) yuv_image->columns; x+=2)
{
if (quantum == 1)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelGreen(yuv_image,s)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelRed(yuv_image,p)));
p+=GetPixelChannels(yuv_image);
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelBlue(yuv_image,s)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelRed(yuv_image,p)));
}
else
{
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelGreen(yuv_image,s)));
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelRed(yuv_image,p)));
p+=GetPixelChannels(yuv_image);
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelBlue(yuv_image,s)));
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelRed(yuv_image,p)));
}
p+=GetPixelChannels(yuv_image);
s++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
yuv_image=DestroyImage(yuv_image);
}
else
{
/*
Initialize Y channel.
*/
for (y=0; y < (ssize_t) yuv_image->rows; y++)
{
p=GetVirtualPixels(yuv_image,0,y,yuv_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) yuv_image->columns; x++)
{
if (quantum == 1)
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelRed(yuv_image,p)));
else
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelRed(yuv_image,p)));
p+=GetPixelChannels(yuv_image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
yuv_image=DestroyImage(yuv_image);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,3);
if (status == MagickFalse)
break;
}
/*
Initialize U channel.
*/
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("U",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
p=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
if (quantum == 1)
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelGreen(chroma_image,p)));
else
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelGreen(chroma_image,p)));
p+=GetPixelChannels(chroma_image);
}
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,3);
if (status == MagickFalse)
break;
}
/*
Initialize V channel.
*/
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("V",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
p=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
if (quantum == 1)
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelBlue(chroma_image,p)));
else
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelBlue(chroma_image,p)));
p+=GetPixelChannels(chroma_image);
}
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,3);
if (status == MagickFalse)
break;
}
}
chroma_image=DestroyImage(chroma_image);
if (interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/bad_2830_0 |
crossvul-cpp_data_bad_1168_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-772/c/bad_1168_0 |
crossvul-cpp_data_bad_2741_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% M M AAA TTTTT L AAA BBBB %
% MM MM A A T L A A B B %
% M M M AAAAA T L AAAAA BBBB %
% M M A A T L A A B B %
% M M A A T LLLLL A A BBBB %
% %
% %
% Read MATLAB Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% 2001-2008 %
% %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% ImageMagick Studio be liable for any claim, damages or other liability, %
% whether in an action of contract, tort or otherwise, arising from, out of %
% or in connection with ImageMagick or the use or other dealings in %
% ImageMagick. %
% %
% Except as contained in this notice, the name of the ImageMagick Studio %
% shall not be used in advertising or otherwise to promote the sale, use or %
% other dealings in ImageMagick without prior written authorization from the %
% ImageMagick Studio. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace-private.h"
#include "magick/distort.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
#include "magick/utility-private.h"
#if defined(MAGICKCORE_ZLIB_DELEGATE)
#include "zlib.h"
#endif
/*
Forward declaration.
*/
static MagickBooleanType
WriteMATImage(const ImageInfo *,Image *);
/* Auto coloring method, sorry this creates some artefact inside data
MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
MinReal+j*0 = white MaxReal+j*0 = black
MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
*/
typedef struct
{
char identific[124];
unsigned short Version;
char EndianIndicator[2];
unsigned long DataType;
unsigned long ObjectSize;
unsigned long unknown1;
unsigned long unknown2;
unsigned short unknown5;
unsigned char StructureFlag;
unsigned char StructureClass;
unsigned long unknown3;
unsigned long unknown4;
unsigned long DimFlag;
unsigned long SizeX;
unsigned long SizeY;
unsigned short Flag1;
unsigned short NameFlag;
}
MATHeader;
static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static const char *OsDesc=
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
"PCWIN";
#else
#ifdef __APPLE__
"MAC";
#else
"LNX86";
#endif
#endif
typedef enum
{
miINT8 = 1, /* 8 bit signed */
miUINT8, /* 8 bit unsigned */
miINT16, /* 16 bit signed */
miUINT16, /* 16 bit unsigned */
miINT32, /* 32 bit signed */
miUINT32, /* 32 bit unsigned */
miSINGLE, /* IEEE 754 single precision float */
miRESERVE1,
miDOUBLE, /* IEEE 754 double precision float */
miRESERVE2,
miRESERVE3,
miINT64, /* 64 bit signed */
miUINT64, /* 64 bit unsigned */
miMATRIX, /* MATLAB array */
miCOMPRESSED, /* Compressed Data */
miUTF8, /* Unicode UTF-8 Encoded Character Data */
miUTF16, /* Unicode UTF-16 Encoded Character Data */
miUTF32 /* Unicode UTF-32 Encoded Character Data */
} mat5_data_type;
typedef enum
{
mxCELL_CLASS=1, /* cell array */
mxSTRUCT_CLASS, /* structure */
mxOBJECT_CLASS, /* object */
mxCHAR_CLASS, /* character array */
mxSPARSE_CLASS, /* sparse array */
mxDOUBLE_CLASS, /* double precision array */
mxSINGLE_CLASS, /* single precision floating point */
mxINT8_CLASS, /* 8 bit signed integer */
mxUINT8_CLASS, /* 8 bit unsigned integer */
mxINT16_CLASS, /* 16 bit signed integer */
mxUINT16_CLASS, /* 16 bit unsigned integer */
mxINT32_CLASS, /* 32 bit signed integer */
mxUINT32_CLASS, /* 32 bit unsigned integer */
mxINT64_CLASS, /* 64 bit signed integer */
mxUINT64_CLASS, /* 64 bit unsigned integer */
mxFUNCTION_CLASS /* Function handle */
} arrayclasstype;
#define FLAG_COMPLEX 0x8
#define FLAG_GLOBAL 0x4
#define FLAG_LOGICAL 0x2
static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelRed(q,0);
SetPixelGreen(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
double MaxVal)
{
ExceptionInfo
*exception;
double f;
int x;
register PixelPacket *q;
if (MinVal == 0)
MinVal = -1;
if (MaxVal == 0)
MaxVal = 1;
exception=(&image->exception);
q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
if (q == (PixelPacket *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q));
if (f + GetPixelRed(q) > QuantumRange)
SetPixelRed(q,QuantumRange);
else
SetPixelRed(q,GetPixelRed(q)+(int) f);
if ((int) f / 2.0 > GetPixelGreen(q))
{
SetPixelGreen(q,0);
SetPixelBlue(q,0);
}
else
{
SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelBlue(q));
}
}
if (*p < 0)
{
f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q));
if (f + GetPixelBlue(q) > QuantumRange)
SetPixelBlue(q,QuantumRange);
else
SetPixelBlue(q,GetPixelBlue(q)+(int) f);
if ((int) f / 2.0 > q->green)
{
SetPixelGreen(q,0);
SetPixelRed(q,0);
}
else
{
SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0));
SetPixelGreen(q,GetPixelRed(q));
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
/************** READERS ******************/
/* This function reads one block of floats*/
static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* This function reads one block of doubles*/
static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
{
while (len >= 8)
{
*data++ = ReadBlobDouble(image);
len -= sizeof(double);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
/* Calculate minimum and maximum from a given block of data */
static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
{
MagickOffsetType filepos;
int i, x;
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
double *dblrow;
float *fltrow;
if (endian_indicator == LSBEndian)
{
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
}
else /* MI */
{
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
}
filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
for (i = 0; i < SizeY; i++)
{
if (CellType==miDOUBLE)
{
ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
dblrow = (double *)BImgBuff;
if (i == 0)
{
*Min = *Max = *dblrow;
}
for (x = 0; x < SizeX; x++)
{
if (*Min > *dblrow)
*Min = *dblrow;
if (*Max < *dblrow)
*Max = *dblrow;
dblrow++;
}
}
if (CellType==miSINGLE)
{
ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
fltrow = (float *)BImgBuff;
if (i == 0)
{
*Min = *Max = *fltrow;
}
for (x = 0; x < (ssize_t) SizeX; x++)
{
if (*Min > *fltrow)
*Min = *fltrow;
if (*Max < *fltrow)
*Max = *fltrow;
fltrow++;
}
}
}
(void) SeekBlob(image, filepos, SEEK_SET);
}
static void FixSignedValues(PixelPacket *q, int y)
{
while(y-->0)
{
/* Please note that negative values will overflow
Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
<-1;-128> + 127+1 = <0; 127> */
SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1);
SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1);
SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1);
q++;
}
}
/** Fix whole row of logical/binary data. It means pack it. */
static void FixLogical(unsigned char *Buff,int ldblk)
{
unsigned char mask=128;
unsigned char *BuffL = Buff;
unsigned char val = 0;
while(ldblk-->0)
{
if(*Buff++ != 0)
val |= mask;
mask >>= 1;
if(mask==0)
{
*BuffL++ = val;
val = 0;
mask = 128;
}
}
*BuffL = val;
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
unsigned int size)
{
(void) context;
return((voidpf) AcquireQuantumMemory(items,size));
}
static void RelinquishZIPMemory(voidpf context,voidpf memory)
{
(void) context;
memory=RelinquishMagickMemory(memory);
}
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
/** This procedure decompreses an image block for a new MATLAB format. */
static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
{
Image *image2;
void *CacheBlock, *DecompressBlock;
z_stream zip_info;
FILE *mat_file;
size_t magick_size;
size_t extent;
int file;
int status;
int zip_status;
if(clone_info==NULL) return NULL;
if(clone_info->file) /* Close file opened from previous transaction. */
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
if(CacheBlock==NULL) return NULL;
DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
if(DecompressBlock==NULL)
{
RelinquishMagickMemory(CacheBlock);
return NULL;
}
mat_file=0;
file = AcquireUniqueFileResource(clone_info->filename);
if (file != -1)
mat_file = fdopen(file,"w");
if(!mat_file)
{
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image");
return NULL;
}
zip_info.zalloc=AcquireZIPMemory;
zip_info.zfree=RelinquishZIPMemory;
zip_info.opaque = (voidpf) NULL;
zip_status = inflateInit(&zip_info);
if (zip_status != Z_OK)
{
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"UnableToUncompressImage","`%s'",clone_info->filename);
(void) fclose(mat_file);
RelinquishUniqueFileResource(clone_info->filename);
return NULL;
}
/* zip_info.next_out = 8*4;*/
zip_info.avail_in = 0;
zip_info.total_out = 0;
while(Size>0 && !EOFBlob(orig))
{
magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
zip_info.next_in = (Bytef *) CacheBlock;
zip_info.avail_in = (uInt) magick_size;
while(zip_info.avail_in>0)
{
zip_info.avail_out = 4096;
zip_info.next_out = (Bytef *) DecompressBlock;
zip_status = inflate(&zip_info,Z_NO_FLUSH);
if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
break;
extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
(void) extent;
if(zip_status == Z_STREAM_END) goto DblBreak;
}
if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
break;
Size -= magick_size;
}
DblBreak:
inflateEnd(&zip_info);
(void)fclose(mat_file);
RelinquishMagickMemory(CacheBlock);
RelinquishMagickMemory(DecompressBlock);
if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
DeleteImageFromList(&image2);
EraseFile:
fclose(clone_info->file);
clone_info->file = NULL;
UnlinkFile:
RelinquishUniqueFileResource(clone_info->filename);
return NULL;
}
return image2;
}
#endif
static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
typedef struct {
unsigned char Type[4];
unsigned int nRows;
unsigned int nCols;
unsigned int imagf;
unsigned int nameLen;
} MAT4_HDR;
long
ldblk;
EndianType
endian;
Image
*rotate_image;
MagickBooleanType
status;
MAT4_HDR
HDR;
QuantumInfo
*quantum_info;
QuantumFormatType
format_type;
register ssize_t
i;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned int
depth;
(void) SeekBlob(image,0,SEEK_SET);
while (EOFBlob(image) != MagickFalse)
{
/*
Object parser.
*/
ldblk=ReadBlobLSBLong(image);
if (EOFBlob(image) != MagickFalse)
break;
if ((ldblk > 9999) || (ldblk < 0))
break;
HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */
HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */
HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */
HDR.Type[0]=ldblk; /* M digit */
if (HDR.Type[3] != 0)
break; /* Data format */
if (HDR.Type[2] != 0)
break; /* Always 0 */
if (HDR.Type[0] == 0)
{
HDR.nRows=ReadBlobLSBLong(image);
HDR.nCols=ReadBlobLSBLong(image);
HDR.imagf=ReadBlobLSBLong(image);
HDR.nameLen=ReadBlobLSBLong(image);
endian=LSBEndian;
}
else
{
HDR.nRows=ReadBlobMSBLong(image);
HDR.nCols=ReadBlobMSBLong(image);
HDR.imagf=ReadBlobMSBLong(image);
HDR.nameLen=ReadBlobMSBLong(image);
endian=MSBEndian;
}
if ((HDR.imagf !=0) && (HDR.imagf !=1))
break;
if (HDR.nameLen > 0xFFFF)
break;
for (i=0; i < (ssize_t) HDR.nameLen; i++)
{
int
byte;
/*
Skip matrix name.
*/
byte=ReadBlobByte(image);
if (byte == EOF)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
image->columns=(size_t) HDR.nRows;
image->rows=(size_t) HDR.nCols;
SetImageColorspace(image,GRAYColorspace);
if (image_info->ping != MagickFalse)
{
Swap(image->columns,image->rows);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
return((Image *) NULL);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return((Image *) NULL);
switch(HDR.Type[1])
{
case 0:
format_type=FloatingPointQuantumFormat;
depth=64;
break;
case 1:
format_type=FloatingPointQuantumFormat;
depth=32;
break;
case 2:
format_type=UnsignedQuantumFormat;
depth=16;
break;
case 3:
format_type=SignedQuantumFormat;
depth=16;
break;
case 4:
format_type=UnsignedQuantumFormat;
depth=8;
break;
default:
format_type=UnsignedQuantumFormat;
depth=8;
break;
}
image->depth=depth;
if (HDR.Type[0] != 0)
SetQuantumEndian(image,quantum_info,MSBEndian);
status=SetQuantumFormat(image,quantum_info,format_type);
status=SetQuantumDepth(image,quantum_info,depth);
status=SetQuantumEndian(image,quantum_info,endian);
SetQuantumScale(quantum_info,1.0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels);
if (count == -1)
break;
q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))
FixSignedValues(q,image->columns);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (HDR.imagf == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
/*
Read complex pixels.
*/
count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels);
if (count == -1)
break;
if (HDR.Type[1] == 0)
InsertComplexDoubleRow((double *) pixels,y,image,0,0);
else
InsertComplexFloatRow((float *) pixels,y,image,0,0);
}
quantum_info=DestroyQuantumInfo(quantum_info);
rotate_image=RotateImage(image,90.0,exception);
if (rotate_image != (Image *) NULL)
{
image=DestroyImage(image);
image=rotate_image;
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M A T L A B i m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMATImage() reads an MAT X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadMATImage method is:
%
% Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadMATImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterMATImage adds attributes for the MAT image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMATImage method is:
%
% size_t RegisterMATImage(void)
%
*/
ModuleExport size_t RegisterMATImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MAT");
entry->decoder=(DecodeImageHandler *) ReadMATImage;
entry->encoder=(EncodeImageHandler *) WriteMATImage;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=AcquireString("MATLAB level 5 image format");
entry->module=AcquireString("MAT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M A T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterMATImage removes format registrations made by the
% MAT module from the list of supported formats.
%
% The format of the UnregisterMATImage method is:
%
% UnregisterMATImage(void)
%
*/
ModuleExport void UnregisterMATImage(void)
{
(void) UnregisterMagickInfo("MAT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M A T L A B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Function WriteMATImage writes an Matlab matrix to a file.
%
% The format of the WriteMATImage method is:
%
% unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o status: Function WriteMATImage return True if the image is written.
% False is returned is there is a memory shortage or if the image file
% fails to write.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o image: A pointer to an Image structure.
%
*/
static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
{
ExceptionInfo
*exception;
ssize_t y;
unsigned z;
const PixelPacket *p;
unsigned int status;
int logging;
size_t DataSize;
char padding;
char MATLAB_HDR[0x80];
time_t current_time;
struct tm local_time;
unsigned char *pixels;
int is_gray;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
(void) logging;
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(MagickFalse);
image->depth=8;
current_time=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(¤t_time,&local_time);
#else
(void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));
#endif
(void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),
"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
local_time.tm_sec,local_time.tm_year+1900);
MATLAB_HDR[0x7C]=0;
MATLAB_HDR[0x7D]=1;
MATLAB_HDR[0x7E]='I';
MATLAB_HDR[0x7F]='M';
(void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
scene=0;
do
{
(void) TransformImageColorspace(image,sRGBColorspace);
is_gray = SetImageGray(image,&image->exception);
z = is_gray ? 0 : 3;
/*
Store MAT header.
*/
DataSize = image->rows /*Y*/ * image->columns /*X*/;
if(!is_gray) DataSize *= 3 /*Z*/;
padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
(void) WriteBlobLSBLong(image, miMATRIX);
(void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
(void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
(void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
(void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
(void) WriteBlobLSBLong(image, 0);
(void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
(void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
(void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
(void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
if(!is_gray)
{
(void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
(void) WriteBlobLSBLong(image, 0);
}
(void) WriteBlobLSBShort(image, 1); /* 0xB0 */
(void) WriteBlobLSBShort(image, 1); /* 0xB2 */
(void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
(void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
(void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
/*
Store image data.
*/
exception=(&image->exception);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
do
{
for (y=0; y < (ssize_t)image->columns; y++)
{
p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
z2qtype[z],pixels,exception);
(void) WriteBlob(image,image->rows,pixels);
}
if (!SyncAuthenticPixels(image,exception))
break;
} while(z-- >= 2);
while(padding-->0) (void) WriteBlobByte(image,0);
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/bad_2741_0 |
crossvul-cpp_data_bad_1162_1 | /* Copyright 2011-2014 Autronica Fire and Security AS
*
* 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.
*
* Author(s):
* 2011-2014 Arvid Brodin, arvid.brodin@alten.se
*
* The HSR spec says never to forward the same frame twice on the same
* interface. A frame is identified by its source MAC address and its HSR
* sequence number. This code keeps track of senders and their sequence numbers
* to allow filtering of duplicate frames, and to detect HSR ring errors.
*/
#include <linux/if_ether.h>
#include <linux/etherdevice.h>
#include <linux/slab.h>
#include <linux/rculist.h>
#include "hsr_main.h"
#include "hsr_framereg.h"
#include "hsr_netlink.h"
struct hsr_node {
struct list_head mac_list;
unsigned char MacAddressA[ETH_ALEN];
unsigned char MacAddressB[ETH_ALEN];
/* Local slave through which AddrB frames are received from this node */
enum hsr_port_type AddrB_port;
unsigned long time_in[HSR_PT_PORTS];
bool time_in_stale[HSR_PT_PORTS];
u16 seq_out[HSR_PT_PORTS];
struct rcu_head rcu_head;
};
/* TODO: use hash lists for mac addresses (linux/jhash.h)? */
/* seq_nr_after(a, b) - return true if a is after (higher in sequence than) b,
* false otherwise.
*/
static bool seq_nr_after(u16 a, u16 b)
{
/* Remove inconsistency where
* seq_nr_after(a, b) == seq_nr_before(a, b)
*/
if ((int) b - a == 32768)
return false;
return (((s16) (b - a)) < 0);
}
#define seq_nr_before(a, b) seq_nr_after((b), (a))
#define seq_nr_after_or_eq(a, b) (!seq_nr_before((a), (b)))
#define seq_nr_before_or_eq(a, b) (!seq_nr_after((a), (b)))
bool hsr_addr_is_self(struct hsr_priv *hsr, unsigned char *addr)
{
struct hsr_node *node;
node = list_first_or_null_rcu(&hsr->self_node_db, struct hsr_node,
mac_list);
if (!node) {
WARN_ONCE(1, "HSR: No self node\n");
return false;
}
if (ether_addr_equal(addr, node->MacAddressA))
return true;
if (ether_addr_equal(addr, node->MacAddressB))
return true;
return false;
}
/* Search for mac entry. Caller must hold rcu read lock.
*/
static struct hsr_node *find_node_by_AddrA(struct list_head *node_db,
const unsigned char addr[ETH_ALEN])
{
struct hsr_node *node;
list_for_each_entry_rcu(node, node_db, mac_list) {
if (ether_addr_equal(node->MacAddressA, addr))
return node;
}
return NULL;
}
/* Helper for device init; the self_node_db is used in hsr_rcv() to recognize
* frames from self that's been looped over the HSR ring.
*/
int hsr_create_self_node(struct list_head *self_node_db,
unsigned char addr_a[ETH_ALEN],
unsigned char addr_b[ETH_ALEN])
{
struct hsr_node *node, *oldnode;
node = kmalloc(sizeof(*node), GFP_KERNEL);
if (!node)
return -ENOMEM;
ether_addr_copy(node->MacAddressA, addr_a);
ether_addr_copy(node->MacAddressB, addr_b);
rcu_read_lock();
oldnode = list_first_or_null_rcu(self_node_db,
struct hsr_node, mac_list);
if (oldnode) {
list_replace_rcu(&oldnode->mac_list, &node->mac_list);
rcu_read_unlock();
synchronize_rcu();
kfree(oldnode);
} else {
rcu_read_unlock();
list_add_tail_rcu(&node->mac_list, self_node_db);
}
return 0;
}
/* Allocate an hsr_node and add it to node_db. 'addr' is the node's AddressA;
* seq_out is used to initialize filtering of outgoing duplicate frames
* originating from the newly added node.
*/
struct hsr_node *hsr_add_node(struct list_head *node_db, unsigned char addr[],
u16 seq_out)
{
struct hsr_node *node;
unsigned long now;
int i;
node = kzalloc(sizeof(*node), GFP_ATOMIC);
if (!node)
return NULL;
ether_addr_copy(node->MacAddressA, addr);
/* We are only interested in time diffs here, so use current jiffies
* as initialization. (0 could trigger an spurious ring error warning).
*/
now = jiffies;
for (i = 0; i < HSR_PT_PORTS; i++)
node->time_in[i] = now;
for (i = 0; i < HSR_PT_PORTS; i++)
node->seq_out[i] = seq_out;
list_add_tail_rcu(&node->mac_list, node_db);
return node;
}
/* Get the hsr_node from which 'skb' was sent.
*/
struct hsr_node *hsr_get_node(struct hsr_port *port, struct sk_buff *skb,
bool is_sup)
{
struct list_head *node_db = &port->hsr->node_db;
struct hsr_node *node;
struct ethhdr *ethhdr;
u16 seq_out;
if (!skb_mac_header_was_set(skb))
return NULL;
ethhdr = (struct ethhdr *) skb_mac_header(skb);
list_for_each_entry_rcu(node, node_db, mac_list) {
if (ether_addr_equal(node->MacAddressA, ethhdr->h_source))
return node;
if (ether_addr_equal(node->MacAddressB, ethhdr->h_source))
return node;
}
/* Everyone may create a node entry, connected node to a HSR device. */
if (ethhdr->h_proto == htons(ETH_P_PRP)
|| ethhdr->h_proto == htons(ETH_P_HSR)) {
/* Use the existing sequence_nr from the tag as starting point
* for filtering duplicate frames.
*/
seq_out = hsr_get_skb_sequence_nr(skb) - 1;
} else {
/* this is called also for frames from master port and
* so warn only for non master ports
*/
if (port->type != HSR_PT_MASTER)
WARN_ONCE(1, "%s: Non-HSR frame\n", __func__);
seq_out = HSR_SEQNR_START;
}
return hsr_add_node(node_db, ethhdr->h_source, seq_out);
}
/* Use the Supervision frame's info about an eventual MacAddressB for merging
* nodes that has previously had their MacAddressB registered as a separate
* node.
*/
void hsr_handle_sup_frame(struct sk_buff *skb, struct hsr_node *node_curr,
struct hsr_port *port_rcv)
{
struct ethhdr *ethhdr;
struct hsr_node *node_real;
struct hsr_sup_payload *hsr_sp;
struct list_head *node_db;
int i;
ethhdr = (struct ethhdr *) skb_mac_header(skb);
/* Leave the ethernet header. */
skb_pull(skb, sizeof(struct ethhdr));
/* And leave the HSR tag. */
if (ethhdr->h_proto == htons(ETH_P_HSR))
skb_pull(skb, sizeof(struct hsr_tag));
/* And leave the HSR sup tag. */
skb_pull(skb, sizeof(struct hsr_sup_tag));
hsr_sp = (struct hsr_sup_payload *) skb->data;
/* Merge node_curr (registered on MacAddressB) into node_real */
node_db = &port_rcv->hsr->node_db;
node_real = find_node_by_AddrA(node_db, hsr_sp->MacAddressA);
if (!node_real)
/* No frame received from AddrA of this node yet */
node_real = hsr_add_node(node_db, hsr_sp->MacAddressA,
HSR_SEQNR_START - 1);
if (!node_real)
goto done; /* No mem */
if (node_real == node_curr)
/* Node has already been merged */
goto done;
ether_addr_copy(node_real->MacAddressB, ethhdr->h_source);
for (i = 0; i < HSR_PT_PORTS; i++) {
if (!node_curr->time_in_stale[i] &&
time_after(node_curr->time_in[i], node_real->time_in[i])) {
node_real->time_in[i] = node_curr->time_in[i];
node_real->time_in_stale[i] = node_curr->time_in_stale[i];
}
if (seq_nr_after(node_curr->seq_out[i], node_real->seq_out[i]))
node_real->seq_out[i] = node_curr->seq_out[i];
}
node_real->AddrB_port = port_rcv->type;
list_del_rcu(&node_curr->mac_list);
kfree_rcu(node_curr, rcu_head);
done:
skb_push(skb, sizeof(struct hsrv1_ethhdr_sp));
}
/* 'skb' is a frame meant for this host, that is to be passed to upper layers.
*
* If the frame was sent by a node's B interface, replace the source
* address with that node's "official" address (MacAddressA) so that upper
* layers recognize where it came from.
*/
void hsr_addr_subst_source(struct hsr_node *node, struct sk_buff *skb)
{
if (!skb_mac_header_was_set(skb)) {
WARN_ONCE(1, "%s: Mac header not set\n", __func__);
return;
}
memcpy(ð_hdr(skb)->h_source, node->MacAddressA, ETH_ALEN);
}
/* 'skb' is a frame meant for another host.
* 'port' is the outgoing interface
*
* Substitute the target (dest) MAC address if necessary, so the it matches the
* recipient interface MAC address, regardless of whether that is the
* recipient's A or B interface.
* This is needed to keep the packets flowing through switches that learn on
* which "side" the different interfaces are.
*/
void hsr_addr_subst_dest(struct hsr_node *node_src, struct sk_buff *skb,
struct hsr_port *port)
{
struct hsr_node *node_dst;
if (!skb_mac_header_was_set(skb)) {
WARN_ONCE(1, "%s: Mac header not set\n", __func__);
return;
}
if (!is_unicast_ether_addr(eth_hdr(skb)->h_dest))
return;
node_dst = find_node_by_AddrA(&port->hsr->node_db, eth_hdr(skb)->h_dest);
if (!node_dst) {
WARN_ONCE(1, "%s: Unknown node\n", __func__);
return;
}
if (port->type != node_dst->AddrB_port)
return;
ether_addr_copy(eth_hdr(skb)->h_dest, node_dst->MacAddressB);
}
void hsr_register_frame_in(struct hsr_node *node, struct hsr_port *port,
u16 sequence_nr)
{
/* Don't register incoming frames without a valid sequence number. This
* ensures entries of restarted nodes gets pruned so that they can
* re-register and resume communications.
*/
if (seq_nr_before(sequence_nr, node->seq_out[port->type]))
return;
node->time_in[port->type] = jiffies;
node->time_in_stale[port->type] = false;
}
/* 'skb' is a HSR Ethernet frame (with a HSR tag inserted), with a valid
* ethhdr->h_source address and skb->mac_header set.
*
* Return:
* 1 if frame can be shown to have been sent recently on this interface,
* 0 otherwise, or
* negative error code on error
*/
int hsr_register_frame_out(struct hsr_port *port, struct hsr_node *node,
u16 sequence_nr)
{
if (seq_nr_before_or_eq(sequence_nr, node->seq_out[port->type]))
return 1;
node->seq_out[port->type] = sequence_nr;
return 0;
}
static struct hsr_port *get_late_port(struct hsr_priv *hsr,
struct hsr_node *node)
{
if (node->time_in_stale[HSR_PT_SLAVE_A])
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_A);
if (node->time_in_stale[HSR_PT_SLAVE_B])
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_B);
if (time_after(node->time_in[HSR_PT_SLAVE_B],
node->time_in[HSR_PT_SLAVE_A] +
msecs_to_jiffies(MAX_SLAVE_DIFF)))
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_A);
if (time_after(node->time_in[HSR_PT_SLAVE_A],
node->time_in[HSR_PT_SLAVE_B] +
msecs_to_jiffies(MAX_SLAVE_DIFF)))
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_B);
return NULL;
}
/* Remove stale sequence_nr records. Called by timer every
* HSR_LIFE_CHECK_INTERVAL (two seconds or so).
*/
void hsr_prune_nodes(struct timer_list *t)
{
struct hsr_priv *hsr = from_timer(hsr, t, prune_timer);
struct hsr_node *node;
struct hsr_port *port;
unsigned long timestamp;
unsigned long time_a, time_b;
rcu_read_lock();
list_for_each_entry_rcu(node, &hsr->node_db, mac_list) {
/* Shorthand */
time_a = node->time_in[HSR_PT_SLAVE_A];
time_b = node->time_in[HSR_PT_SLAVE_B];
/* Check for timestamps old enough to risk wrap-around */
if (time_after(jiffies, time_a + MAX_JIFFY_OFFSET/2))
node->time_in_stale[HSR_PT_SLAVE_A] = true;
if (time_after(jiffies, time_b + MAX_JIFFY_OFFSET/2))
node->time_in_stale[HSR_PT_SLAVE_B] = true;
/* Get age of newest frame from node.
* At least one time_in is OK here; nodes get pruned long
* before both time_ins can get stale
*/
timestamp = time_a;
if (node->time_in_stale[HSR_PT_SLAVE_A] ||
(!node->time_in_stale[HSR_PT_SLAVE_B] &&
time_after(time_b, time_a)))
timestamp = time_b;
/* Warn of ring error only as long as we get frames at all */
if (time_is_after_jiffies(timestamp +
msecs_to_jiffies(1.5*MAX_SLAVE_DIFF))) {
rcu_read_lock();
port = get_late_port(hsr, node);
if (port != NULL)
hsr_nl_ringerror(hsr, node->MacAddressA, port);
rcu_read_unlock();
}
/* Prune old entries */
if (time_is_before_jiffies(timestamp +
msecs_to_jiffies(HSR_NODE_FORGET_TIME))) {
hsr_nl_nodedown(hsr, node->MacAddressA);
list_del_rcu(&node->mac_list);
/* Note that we need to free this entry later: */
kfree_rcu(node, rcu_head);
}
}
rcu_read_unlock();
}
void *hsr_get_next_node(struct hsr_priv *hsr, void *_pos,
unsigned char addr[ETH_ALEN])
{
struct hsr_node *node;
if (!_pos) {
node = list_first_or_null_rcu(&hsr->node_db,
struct hsr_node, mac_list);
if (node)
ether_addr_copy(addr, node->MacAddressA);
return node;
}
node = _pos;
list_for_each_entry_continue_rcu(node, &hsr->node_db, mac_list) {
ether_addr_copy(addr, node->MacAddressA);
return node;
}
return NULL;
}
int hsr_get_node_data(struct hsr_priv *hsr,
const unsigned char *addr,
unsigned char addr_b[ETH_ALEN],
unsigned int *addr_b_ifindex,
int *if1_age,
u16 *if1_seq,
int *if2_age,
u16 *if2_seq)
{
struct hsr_node *node;
struct hsr_port *port;
unsigned long tdiff;
rcu_read_lock();
node = find_node_by_AddrA(&hsr->node_db, addr);
if (!node) {
rcu_read_unlock();
return -ENOENT; /* No such entry */
}
ether_addr_copy(addr_b, node->MacAddressB);
tdiff = jiffies - node->time_in[HSR_PT_SLAVE_A];
if (node->time_in_stale[HSR_PT_SLAVE_A])
*if1_age = INT_MAX;
#if HZ <= MSEC_PER_SEC
else if (tdiff > msecs_to_jiffies(INT_MAX))
*if1_age = INT_MAX;
#endif
else
*if1_age = jiffies_to_msecs(tdiff);
tdiff = jiffies - node->time_in[HSR_PT_SLAVE_B];
if (node->time_in_stale[HSR_PT_SLAVE_B])
*if2_age = INT_MAX;
#if HZ <= MSEC_PER_SEC
else if (tdiff > msecs_to_jiffies(INT_MAX))
*if2_age = INT_MAX;
#endif
else
*if2_age = jiffies_to_msecs(tdiff);
/* Present sequence numbers as if they were incoming on interface */
*if1_seq = node->seq_out[HSR_PT_SLAVE_B];
*if2_seq = node->seq_out[HSR_PT_SLAVE_A];
if (node->AddrB_port != HSR_PT_NONE) {
port = hsr_port_get_hsr(hsr, node->AddrB_port);
*addr_b_ifindex = port->dev->ifindex;
} else {
*addr_b_ifindex = -1;
}
rcu_read_unlock();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/bad_1162_1 |
crossvul-cpp_data_good_1194_0 | // SPDX-License-Identifier: GPL-2.0-only
/*
* net/ipv6/fib6_rules.c IPv6 Routing Policy Rules
*
* Copyright (C)2003-2006 Helsinki University of Technology
* Copyright (C)2003-2006 USAGI/WIDE Project
*
* Authors
* Thomas Graf <tgraf@suug.ch>
* Ville Nuorvala <vnuorval@tcs.hut.fi>
*/
#include <linux/netdevice.h>
#include <linux/notifier.h>
#include <linux/export.h>
#include <net/fib_rules.h>
#include <net/ipv6.h>
#include <net/addrconf.h>
#include <net/ip6_route.h>
#include <net/netlink.h>
struct fib6_rule {
struct fib_rule common;
struct rt6key src;
struct rt6key dst;
u8 tclass;
};
static bool fib6_rule_matchall(const struct fib_rule *rule)
{
struct fib6_rule *r = container_of(rule, struct fib6_rule, common);
if (r->dst.plen || r->src.plen || r->tclass)
return false;
return fib_rule_matchall(rule);
}
bool fib6_rule_default(const struct fib_rule *rule)
{
if (!fib6_rule_matchall(rule) || rule->action != FR_ACT_TO_TBL ||
rule->l3mdev)
return false;
if (rule->table != RT6_TABLE_LOCAL && rule->table != RT6_TABLE_MAIN)
return false;
return true;
}
EXPORT_SYMBOL_GPL(fib6_rule_default);
int fib6_rules_dump(struct net *net, struct notifier_block *nb)
{
return fib_rules_dump(net, nb, AF_INET6);
}
unsigned int fib6_rules_seq_read(struct net *net)
{
return fib_rules_seq_read(net, AF_INET6);
}
/* called with rcu lock held; no reference taken on fib6_info */
int fib6_lookup(struct net *net, int oif, struct flowi6 *fl6,
struct fib6_result *res, int flags)
{
int err;
if (net->ipv6.fib6_has_custom_rules) {
struct fib_lookup_arg arg = {
.lookup_ptr = fib6_table_lookup,
.lookup_data = &oif,
.result = res,
.flags = FIB_LOOKUP_NOREF,
};
l3mdev_update_flow(net, flowi6_to_flowi(fl6));
err = fib_rules_lookup(net->ipv6.fib6_rules_ops,
flowi6_to_flowi(fl6), flags, &arg);
} else {
err = fib6_table_lookup(net, net->ipv6.fib6_local_tbl, oif,
fl6, res, flags);
if (err || res->f6i == net->ipv6.fib6_null_entry)
err = fib6_table_lookup(net, net->ipv6.fib6_main_tbl,
oif, fl6, res, flags);
}
return err;
}
struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6,
const struct sk_buff *skb,
int flags, pol_lookup_t lookup)
{
if (net->ipv6.fib6_has_custom_rules) {
struct fib6_result res = {};
struct fib_lookup_arg arg = {
.lookup_ptr = lookup,
.lookup_data = skb,
.result = &res,
.flags = FIB_LOOKUP_NOREF,
};
/* update flow if oif or iif point to device enslaved to l3mdev */
l3mdev_update_flow(net, flowi6_to_flowi(fl6));
fib_rules_lookup(net->ipv6.fib6_rules_ops,
flowi6_to_flowi(fl6), flags, &arg);
if (res.rt6)
return &res.rt6->dst;
} else {
struct rt6_info *rt;
rt = lookup(net, net->ipv6.fib6_local_tbl, fl6, skb, flags);
if (rt != net->ipv6.ip6_null_entry && rt->dst.error != -EAGAIN)
return &rt->dst;
ip6_rt_put_flags(rt, flags);
rt = lookup(net, net->ipv6.fib6_main_tbl, fl6, skb, flags);
if (rt->dst.error != -EAGAIN)
return &rt->dst;
ip6_rt_put_flags(rt, flags);
}
if (!(flags & RT6_LOOKUP_F_DST_NOREF))
dst_hold(&net->ipv6.ip6_null_entry->dst);
return &net->ipv6.ip6_null_entry->dst;
}
static int fib6_rule_saddr(struct net *net, struct fib_rule *rule, int flags,
struct flowi6 *flp6, const struct net_device *dev)
{
struct fib6_rule *r = (struct fib6_rule *)rule;
/* If we need to find a source address for this traffic,
* we check the result if it meets requirement of the rule.
*/
if ((rule->flags & FIB_RULE_FIND_SADDR) &&
r->src.plen && !(flags & RT6_LOOKUP_F_HAS_SADDR)) {
struct in6_addr saddr;
if (ipv6_dev_get_saddr(net, dev, &flp6->daddr,
rt6_flags2srcprefs(flags), &saddr))
return -EAGAIN;
if (!ipv6_prefix_equal(&saddr, &r->src.addr, r->src.plen))
return -EAGAIN;
flp6->saddr = saddr;
}
return 0;
}
static int fib6_rule_action_alt(struct fib_rule *rule, struct flowi *flp,
int flags, struct fib_lookup_arg *arg)
{
struct fib6_result *res = arg->result;
struct flowi6 *flp6 = &flp->u.ip6;
struct net *net = rule->fr_net;
struct fib6_table *table;
int err, *oif;
u32 tb_id;
switch (rule->action) {
case FR_ACT_TO_TBL:
break;
case FR_ACT_UNREACHABLE:
return -ENETUNREACH;
case FR_ACT_PROHIBIT:
return -EACCES;
case FR_ACT_BLACKHOLE:
default:
return -EINVAL;
}
tb_id = fib_rule_get_table(rule, arg);
table = fib6_get_table(net, tb_id);
if (!table)
return -EAGAIN;
oif = (int *)arg->lookup_data;
err = fib6_table_lookup(net, table, *oif, flp6, res, flags);
if (!err && res->f6i != net->ipv6.fib6_null_entry)
err = fib6_rule_saddr(net, rule, flags, flp6,
res->nh->fib_nh_dev);
else
err = -EAGAIN;
return err;
}
static int __fib6_rule_action(struct fib_rule *rule, struct flowi *flp,
int flags, struct fib_lookup_arg *arg)
{
struct fib6_result *res = arg->result;
struct flowi6 *flp6 = &flp->u.ip6;
struct rt6_info *rt = NULL;
struct fib6_table *table;
struct net *net = rule->fr_net;
pol_lookup_t lookup = arg->lookup_ptr;
int err = 0;
u32 tb_id;
switch (rule->action) {
case FR_ACT_TO_TBL:
break;
case FR_ACT_UNREACHABLE:
err = -ENETUNREACH;
rt = net->ipv6.ip6_null_entry;
goto discard_pkt;
default:
case FR_ACT_BLACKHOLE:
err = -EINVAL;
rt = net->ipv6.ip6_blk_hole_entry;
goto discard_pkt;
case FR_ACT_PROHIBIT:
err = -EACCES;
rt = net->ipv6.ip6_prohibit_entry;
goto discard_pkt;
}
tb_id = fib_rule_get_table(rule, arg);
table = fib6_get_table(net, tb_id);
if (!table) {
err = -EAGAIN;
goto out;
}
rt = lookup(net, table, flp6, arg->lookup_data, flags);
if (rt != net->ipv6.ip6_null_entry) {
err = fib6_rule_saddr(net, rule, flags, flp6,
ip6_dst_idev(&rt->dst)->dev);
if (err == -EAGAIN)
goto again;
err = rt->dst.error;
if (err != -EAGAIN)
goto out;
}
again:
ip6_rt_put_flags(rt, flags);
err = -EAGAIN;
rt = NULL;
goto out;
discard_pkt:
if (!(flags & RT6_LOOKUP_F_DST_NOREF))
dst_hold(&rt->dst);
out:
res->rt6 = rt;
return err;
}
static int fib6_rule_action(struct fib_rule *rule, struct flowi *flp,
int flags, struct fib_lookup_arg *arg)
{
if (arg->lookup_ptr == fib6_table_lookup)
return fib6_rule_action_alt(rule, flp, flags, arg);
return __fib6_rule_action(rule, flp, flags, arg);
}
static bool fib6_rule_suppress(struct fib_rule *rule, struct fib_lookup_arg *arg)
{
struct fib6_result *res = arg->result;
struct rt6_info *rt = res->rt6;
struct net_device *dev = NULL;
if (!rt)
return false;
if (rt->rt6i_idev)
dev = rt->rt6i_idev->dev;
/* do not accept result if the route does
* not meet the required prefix length
*/
if (rt->rt6i_dst.plen <= rule->suppress_prefixlen)
goto suppress_route;
/* do not accept result if the route uses a device
* belonging to a forbidden interface group
*/
if (rule->suppress_ifgroup != -1 && dev && dev->group == rule->suppress_ifgroup)
goto suppress_route;
return false;
suppress_route:
if (!(arg->flags & FIB_LOOKUP_NOREF))
ip6_rt_put(rt);
return true;
}
static int fib6_rule_match(struct fib_rule *rule, struct flowi *fl, int flags)
{
struct fib6_rule *r = (struct fib6_rule *) rule;
struct flowi6 *fl6 = &fl->u.ip6;
if (r->dst.plen &&
!ipv6_prefix_equal(&fl6->daddr, &r->dst.addr, r->dst.plen))
return 0;
/*
* If FIB_RULE_FIND_SADDR is set and we do not have a
* source address for the traffic, we defer check for
* source address.
*/
if (r->src.plen) {
if (flags & RT6_LOOKUP_F_HAS_SADDR) {
if (!ipv6_prefix_equal(&fl6->saddr, &r->src.addr,
r->src.plen))
return 0;
} else if (!(r->common.flags & FIB_RULE_FIND_SADDR))
return 0;
}
if (r->tclass && r->tclass != ip6_tclass(fl6->flowlabel))
return 0;
if (rule->ip_proto && (rule->ip_proto != fl6->flowi6_proto))
return 0;
if (fib_rule_port_range_set(&rule->sport_range) &&
!fib_rule_port_inrange(&rule->sport_range, fl6->fl6_sport))
return 0;
if (fib_rule_port_range_set(&rule->dport_range) &&
!fib_rule_port_inrange(&rule->dport_range, fl6->fl6_dport))
return 0;
return 1;
}
static const struct nla_policy fib6_rule_policy[FRA_MAX+1] = {
FRA_GENERIC_POLICY,
};
static int fib6_rule_configure(struct fib_rule *rule, struct sk_buff *skb,
struct fib_rule_hdr *frh,
struct nlattr **tb,
struct netlink_ext_ack *extack)
{
int err = -EINVAL;
struct net *net = sock_net(skb->sk);
struct fib6_rule *rule6 = (struct fib6_rule *) rule;
if (rule->action == FR_ACT_TO_TBL && !rule->l3mdev) {
if (rule->table == RT6_TABLE_UNSPEC) {
NL_SET_ERR_MSG(extack, "Invalid table");
goto errout;
}
if (fib6_new_table(net, rule->table) == NULL) {
err = -ENOBUFS;
goto errout;
}
}
if (frh->src_len)
rule6->src.addr = nla_get_in6_addr(tb[FRA_SRC]);
if (frh->dst_len)
rule6->dst.addr = nla_get_in6_addr(tb[FRA_DST]);
rule6->src.plen = frh->src_len;
rule6->dst.plen = frh->dst_len;
rule6->tclass = frh->tos;
if (fib_rule_requires_fldissect(rule))
net->ipv6.fib6_rules_require_fldissect++;
net->ipv6.fib6_has_custom_rules = true;
err = 0;
errout:
return err;
}
static int fib6_rule_delete(struct fib_rule *rule)
{
struct net *net = rule->fr_net;
if (net->ipv6.fib6_rules_require_fldissect &&
fib_rule_requires_fldissect(rule))
net->ipv6.fib6_rules_require_fldissect--;
return 0;
}
static int fib6_rule_compare(struct fib_rule *rule, struct fib_rule_hdr *frh,
struct nlattr **tb)
{
struct fib6_rule *rule6 = (struct fib6_rule *) rule;
if (frh->src_len && (rule6->src.plen != frh->src_len))
return 0;
if (frh->dst_len && (rule6->dst.plen != frh->dst_len))
return 0;
if (frh->tos && (rule6->tclass != frh->tos))
return 0;
if (frh->src_len &&
nla_memcmp(tb[FRA_SRC], &rule6->src.addr, sizeof(struct in6_addr)))
return 0;
if (frh->dst_len &&
nla_memcmp(tb[FRA_DST], &rule6->dst.addr, sizeof(struct in6_addr)))
return 0;
return 1;
}
static int fib6_rule_fill(struct fib_rule *rule, struct sk_buff *skb,
struct fib_rule_hdr *frh)
{
struct fib6_rule *rule6 = (struct fib6_rule *) rule;
frh->dst_len = rule6->dst.plen;
frh->src_len = rule6->src.plen;
frh->tos = rule6->tclass;
if ((rule6->dst.plen &&
nla_put_in6_addr(skb, FRA_DST, &rule6->dst.addr)) ||
(rule6->src.plen &&
nla_put_in6_addr(skb, FRA_SRC, &rule6->src.addr)))
goto nla_put_failure;
return 0;
nla_put_failure:
return -ENOBUFS;
}
static size_t fib6_rule_nlmsg_payload(struct fib_rule *rule)
{
return nla_total_size(16) /* dst */
+ nla_total_size(16); /* src */
}
static const struct fib_rules_ops __net_initconst fib6_rules_ops_template = {
.family = AF_INET6,
.rule_size = sizeof(struct fib6_rule),
.addr_size = sizeof(struct in6_addr),
.action = fib6_rule_action,
.match = fib6_rule_match,
.suppress = fib6_rule_suppress,
.configure = fib6_rule_configure,
.delete = fib6_rule_delete,
.compare = fib6_rule_compare,
.fill = fib6_rule_fill,
.nlmsg_payload = fib6_rule_nlmsg_payload,
.nlgroup = RTNLGRP_IPV6_RULE,
.policy = fib6_rule_policy,
.owner = THIS_MODULE,
.fro_net = &init_net,
};
static int __net_init fib6_rules_net_init(struct net *net)
{
struct fib_rules_ops *ops;
int err = -ENOMEM;
ops = fib_rules_register(&fib6_rules_ops_template, net);
if (IS_ERR(ops))
return PTR_ERR(ops);
err = fib_default_rule_add(ops, 0, RT6_TABLE_LOCAL, 0);
if (err)
goto out_fib6_rules_ops;
err = fib_default_rule_add(ops, 0x7FFE, RT6_TABLE_MAIN, 0);
if (err)
goto out_fib6_rules_ops;
net->ipv6.fib6_rules_ops = ops;
net->ipv6.fib6_rules_require_fldissect = 0;
out:
return err;
out_fib6_rules_ops:
fib_rules_unregister(ops);
goto out;
}
static void __net_exit fib6_rules_net_exit(struct net *net)
{
rtnl_lock();
fib_rules_unregister(net->ipv6.fib6_rules_ops);
rtnl_unlock();
}
static struct pernet_operations fib6_rules_net_ops = {
.init = fib6_rules_net_init,
.exit = fib6_rules_net_exit,
};
int __init fib6_rules_init(void)
{
return register_pernet_subsys(&fib6_rules_net_ops);
}
void fib6_rules_cleanup(void)
{
unregister_pernet_subsys(&fib6_rules_net_ops);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_1194_0 |
crossvul-cpp_data_good_2619_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP IIIII CCCC TTTTT %
% P P I C T %
% PPPP I C T %
% P I C T %
% P IIIII CCCC T %
% %
% %
% Read/Write Apple Macintosh QuickDraw/PICT Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
#include "magick/utility.h"
/*
ImageMagick Macintosh PICT Methods.
*/
#define ReadPixmap(pixmap) \
{ \
pixmap.version=(short) ReadBlobMSBShort(image); \
pixmap.pack_type=(short) ReadBlobMSBShort(image); \
pixmap.pack_size=ReadBlobMSBLong(image); \
pixmap.horizontal_resolution=1UL*ReadBlobMSBShort(image); \
(void) ReadBlobMSBShort(image); \
pixmap.vertical_resolution=1UL*ReadBlobMSBShort(image); \
(void) ReadBlobMSBShort(image); \
pixmap.pixel_type=(short) ReadBlobMSBShort(image); \
pixmap.bits_per_pixel=(short) ReadBlobMSBShort(image); \
pixmap.component_count=(short) ReadBlobMSBShort(image); \
pixmap.component_size=(short) ReadBlobMSBShort(image); \
pixmap.plane_bytes=ReadBlobMSBLong(image); \
pixmap.table=ReadBlobMSBLong(image); \
pixmap.reserved=ReadBlobMSBLong(image); \
if ((EOFBlob(image) != MagickFalse) || (pixmap.bits_per_pixel <= 0) || \
(pixmap.bits_per_pixel > 32) || (pixmap.component_count <= 0) || \
(pixmap.component_count > 4) || (pixmap.component_size <= 0)) \
ThrowReaderException(CorruptImageError,"ImproperImageHeader"); \
}
typedef struct _PICTCode
{
const char
*name;
ssize_t
length;
const char
*description;
} PICTCode;
typedef struct _PICTPixmap
{
short
version,
pack_type;
size_t
pack_size,
horizontal_resolution,
vertical_resolution;
short
pixel_type,
bits_per_pixel,
component_count,
component_size;
size_t
plane_bytes,
table,
reserved;
} PICTPixmap;
typedef struct _PICTRectangle
{
short
top,
left,
bottom,
right;
} PICTRectangle;
static const PICTCode
codes[] =
{
/* 0x00 */ { "NOP", 0, "nop" },
/* 0x01 */ { "Clip", 0, "clip" },
/* 0x02 */ { "BkPat", 8, "background pattern" },
/* 0x03 */ { "TxFont", 2, "text font (word)" },
/* 0x04 */ { "TxFace", 1, "text face (byte)" },
/* 0x05 */ { "TxMode", 2, "text mode (word)" },
/* 0x06 */ { "SpExtra", 4, "space extra (fixed point)" },
/* 0x07 */ { "PnSize", 4, "pen size (point)" },
/* 0x08 */ { "PnMode", 2, "pen mode (word)" },
/* 0x09 */ { "PnPat", 8, "pen pattern" },
/* 0x0a */ { "FillPat", 8, "fill pattern" },
/* 0x0b */ { "OvSize", 4, "oval size (point)" },
/* 0x0c */ { "Origin", 4, "dh, dv (word)" },
/* 0x0d */ { "TxSize", 2, "text size (word)" },
/* 0x0e */ { "FgColor", 4, "foreground color (ssize_tword)" },
/* 0x0f */ { "BkColor", 4, "background color (ssize_tword)" },
/* 0x10 */ { "TxRatio", 8, "numerator (point), denominator (point)" },
/* 0x11 */ { "Version", 1, "version (byte)" },
/* 0x12 */ { "BkPixPat", 0, "color background pattern" },
/* 0x13 */ { "PnPixPat", 0, "color pen pattern" },
/* 0x14 */ { "FillPixPat", 0, "color fill pattern" },
/* 0x15 */ { "PnLocHFrac", 2, "fractional pen position" },
/* 0x16 */ { "ChExtra", 2, "extra for each character" },
/* 0x17 */ { "reserved", 0, "reserved for Apple use" },
/* 0x18 */ { "reserved", 0, "reserved for Apple use" },
/* 0x19 */ { "reserved", 0, "reserved for Apple use" },
/* 0x1a */ { "RGBFgCol", 6, "RGB foreColor" },
/* 0x1b */ { "RGBBkCol", 6, "RGB backColor" },
/* 0x1c */ { "HiliteMode", 0, "hilite mode flag" },
/* 0x1d */ { "HiliteColor", 6, "RGB hilite color" },
/* 0x1e */ { "DefHilite", 0, "Use default hilite color" },
/* 0x1f */ { "OpColor", 6, "RGB OpColor for arithmetic modes" },
/* 0x20 */ { "Line", 8, "pnLoc (point), newPt (point)" },
/* 0x21 */ { "LineFrom", 4, "newPt (point)" },
/* 0x22 */ { "ShortLine", 6, "pnLoc (point, dh, dv (-128 .. 127))" },
/* 0x23 */ { "ShortLineFrom", 2, "dh, dv (-128 .. 127)" },
/* 0x24 */ { "reserved", -1, "reserved for Apple use" },
/* 0x25 */ { "reserved", -1, "reserved for Apple use" },
/* 0x26 */ { "reserved", -1, "reserved for Apple use" },
/* 0x27 */ { "reserved", -1, "reserved for Apple use" },
/* 0x28 */ { "LongText", 0, "txLoc (point), count (0..255), text" },
/* 0x29 */ { "DHText", 0, "dh (0..255), count (0..255), text" },
/* 0x2a */ { "DVText", 0, "dv (0..255), count (0..255), text" },
/* 0x2b */ { "DHDVText", 0, "dh, dv (0..255), count (0..255), text" },
/* 0x2c */ { "reserved", -1, "reserved for Apple use" },
/* 0x2d */ { "reserved", -1, "reserved for Apple use" },
/* 0x2e */ { "reserved", -1, "reserved for Apple use" },
/* 0x2f */ { "reserved", -1, "reserved for Apple use" },
/* 0x30 */ { "frameRect", 8, "rect" },
/* 0x31 */ { "paintRect", 8, "rect" },
/* 0x32 */ { "eraseRect", 8, "rect" },
/* 0x33 */ { "invertRect", 8, "rect" },
/* 0x34 */ { "fillRect", 8, "rect" },
/* 0x35 */ { "reserved", 8, "reserved for Apple use" },
/* 0x36 */ { "reserved", 8, "reserved for Apple use" },
/* 0x37 */ { "reserved", 8, "reserved for Apple use" },
/* 0x38 */ { "frameSameRect", 0, "rect" },
/* 0x39 */ { "paintSameRect", 0, "rect" },
/* 0x3a */ { "eraseSameRect", 0, "rect" },
/* 0x3b */ { "invertSameRect", 0, "rect" },
/* 0x3c */ { "fillSameRect", 0, "rect" },
/* 0x3d */ { "reserved", 0, "reserved for Apple use" },
/* 0x3e */ { "reserved", 0, "reserved for Apple use" },
/* 0x3f */ { "reserved", 0, "reserved for Apple use" },
/* 0x40 */ { "frameRRect", 8, "rect" },
/* 0x41 */ { "paintRRect", 8, "rect" },
/* 0x42 */ { "eraseRRect", 8, "rect" },
/* 0x43 */ { "invertRRect", 8, "rect" },
/* 0x44 */ { "fillRRrect", 8, "rect" },
/* 0x45 */ { "reserved", 8, "reserved for Apple use" },
/* 0x46 */ { "reserved", 8, "reserved for Apple use" },
/* 0x47 */ { "reserved", 8, "reserved for Apple use" },
/* 0x48 */ { "frameSameRRect", 0, "rect" },
/* 0x49 */ { "paintSameRRect", 0, "rect" },
/* 0x4a */ { "eraseSameRRect", 0, "rect" },
/* 0x4b */ { "invertSameRRect", 0, "rect" },
/* 0x4c */ { "fillSameRRect", 0, "rect" },
/* 0x4d */ { "reserved", 0, "reserved for Apple use" },
/* 0x4e */ { "reserved", 0, "reserved for Apple use" },
/* 0x4f */ { "reserved", 0, "reserved for Apple use" },
/* 0x50 */ { "frameOval", 8, "rect" },
/* 0x51 */ { "paintOval", 8, "rect" },
/* 0x52 */ { "eraseOval", 8, "rect" },
/* 0x53 */ { "invertOval", 8, "rect" },
/* 0x54 */ { "fillOval", 8, "rect" },
/* 0x55 */ { "reserved", 8, "reserved for Apple use" },
/* 0x56 */ { "reserved", 8, "reserved for Apple use" },
/* 0x57 */ { "reserved", 8, "reserved for Apple use" },
/* 0x58 */ { "frameSameOval", 0, "rect" },
/* 0x59 */ { "paintSameOval", 0, "rect" },
/* 0x5a */ { "eraseSameOval", 0, "rect" },
/* 0x5b */ { "invertSameOval", 0, "rect" },
/* 0x5c */ { "fillSameOval", 0, "rect" },
/* 0x5d */ { "reserved", 0, "reserved for Apple use" },
/* 0x5e */ { "reserved", 0, "reserved for Apple use" },
/* 0x5f */ { "reserved", 0, "reserved for Apple use" },
/* 0x60 */ { "frameArc", 12, "rect, startAngle, arcAngle" },
/* 0x61 */ { "paintArc", 12, "rect, startAngle, arcAngle" },
/* 0x62 */ { "eraseArc", 12, "rect, startAngle, arcAngle" },
/* 0x63 */ { "invertArc", 12, "rect, startAngle, arcAngle" },
/* 0x64 */ { "fillArc", 12, "rect, startAngle, arcAngle" },
/* 0x65 */ { "reserved", 12, "reserved for Apple use" },
/* 0x66 */ { "reserved", 12, "reserved for Apple use" },
/* 0x67 */ { "reserved", 12, "reserved for Apple use" },
/* 0x68 */ { "frameSameArc", 4, "rect, startAngle, arcAngle" },
/* 0x69 */ { "paintSameArc", 4, "rect, startAngle, arcAngle" },
/* 0x6a */ { "eraseSameArc", 4, "rect, startAngle, arcAngle" },
/* 0x6b */ { "invertSameArc", 4, "rect, startAngle, arcAngle" },
/* 0x6c */ { "fillSameArc", 4, "rect, startAngle, arcAngle" },
/* 0x6d */ { "reserved", 4, "reserved for Apple use" },
/* 0x6e */ { "reserved", 4, "reserved for Apple use" },
/* 0x6f */ { "reserved", 4, "reserved for Apple use" },
/* 0x70 */ { "framePoly", 0, "poly" },
/* 0x71 */ { "paintPoly", 0, "poly" },
/* 0x72 */ { "erasePoly", 0, "poly" },
/* 0x73 */ { "invertPoly", 0, "poly" },
/* 0x74 */ { "fillPoly", 0, "poly" },
/* 0x75 */ { "reserved", 0, "reserved for Apple use" },
/* 0x76 */ { "reserved", 0, "reserved for Apple use" },
/* 0x77 */ { "reserved", 0, "reserved for Apple use" },
/* 0x78 */ { "frameSamePoly", 0, "poly (NYI)" },
/* 0x79 */ { "paintSamePoly", 0, "poly (NYI)" },
/* 0x7a */ { "eraseSamePoly", 0, "poly (NYI)" },
/* 0x7b */ { "invertSamePoly", 0, "poly (NYI)" },
/* 0x7c */ { "fillSamePoly", 0, "poly (NYI)" },
/* 0x7d */ { "reserved", 0, "reserved for Apple use" },
/* 0x7e */ { "reserved", 0, "reserved for Apple use" },
/* 0x7f */ { "reserved", 0, "reserved for Apple use" },
/* 0x80 */ { "frameRgn", 0, "region" },
/* 0x81 */ { "paintRgn", 0, "region" },
/* 0x82 */ { "eraseRgn", 0, "region" },
/* 0x83 */ { "invertRgn", 0, "region" },
/* 0x84 */ { "fillRgn", 0, "region" },
/* 0x85 */ { "reserved", 0, "reserved for Apple use" },
/* 0x86 */ { "reserved", 0, "reserved for Apple use" },
/* 0x87 */ { "reserved", 0, "reserved for Apple use" },
/* 0x88 */ { "frameSameRgn", 0, "region (NYI)" },
/* 0x89 */ { "paintSameRgn", 0, "region (NYI)" },
/* 0x8a */ { "eraseSameRgn", 0, "region (NYI)" },
/* 0x8b */ { "invertSameRgn", 0, "region (NYI)" },
/* 0x8c */ { "fillSameRgn", 0, "region (NYI)" },
/* 0x8d */ { "reserved", 0, "reserved for Apple use" },
/* 0x8e */ { "reserved", 0, "reserved for Apple use" },
/* 0x8f */ { "reserved", 0, "reserved for Apple use" },
/* 0x90 */ { "BitsRect", 0, "copybits, rect clipped" },
/* 0x91 */ { "BitsRgn", 0, "copybits, rgn clipped" },
/* 0x92 */ { "reserved", -1, "reserved for Apple use" },
/* 0x93 */ { "reserved", -1, "reserved for Apple use" },
/* 0x94 */ { "reserved", -1, "reserved for Apple use" },
/* 0x95 */ { "reserved", -1, "reserved for Apple use" },
/* 0x96 */ { "reserved", -1, "reserved for Apple use" },
/* 0x97 */ { "reserved", -1, "reserved for Apple use" },
/* 0x98 */ { "PackBitsRect", 0, "packed copybits, rect clipped" },
/* 0x99 */ { "PackBitsRgn", 0, "packed copybits, rgn clipped" },
/* 0x9a */ { "DirectBitsRect", 0, "PixMap, srcRect, dstRect, mode, PixData" },
/* 0x9b */ { "DirectBitsRgn", 0, "PixMap, srcRect, dstRect, mode, maskRgn, PixData" },
/* 0x9c */ { "reserved", -1, "reserved for Apple use" },
/* 0x9d */ { "reserved", -1, "reserved for Apple use" },
/* 0x9e */ { "reserved", -1, "reserved for Apple use" },
/* 0x9f */ { "reserved", -1, "reserved for Apple use" },
/* 0xa0 */ { "ShortComment", 2, "kind (word)" },
/* 0xa1 */ { "LongComment", 0, "kind (word), size (word), data" }
};
/*
Forward declarations.
*/
static MagickBooleanType
WritePICTImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e c o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecodeImage decompresses an image via Macintosh pack bits decoding for
% Macintosh PICT images.
%
% The format of the DecodeImage method is:
%
% unsigned char *DecodeImage(Image *blob,Image *image,
% size_t bytes_per_line,const int bits_per_pixel,
% unsigned size_t extent)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o blob,image: the address of a structure of type Image.
%
% o bytes_per_line: This integer identifies the number of bytes in a
% scanline.
%
% o bits_per_pixel: the number of bits in a pixel.
%
% o extent: the number of pixels allocated.
%
*/
static unsigned char *ExpandBuffer(unsigned char *pixels,
MagickSizeType *bytes_per_line,const unsigned int bits_per_pixel)
{
register ssize_t
i;
register unsigned char
*p,
*q;
static unsigned char
scanline[8*256];
p=pixels;
q=scanline;
switch (bits_per_pixel)
{
case 8:
case 16:
case 32:
return(pixels);
case 4:
{
for (i=0; i < (ssize_t) *bytes_per_line; i++)
{
*q++=(*p >> 4) & 0xff;
*q++=(*p & 15);
p++;
}
*bytes_per_line*=2;
break;
}
case 2:
{
for (i=0; i < (ssize_t) *bytes_per_line; i++)
{
*q++=(*p >> 6) & 0x03;
*q++=(*p >> 4) & 0x03;
*q++=(*p >> 2) & 0x03;
*q++=(*p & 3);
p++;
}
*bytes_per_line*=4;
break;
}
case 1:
{
for (i=0; i < (ssize_t) *bytes_per_line; i++)
{
*q++=(*p >> 7) & 0x01;
*q++=(*p >> 6) & 0x01;
*q++=(*p >> 5) & 0x01;
*q++=(*p >> 4) & 0x01;
*q++=(*p >> 3) & 0x01;
*q++=(*p >> 2) & 0x01;
*q++=(*p >> 1) & 0x01;
*q++=(*p & 0x01);
p++;
}
*bytes_per_line*=8;
break;
}
default:
break;
}
return(scanline);
}
static unsigned char *DecodeImage(Image *blob,Image *image,
size_t bytes_per_line,const unsigned int bits_per_pixel,size_t *extent)
{
MagickSizeType
number_pixels;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
bytes_per_pixel,
length,
row_bytes,
scanline_length,
width;
ssize_t
count,
j,
y;
unsigned char
*pixels,
*scanline;
/*
Determine pixel buffer size.
*/
if (bits_per_pixel <= 8)
bytes_per_line&=0x7fff;
width=image->columns;
bytes_per_pixel=1;
if (bits_per_pixel == 16)
{
bytes_per_pixel=2;
width*=2;
}
else
if (bits_per_pixel == 32)
width*=image->matte != MagickFalse ? 4 : 3;
if (bytes_per_line == 0)
bytes_per_line=width;
row_bytes=(size_t) (image->columns | 0x8000);
if (image->storage_class == DirectClass)
row_bytes=(size_t) ((4*image->columns) | 0x8000);
/*
Allocate pixel and scanline buffer.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->rows,row_bytes*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
return((unsigned char *) NULL);
*extent=row_bytes*image->rows*sizeof(*pixels);
(void) ResetMagickMemory(pixels,0,*extent);
scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,2*
sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
return((unsigned char *) NULL);
if (bytes_per_line < 8)
{
/*
Pixels are already uncompressed.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=pixels+y*width;
number_pixels=bytes_per_line;
count=ReadBlob(blob,(size_t) number_pixels,scanline);
if (count != (ssize_t) number_pixels)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",
image->filename);
break;
}
p=ExpandBuffer(scanline,&number_pixels,bits_per_pixel);
if ((q+number_pixels) > (pixels+(*extent)))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",
image->filename);
break;
}
(void) CopyMagickMemory(q,p,(size_t) number_pixels);
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
return(pixels);
}
/*
Uncompress RLE pixels into uncompressed pixel buffer.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=pixels+y*width;
if (bytes_per_line > 200)
scanline_length=ReadBlobMSBShort(blob);
else
scanline_length=1UL*ReadBlobByte(blob);
if (scanline_length >= row_bytes)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",image->filename);
break;
}
count=ReadBlob(blob,scanline_length,scanline);
if (count != (ssize_t) scanline_length)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",image->filename);
break;
}
for (j=0; j < (ssize_t) scanline_length; )
if ((scanline[j] & 0x80) == 0)
{
length=(size_t) ((scanline[j] & 0xff)+1);
number_pixels=length*bytes_per_pixel;
p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel);
if ((q-pixels+number_pixels) <= *extent)
(void) CopyMagickMemory(q,p,(size_t) number_pixels);
q+=number_pixels;
j+=(ssize_t) (length*bytes_per_pixel+1);
}
else
{
length=(size_t) (((scanline[j] ^ 0xff) & 0xff)+2);
number_pixels=bytes_per_pixel;
p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel);
for (i=0; i < (ssize_t) length; i++)
{
if ((q-pixels+number_pixels) <= *extent)
(void) CopyMagickMemory(q,p,(size_t) number_pixels);
q+=number_pixels;
}
j+=(ssize_t) bytes_per_pixel+1;
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E n c o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EncodeImage compresses an image via Macintosh pack bits encoding
% for Macintosh PICT images.
%
% The format of the EncodeImage method is:
%
% size_t EncodeImage(Image *image,const unsigned char *scanline,
% const size_t bytes_per_line,unsigned char *pixels)
%
% A description of each parameter follows:
%
% o image: the address of a structure of type Image.
%
% o scanline: A pointer to an array of characters to pack.
%
% o bytes_per_line: the number of bytes in a scanline.
%
% o pixels: A pointer to an array of characters where the packed
% characters are stored.
%
*/
static size_t EncodeImage(Image *image,const unsigned char *scanline,
const size_t bytes_per_line,unsigned char *pixels)
{
#define MaxCount 128
#define MaxPackbitsRunlength 128
register const unsigned char
*p;
register ssize_t
i;
register unsigned char
*q;
size_t
length;
ssize_t
count,
repeat_count,
runlength;
unsigned char
index;
/*
Pack scanline.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(scanline != (unsigned char *) NULL);
assert(pixels != (unsigned char *) NULL);
count=0;
runlength=0;
p=scanline+(bytes_per_line-1);
q=pixels;
index=(*p);
for (i=(ssize_t) bytes_per_line-1; i >= 0; i--)
{
if (index == *p)
runlength++;
else
{
if (runlength < 3)
while (runlength > 0)
{
*q++=(unsigned char) index;
runlength--;
count++;
if (count == MaxCount)
{
*q++=(unsigned char) (MaxCount-1);
count-=MaxCount;
}
}
else
{
if (count > 0)
*q++=(unsigned char) (count-1);
count=0;
while (runlength > 0)
{
repeat_count=runlength;
if (repeat_count > MaxPackbitsRunlength)
repeat_count=MaxPackbitsRunlength;
*q++=(unsigned char) index;
*q++=(unsigned char) (257-repeat_count);
runlength-=repeat_count;
}
}
runlength=1;
}
index=(*p);
p--;
}
if (runlength < 3)
while (runlength > 0)
{
*q++=(unsigned char) index;
runlength--;
count++;
if (count == MaxCount)
{
*q++=(unsigned char) (MaxCount-1);
count-=MaxCount;
}
}
else
{
if (count > 0)
*q++=(unsigned char) (count-1);
count=0;
while (runlength > 0)
{
repeat_count=runlength;
if (repeat_count > MaxPackbitsRunlength)
repeat_count=MaxPackbitsRunlength;
*q++=(unsigned char) index;
*q++=(unsigned char) (257-repeat_count);
runlength-=repeat_count;
}
}
if (count > 0)
*q++=(unsigned char) (count-1);
/*
Write the number of and the packed length.
*/
length=(size_t) (q-pixels);
if (bytes_per_line > 200)
{
(void) WriteBlobMSBShort(image,(unsigned short) length);
length+=2;
}
else
{
(void) WriteBlobByte(image,(unsigned char) length);
length++;
}
while (q != pixels)
{
q--;
(void) WriteBlobByte(image,*q);
}
return(length);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P I C T %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPICT()() returns MagickTrue if the image format type, identified by the
% magick string, is PICT.
%
% The format of the ReadPICTImage method is:
%
% MagickBooleanType IsPICT(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPICT(const unsigned char *magick,const size_t length)
{
/*
Embedded OLE2 macintosh have "PICT" instead of 512 platform header.
*/
if (length < 12)
return(MagickFalse);
if (memcmp(magick,"PICT",4) == 0)
return(MagickTrue);
if (length < 528)
return(MagickFalse);
if (memcmp(magick+522,"\000\021\002\377\014\000",6) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if !defined(macintosh)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P I C T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPICTImage() reads an Apple Macintosh QuickDraw/PICT image file
% and returns it. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the ReadPICTImage method is:
%
% Image *ReadPICTImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ReadRectangle(Image *image,PICTRectangle *rectangle)
{
rectangle->top=(short) ReadBlobMSBShort(image);
rectangle->left=(short) ReadBlobMSBShort(image);
rectangle->bottom=(short) ReadBlobMSBShort(image);
rectangle->right=(short) ReadBlobMSBShort(image);
if ((EOFBlob(image) != MagickFalse) || (rectangle->left > rectangle->right) ||
(rectangle->top > rectangle->bottom))
return(MagickFalse);
return(MagickTrue);
}
static Image *ReadPICTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
header_ole[4];
Image
*image;
IndexPacket
index;
int
c,
code;
MagickBooleanType
jpeg,
status;
PICTRectangle
frame;
PICTPixmap
pixmap;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
size_t
extent,
length;
ssize_t
count,
flags,
j,
version,
y;
StringInfo
*profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PICT header.
*/
pixmap.bits_per_pixel=0;
pixmap.component_count=0;
/*
Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2
*/
header_ole[0]=ReadBlobByte(image);
header_ole[1]=ReadBlobByte(image);
header_ole[2]=ReadBlobByte(image);
header_ole[3]=ReadBlobByte(image);
if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
(header_ole[2] == 0x43) && (header_ole[3] == 0x54)))
for (i=0; i < 508; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) ReadBlobMSBShort(image); /* skip picture size */
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
while ((c=ReadBlobByte(image)) == 0) ;
if (c != 0x11)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
version=ReadBlobByte(image);
if (version == 2)
{
c=ReadBlobByte(image);
if (c != 0xff)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
else
if (version != 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
(frame.bottom < 0) || (frame.left >= frame.right) ||
(frame.top >= frame.bottom))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Create black canvas.
*/
flags=0;
image->depth=8;
image->columns=1UL*(frame.right-frame.left);
image->rows=1UL*(frame.bottom-frame.top);
image->x_resolution=DefaultResolution;
image->y_resolution=DefaultResolution;
image->units=UndefinedResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Interpret PICT opcodes.
*/
jpeg=MagickFalse;
for (code=0; EOFBlob(image) == MagickFalse; )
{
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((version == 1) || ((TellBlob(image) % 2) != 0))
code=ReadBlobByte(image);
if (version == 2)
code=ReadBlobMSBSignedShort(image);
if (code < 0)
break;
if (code > 0xa1)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
}
else
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %04X %s: %s",code,codes[code].name,codes[code].description);
switch (code)
{
case 0x01:
{
/*
Clipping rectangle.
*/
length=ReadBlobMSBShort(image);
if (length != 0x000a)
{
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
break;
image->columns=1UL*(frame.right-frame.left);
image->rows=1UL*(frame.bottom-frame.top);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image);
break;
}
case 0x12:
case 0x13:
case 0x14:
{
ssize_t
pattern;
size_t
height,
width;
/*
Skip pattern definition.
*/
pattern=1L*ReadBlobMSBShort(image);
for (i=0; i < 8; i++)
if (ReadBlobByte(image) == EOF)
break;
if (pattern == 2)
{
for (i=0; i < 5; i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (pattern != 1)
ThrowReaderException(CorruptImageError,"UnknownPatternType");
length=ReadBlobMSBShort(image);
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
ReadPixmap(pixmap);
image->depth=1UL*pixmap.component_size;
image->x_resolution=1.0*pixmap.horizontal_resolution;
image->y_resolution=1.0*pixmap.vertical_resolution;
image->units=PixelsPerInchResolution;
(void) ReadBlobMSBLong(image);
flags=1L*ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
for (i=0; i <= (ssize_t) length; i++)
(void) ReadBlobMSBLong(image);
width=1UL*(frame.bottom-frame.top);
height=1UL*(frame.right-frame.left);
if (pixmap.bits_per_pixel <= 8)
length&=0x7fff;
if (pixmap.bits_per_pixel == 16)
width<<=1;
if (length == 0)
length=width;
if (length < 8)
{
for (i=0; i < (ssize_t) (length*height); i++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (int) height; j++)
if (length > 200)
{
for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x1b:
{
/*
Initialize image background color.
*/
image->background_color.red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
break;
}
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
{
/*
Skip polygon or region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x90:
case 0x91:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
{
ssize_t
bytes_per_line;
PICTRectangle
source,
destination;
register unsigned char
*p;
size_t
j;
unsigned char
*pixels;
Image
*tile_image;
/*
Pixmap clipped by a rectangle.
*/
bytes_per_line=0;
if ((code != 0x9a) && (code != 0x9b))
bytes_per_line=1L*ReadBlobMSBShort(image);
else
{
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize tile image.
*/
tile_image=CloneImage(image,1UL*(frame.right-frame.left),
1UL*(frame.bottom-frame.top),MagickTrue,exception);
if (tile_image == (Image *) NULL)
return((Image *) NULL);
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
{
ReadPixmap(pixmap);
tile_image->depth=1UL*pixmap.component_size;
tile_image->matte=pixmap.component_count == 4 ?
MagickTrue : MagickFalse;
tile_image->x_resolution=(double) pixmap.horizontal_resolution;
tile_image->y_resolution=(double) pixmap.vertical_resolution;
tile_image->units=PixelsPerInchResolution;
if (tile_image->matte != MagickFalse)
image->matte=tile_image->matte;
}
if ((code != 0x9a) && (code != 0x9b))
{
/*
Initialize colormap.
*/
tile_image->colors=2;
if ((bytes_per_line & 0x8000) != 0)
{
(void) ReadBlobMSBLong(image);
flags=1L*ReadBlobMSBShort(image);
tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
}
status=AcquireImageColormap(tile_image,tile_image->colors);
if (status == MagickFalse)
{
tile_image=DestroyImage(tile_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if ((bytes_per_line & 0x8000) != 0)
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
j=ReadBlobMSBShort(image) % tile_image->colors;
if ((flags & 0x8000) != 0)
j=(size_t) i;
tile_image->colormap[j].red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
}
}
else
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
tile_image->colormap[i].red=(Quantum) (QuantumRange-
tile_image->colormap[i].red);
tile_image->colormap[i].green=(Quantum) (QuantumRange-
tile_image->colormap[i].green);
tile_image->colormap[i].blue=(Quantum) (QuantumRange-
tile_image->colormap[i].blue);
}
}
}
if (ReadRectangle(image,&source) == MagickFalse)
{
tile_image=DestroyImage(tile_image);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (ReadRectangle(image,&destination) == MagickFalse)
{
tile_image=DestroyImage(tile_image);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
(void) ReadBlobMSBShort(image);
if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
{
/*
Skip region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
}
if ((code != 0x9a) && (code != 0x9b) &&
(bytes_per_line & 0x8000) == 0)
pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1,&extent);
else
pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1U*
pixmap.bits_per_pixel,&extent);
if (pixels == (unsigned char *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/*
Convert PICT tile image to pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
if (p > (pixels+extent+image->columns))
{
tile_image=DestroyImage(tile_image);
ThrowReaderException(CorruptImageError,"NotEnoughPixelData");
}
q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(tile_image);
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
if (tile_image->storage_class == PseudoClass)
{
index=ConstrainColormapIndex(tile_image,*p);
SetPixelIndex(indexes+x,index);
SetPixelRed(q,
tile_image->colormap[(ssize_t) index].red);
SetPixelGreen(q,
tile_image->colormap[(ssize_t) index].green);
SetPixelBlue(q,
tile_image->colormap[(ssize_t) index].blue);
}
else
{
if (pixmap.bits_per_pixel == 16)
{
i=(*p++);
j=(*p);
SetPixelRed(q,ScaleCharToQuantum(
(unsigned char) ((i & 0x7c) << 1)));
SetPixelGreen(q,ScaleCharToQuantum(
(unsigned char) (((i & 0x03) << 6) |
((j & 0xe0) >> 2))));
SetPixelBlue(q,ScaleCharToQuantum(
(unsigned char) ((j & 0x1f) << 3)));
}
else
if (tile_image->matte == MagickFalse)
{
if (p > (pixels+extent+2*image->columns))
{
tile_image=DestroyImage(tile_image);
ThrowReaderException(CorruptImageError,
"NotEnoughPixelData");
}
SetPixelRed(q,ScaleCharToQuantum(*p));
SetPixelGreen(q,ScaleCharToQuantum(
*(p+tile_image->columns)));
SetPixelBlue(q,ScaleCharToQuantum(
*(p+2*tile_image->columns)));
}
else
{
if (p > (pixels+extent+3*image->columns))
{
tile_image=DestroyImage(tile_image);
ThrowReaderException(CorruptImageError,
"NotEnoughPixelData");
}
SetPixelAlpha(q,ScaleCharToQuantum(*p));
SetPixelRed(q,ScaleCharToQuantum(
*(p+tile_image->columns)));
SetPixelGreen(q,ScaleCharToQuantum(
*(p+2*tile_image->columns)));
SetPixelBlue(q,ScaleCharToQuantum(
*(p+3*tile_image->columns)));
}
}
p++;
q++;
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
if ((tile_image->storage_class == DirectClass) &&
(pixmap.bits_per_pixel != 16))
{
p+=(pixmap.component_count-1)*tile_image->columns;
if (p < pixels)
break;
}
status=SetImageProgress(image,LoadImageTag,y,tile_image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (jpeg == MagickFalse)
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
(void) CompositeImage(image,CopyCompositeOp,tile_image,
destination.left,destination.top);
tile_image=DestroyImage(tile_image);
break;
}
case 0xa1:
{
unsigned char
*info;
size_t
type;
/*
Comment.
*/
type=ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
if (length == 0)
break;
(void) ReadBlobMSBLong(image);
length-=4;
if (length == 0)
break;
info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
if (info == (unsigned char *) NULL)
break;
count=ReadBlob(image,length,info);
if (count != (ssize_t) length)
ThrowReaderException(ResourceLimitError,"UnableToReadImageData");
switch (type)
{
case 0xe0:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"icc",profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
break;
}
case 0x1f2:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"iptc",profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
profile=DestroyStringInfo(profile);
break;
}
default:
break;
}
info=(unsigned char *) RelinquishMagickMemory(info);
break;
}
default:
{
/*
Skip to next op code.
*/
if (codes[code].length == -1)
(void) ReadBlobMSBShort(image);
else
for (i=0; i < (ssize_t) codes[code].length; i++)
if (ReadBlobByte(image) == EOF)
break;
}
}
}
if (code == 0xc00)
{
/*
Skip header.
*/
for (i=0; i < 24; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if (((code >= 0xb0) && (code <= 0xcf)) ||
((code >= 0x8000) && (code <= 0x80ff)))
continue;
if (code == 0x8200)
{
FILE
*file;
Image
*tile_image;
ImageInfo
*read_info;
int
unique_file;
/*
Embedded JPEG.
*/
jpeg=MagickTrue;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(read_info->filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
(void) CopyMagickString(image->filename,read_info->filename,
MaxTextExtent);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=ReadBlobMSBLong(image);
if (length > 154)
{
for (i=0; i < 6; i++)
(void) ReadBlobMSBLong(image);
if (ReadRectangle(image,&frame) == MagickFalse)
{
(void) fclose(file);
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < 122; i++)
if (ReadBlobByte(image) == EOF)
break;
for (i=0; i < (ssize_t) (length-154); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
break;
(void) fputc(c,file);
}
}
(void) fclose(file);
(void) close(unique_file);
tile_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
continue;
(void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g",
(double) MagickMax(image->columns,tile_image->columns),
(double) MagickMax(image->rows,tile_image->rows));
(void) SetImageExtent(image,
MagickMax(image->columns,tile_image->columns),
MagickMax(image->rows,tile_image->rows));
(void) TransformImageColorspace(image,tile_image->colorspace);
(void) CompositeImage(image,CopyCompositeOp,tile_image,frame.left,
frame.right);
image->compression=tile_image->compression;
tile_image=DestroyImage(tile_image);
continue;
}
if ((code == 0xff) || (code == 0xffff))
break;
if (((code >= 0xd0) && (code <= 0xfe)) ||
((code >= 0x8100) && (code <= 0xffff)))
{
/*
Skip reserved.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if ((code >= 0x100) && (code <= 0x7fff))
{
/*
Skip reserved.
*/
length=(size_t) ((code >> 7) & 0xff);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P I C T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPICTImage() adds attributes for the PICT image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPICTImage method is:
%
% size_t RegisterPICTImage(void)
%
*/
ModuleExport size_t RegisterPICTImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PCT");
entry->decoder=(DecodeImageHandler *) ReadPICTImage;
entry->encoder=(EncodeImageHandler *) WritePICTImage;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Apple Macintosh QuickDraw/PICT");
entry->magick=(IsImageFormatHandler *) IsPICT;
entry->module=ConstantString("PICT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PICT");
entry->decoder=(DecodeImageHandler *) ReadPICTImage;
entry->encoder=(EncodeImageHandler *) WritePICTImage;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Apple Macintosh QuickDraw/PICT");
entry->magick=(IsImageFormatHandler *) IsPICT;
entry->module=ConstantString("PICT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P I C T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPICTImage() removes format registrations made by the
% PICT module from the list of supported formats.
%
% The format of the UnregisterPICTImage method is:
%
% UnregisterPICTImage(void)
%
*/
ModuleExport void UnregisterPICTImage(void)
{
(void) UnregisterMagickInfo("PCT");
(void) UnregisterMagickInfo("PICT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P I C T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePICTImage() writes an image to a file in the Apple Macintosh
% QuickDraw/PICT image format.
%
% The format of the WritePICTImage method is:
%
% MagickBooleanType WritePICTImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePICTImage(const ImageInfo *image_info,
Image *image)
{
#define MaxCount 128
#define PictCropRegionOp 0x01
#define PictEndOfPictureOp 0xff
#define PictJPEGOp 0x8200
#define PictInfoOp 0x0C00
#define PictInfoSize 512
#define PictPixmapOp 0x9A
#define PictPICTOp 0x98
#define PictVersion 0x11
const StringInfo
*profile;
double
x_resolution,
y_resolution;
MagickBooleanType
status;
MagickOffsetType
offset;
PICTPixmap
pixmap;
PICTRectangle
bounds,
crop_rectangle,
destination_rectangle,
frame_rectangle,
size_rectangle,
source_rectangle;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
size_t
bytes_per_line,
count,
row_bytes,
storage_class;
ssize_t
y;
unsigned char
*buffer,
*packed_scanline,
*scanline;
unsigned short
base_address,
transfer_mode;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 65535L) || (image->rows > 65535L))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Initialize image info.
*/
size_rectangle.top=0;
size_rectangle.left=0;
size_rectangle.bottom=(short) image->rows;
size_rectangle.right=(short) image->columns;
frame_rectangle=size_rectangle;
crop_rectangle=size_rectangle;
source_rectangle=size_rectangle;
destination_rectangle=size_rectangle;
base_address=0xff;
row_bytes=image->columns;
bounds.top=0;
bounds.left=0;
bounds.bottom=(short) image->rows;
bounds.right=(short) image->columns;
pixmap.version=0;
pixmap.pack_type=0;
pixmap.pack_size=0;
pixmap.pixel_type=0;
pixmap.bits_per_pixel=8;
pixmap.component_count=1;
pixmap.component_size=8;
pixmap.plane_bytes=0;
pixmap.table=0;
pixmap.reserved=0;
transfer_mode=0;
x_resolution=image->x_resolution != 0.0 ? image->x_resolution :
DefaultResolution;
y_resolution=image->y_resolution != 0.0 ? image->y_resolution :
DefaultResolution;
storage_class=image->storage_class;
if (image_info->compression == JPEGCompression)
storage_class=DirectClass;
if (storage_class == DirectClass)
{
pixmap.component_count=image->matte != MagickFalse ? 4 : 3;
pixmap.pixel_type=16;
pixmap.bits_per_pixel=32;
pixmap.pack_type=0x04;
transfer_mode=0x40;
row_bytes=4*image->columns;
}
/*
Allocate memory.
*/
bytes_per_line=image->columns;
if (storage_class == DirectClass)
bytes_per_line*=image->matte != MagickFalse ? 4 : 3;
buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer));
packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t)
(row_bytes+MaxCount),sizeof(*packed_scanline));
scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline));
if ((buffer == (unsigned char *) NULL) ||
(packed_scanline == (unsigned char *) NULL) ||
(scanline == (unsigned char *) NULL))
{
if (scanline != (unsigned char *) NULL)
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
if (packed_scanline != (unsigned char *) NULL)
packed_scanline=(unsigned char *) RelinquishMagickMemory(
packed_scanline);
if (buffer != (unsigned char *) NULL)
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) ResetMagickMemory(scanline,0,row_bytes);
(void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount));
/*
Write header, header size, size bounding box, version, and reserved.
*/
(void) ResetMagickMemory(buffer,0,PictInfoSize);
(void) WriteBlob(image,PictInfoSize,buffer);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right);
(void) WriteBlobMSBShort(image,PictVersion);
(void) WriteBlobMSBShort(image,0x02ff); /* version #2 */
(void) WriteBlobMSBShort(image,PictInfoOp);
(void) WriteBlobMSBLong(image,0xFFFE0000UL);
/*
Write full size of the file, resolution, frame bounding box, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right);
(void) WriteBlobMSBLong(image,0x00000000L);
profile=GetImageProfile(image,"iptc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0x1f2);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobString(image,"8BIM");
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
}
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,4);
(void) WriteBlobMSBLong(image,0x00000002UL);
}
/*
Write crop region opcode and crop bounding box.
*/
(void) WriteBlobMSBShort(image,PictCropRegionOp);
(void) WriteBlobMSBShort(image,0xa);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right);
if (image_info->compression == JPEGCompression)
{
Image
*jpeg_image;
ImageInfo
*jpeg_info;
size_t
length;
unsigned char
*blob;
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
jpeg_info=CloneImageInfo(image_info);
(void) CopyMagickString(jpeg_info->magick,"JPEG",MaxTextExtent);
length=0;
blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length,
&image->exception);
jpeg_info=DestroyImageInfo(jpeg_info);
if (blob == (unsigned char *) NULL)
return(MagickFalse);
jpeg_image=DestroyImage(jpeg_image);
(void) WriteBlobMSBShort(image,PictJPEGOp);
(void) WriteBlobMSBLong(image,(unsigned int) length+154);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x40000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00400000UL);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00566A70UL);
(void) WriteBlobMSBLong(image,0x65670000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000001UL);
(void) WriteBlobMSBLong(image,0x00016170UL);
(void) WriteBlobMSBLong(image,0x706C0000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x87AC0001UL);
(void) WriteBlobMSBLong(image,0x0B466F74UL);
(void) WriteBlobMSBLong(image,0x6F202D20UL);
(void) WriteBlobMSBLong(image,0x4A504547UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x0018FFFFUL);
(void) WriteBlob(image,length,blob);
if ((length & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/*
Write picture opcode, row bytes, and picture bounding box, and version.
*/
if (storage_class == PseudoClass)
(void) WriteBlobMSBShort(image,PictPICTOp);
else
{
(void) WriteBlobMSBShort(image,PictPixmapOp);
(void) WriteBlobMSBLong(image,(size_t) base_address);
}
(void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000));
(void) WriteBlobMSBShort(image,(unsigned short) bounds.top);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.left);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.right);
/*
Write pack type, pack size, resolution, pixel type, and pixel size.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.version);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size);
(void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel);
/*
Write component count, size, plane bytes, table size, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.table);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved);
if (storage_class == PseudoClass)
{
/*
Write image colormap.
*/
(void) WriteBlobMSBLong(image,0x00000000L); /* color seed */
(void) WriteBlobMSBShort(image,0L); /* color flags */
(void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1));
for (i=0; i < (ssize_t) image->colors; i++)
{
(void) WriteBlobMSBShort(image,(unsigned short) i);
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].red));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].green));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].blue));
}
}
/*
Write source and destination rectangle.
*/
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) transfer_mode);
/*
Write picture data.
*/
count=0;
if (storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
scanline[x]=(unsigned char) GetPixelIndex(indexes+x);
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image_info->compression == JPEGCompression)
{
(void) ResetMagickMemory(scanline,0,row_bytes);
for (y=0; y < (ssize_t) image->rows; y++)
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
}
else
{
register unsigned char
*blue,
*green,
*opacity,
*red;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
opacity=scanline+3*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
if (image->matte != MagickFalse)
{
opacity=scanline;
red=scanline+image->columns;
green=scanline+2*image->columns;
blue=scanline+3*image->columns;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
*red++=ScaleQuantumToChar(GetPixelRed(p));
*green++=ScaleQuantumToChar(GetPixelGreen(p));
*blue++=ScaleQuantumToChar(GetPixelBlue(p));
if (image->matte != MagickFalse)
*opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p)));
p++;
}
count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if ((count & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
(void) WriteBlobMSBShort(image,PictEndOfPictureOp);
offset=TellBlob(image);
offset=SeekBlob(image,512,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) offset);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_2619_0 |
crossvul-cpp_data_good_2830_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Y Y U U V V %
% Y Y U U V V %
% Y U U V V %
% Y U U V V %
% Y UUU V %
% %
% %
% Read/Write Raw CCIR 601 4:1:1 or 4:2:2 Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/resize.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/utility.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteYUVImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadYUVImage() reads an image with digital YUV (CCIR 601 4:1:1, plane
% or partition interlaced, or 4:2:2 plane, partition interlaced or
% noninterlaced) bytes and returns it. It allocates the memory necessary
% for the new Image structure and returns a pointer to the new image.
%
% The format of the ReadYUVImage method is:
%
% Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*chroma_image,
*image,
*resize_image;
InterlaceType
interlace;
MagickBooleanType
status;
register const Quantum
*chroma_pixels;
register ssize_t
x;
register Quantum
*q;
register unsigned char
*p;
ssize_t
count,
horizontal_factor,
vertical_factor,
y;
size_t
length,
quantum;
unsigned char
*scanline;
/*
Allocate image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
quantum=(ssize_t) (image->depth <= 8 ? 1 : 2);
interlace=image_info->interlace;
horizontal_factor=2;
vertical_factor=2;
if (image_info->sampling_factor != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(image_info->sampling_factor,&geometry_info);
horizontal_factor=(ssize_t) geometry_info.rho;
vertical_factor=(ssize_t) geometry_info.sigma;
if ((flags & SigmaValue) == 0)
vertical_factor=horizontal_factor;
if ((horizontal_factor != 1) && (horizontal_factor != 2) &&
(vertical_factor != 1) && (vertical_factor != 2))
ThrowReaderException(CorruptImageError,"UnexpectedSamplingFactor");
}
if ((interlace == UndefinedInterlace) ||
((interlace == NoInterlace) && (vertical_factor == 2)))
{
interlace=NoInterlace; /* CCIR 4:2:2 */
if (vertical_factor == 2)
interlace=PlaneInterlace; /* CCIR 4:1:1 */
}
if (interlace != PartitionInterlace)
{
/*
Open image file.
*/
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
/*
Allocate memory for a scanline.
*/
if (interlace == NoInterlace)
scanline=(unsigned char *) AcquireQuantumMemory((size_t) (2UL*
image->columns+2UL),(size_t) quantum*sizeof(*scanline));
else
scanline=(unsigned char *) AcquireQuantumMemory(image->columns,
(size_t) quantum*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=MagickTrue;
do
{
chroma_image=CloneImage(image,(image->columns+horizontal_factor-1)/
horizontal_factor,(image->rows+vertical_factor-1)/vertical_factor,
MagickTrue,exception);
if (chroma_image == (Image *) NULL)
{
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Convert raster image to pixel packets.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if (interlace == PartitionInterlace)
{
AppendImageFormat("Y",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*chroma_pixels;
if (interlace == NoInterlace)
{
if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))
{
length=2*quantum*image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
}
p=scanline;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
chroma_pixels=QueueAuthenticPixels(chroma_image,0,y,
chroma_image->columns,1,exception);
if (chroma_pixels == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=2)
{
SetPixelRed(chroma_image,0,chroma_pixels);
if (quantum == 1)
SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++),
chroma_pixels);
else
{
SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),chroma_pixels);
p+=2;
}
if (quantum == 1)
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);
p+=2;
}
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
q+=GetPixelChannels(image);
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
if (quantum == 1)
SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),chroma_pixels);
else
{
SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),chroma_pixels);
p+=2;
}
if (quantum == 1)
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);
p+=2;
}
chroma_pixels+=GetPixelChannels(chroma_image);
q+=GetPixelChannels(image);
}
}
else
{
if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL))
{
length=quantum*image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
}
p=scanline;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (quantum == 1)
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q);
p+=2;
}
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
q+=GetPixelChannels(image);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (interlace == NoInterlace)
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("U",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if (interlace != NoInterlace)
{
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
length=quantum*chroma_image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
p=scanline;
q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
SetPixelRed(chroma_image,0,q);
if (quantum == 1)
SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),q);
p+=2;
}
SetPixelBlue(chroma_image,0,q);
q+=GetPixelChannels(chroma_image);
}
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
}
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("V",image->filename);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
length=quantum*chroma_image->columns;
count=ReadBlob(image,length,scanline);
if (count != (ssize_t) length)
{
status=MagickFalse;
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
p=scanline;
q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
if (quantum == 1)
SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),q);
else
{
SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) |
*(p+1)),q);
p+=2;
}
q+=GetPixelChannels(chroma_image);
}
if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse)
break;
}
}
/*
Scale image.
*/
resize_image=ResizeImage(chroma_image,image->columns,image->rows,
TriangleFilter,exception);
chroma_image=DestroyImage(chroma_image);
if (resize_image == (Image *) NULL)
{
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1,
exception);
if ((q == (Quantum *) NULL) ||
(chroma_pixels == (const Quantum *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGreen(image,GetPixelGreen(resize_image,chroma_pixels),q);
SetPixelBlue(image,GetPixelBlue(resize_image,chroma_pixels),q);
chroma_pixels+=GetPixelChannels(resize_image);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
resize_image=DestroyImage(resize_image);
if (SetImageColorspace(image,YCbCrColorspace,exception) == MagickFalse)
break;
if (interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (interlace == NoInterlace)
count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline);
else
count=ReadBlob(image,(size_t) quantum*image->columns,scanline);
if (count != 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (count != 0);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterYUVImage() adds attributes for the YUV image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterYUVImage method is:
%
% size_t RegisterYUVImage(void)
%
*/
ModuleExport size_t RegisterYUVImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("YUV","YUV","CCIR 601 4:1:1 or 4:2:2");
entry->decoder=(DecodeImageHandler *) ReadYUVImage;
entry->encoder=(EncodeImageHandler *) WriteYUVImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderRawSupportFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterYUVImage() removes format registrations made by the
% YUV module from the list of supported formats.
%
% The format of the UnregisterYUVImage method is:
%
% UnregisterYUVImage(void)
%
*/
ModuleExport void UnregisterYUVImage(void)
{
(void) UnregisterMagickInfo("YUV");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e Y U V I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteYUVImage() writes an image to a file in the digital YUV
% (CCIR 601 4:1:1, plane or partition interlaced, or 4:2:2 plane, partition
% interlaced or noninterlaced) bytes and returns it.
%
% The format of the WriteYUVImage method is:
%
% MagickBooleanType WriteYUVImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WriteYUVImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
Image
*chroma_image,
*yuv_image;
InterlaceType
interlace;
MagickBooleanType
status;
MagickOffsetType
scene;
register const Quantum
*p,
*s;
register ssize_t
x;
size_t
height,
quantum,
width;
ssize_t
horizontal_factor,
vertical_factor,
y;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
quantum=(size_t) (image->depth <= 8 ? 1 : 2);
interlace=image->interlace;
horizontal_factor=2;
vertical_factor=2;
if (image_info->sampling_factor != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(image_info->sampling_factor,&geometry_info);
horizontal_factor=(ssize_t) geometry_info.rho;
vertical_factor=(ssize_t) geometry_info.sigma;
if ((flags & SigmaValue) == 0)
vertical_factor=horizontal_factor;
if ((horizontal_factor != 1) && (horizontal_factor != 2) &&
(vertical_factor != 1) && (vertical_factor != 2))
ThrowWriterException(CorruptImageError,"UnexpectedSamplingFactor");
}
if ((interlace == UndefinedInterlace) ||
((interlace == NoInterlace) && (vertical_factor == 2)))
{
interlace=NoInterlace; /* CCIR 4:2:2 */
if (vertical_factor == 2)
interlace=PlaneInterlace; /* CCIR 4:1:1 */
}
if (interlace != PartitionInterlace)
{
/*
Open output image file.
*/
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
else
{
AppendImageFormat("Y",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
scene=0;
do
{
/*
Sample image to an even width and height, if necessary.
*/
image->depth=(size_t) (quantum == 1 ? 8 : 16);
width=image->columns+(image->columns & (horizontal_factor-1));
height=image->rows+(image->rows & (vertical_factor-1));
yuv_image=ResizeImage(image,width,height,TriangleFilter,exception);
if (yuv_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
(void) TransformImageColorspace(yuv_image,YCbCrColorspace,exception);
/*
Downsample image.
*/
chroma_image=ResizeImage(image,width/horizontal_factor,
height/vertical_factor,TriangleFilter,exception);
if (chroma_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
(void) TransformImageColorspace(chroma_image,YCbCrColorspace,exception);
if (interlace == NoInterlace)
{
/*
Write noninterlaced YUV.
*/
for (y=0; y < (ssize_t) yuv_image->rows; y++)
{
p=GetVirtualPixels(yuv_image,0,y,yuv_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
s=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (s == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) yuv_image->columns; x+=2)
{
if (quantum == 1)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelGreen(yuv_image,s)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelRed(yuv_image,p)));
p+=GetPixelChannels(yuv_image);
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelBlue(yuv_image,s)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelRed(yuv_image,p)));
}
else
{
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelGreen(yuv_image,s)));
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelRed(yuv_image,p)));
p+=GetPixelChannels(yuv_image);
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelBlue(yuv_image,s)));
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelRed(yuv_image,p)));
}
p+=GetPixelChannels(yuv_image);
s++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
yuv_image=DestroyImage(yuv_image);
}
else
{
/*
Initialize Y channel.
*/
for (y=0; y < (ssize_t) yuv_image->rows; y++)
{
p=GetVirtualPixels(yuv_image,0,y,yuv_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) yuv_image->columns; x++)
{
if (quantum == 1)
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelRed(yuv_image,p)));
else
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelRed(yuv_image,p)));
p+=GetPixelChannels(yuv_image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
yuv_image=DestroyImage(yuv_image);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,3);
if (status == MagickFalse)
break;
}
/*
Initialize U channel.
*/
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("U",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
p=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
if (quantum == 1)
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelGreen(chroma_image,p)));
else
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelGreen(chroma_image,p)));
p+=GetPixelChannels(chroma_image);
}
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,3);
if (status == MagickFalse)
break;
}
/*
Initialize V channel.
*/
if (interlace == PartitionInterlace)
{
(void) CloseBlob(image);
AppendImageFormat("V",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
}
for (y=0; y < (ssize_t) chroma_image->rows; y++)
{
p=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) chroma_image->columns; x++)
{
if (quantum == 1)
(void) WriteBlobByte(image,ScaleQuantumToChar(
GetPixelBlue(chroma_image,p)));
else
(void) WriteBlobShort(image,ScaleQuantumToShort(
GetPixelBlue(chroma_image,p)));
p+=GetPixelChannels(chroma_image);
}
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,3);
if (status == MagickFalse)
break;
}
}
chroma_image=DestroyImage(chroma_image);
if (interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_2830_0 |
crossvul-cpp_data_bad_2617_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M AAA PPPP %
% MM MM A A P P %
% M M M AAAAA PPPP %
% M M A A P %
% M M A A P %
% %
% %
% Read/Write Image Colormaps As An Image File. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/histogram.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteMAPImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMAPImage() reads an image of raw RGB colormap and colormap index
% bytes and returns it. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the ReadMAPImage method is:
%
% Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
depth,
packet_size,
quantum;
ssize_t
count,
y;
unsigned char
*colormap,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
image->storage_class=PseudoClass;
status=AcquireImageColormap(image,(size_t)
(image->offset != 0 ? image->offset : 256));
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read image colormap.
*/
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
p=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].red=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].green=(Quantum) quantum;
quantum=(*p++ << 8);
quantum|=(*p++);
image->colormap[i].blue=(Quantum) quantum;
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read image pixels.
*/
packet_size=(size_t) (depth/8);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
count=ReadBlob(image,(size_t) packet_size*image->columns,pixels);
if (count != (ssize_t) (packet_size*image->columns))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
p++;
if (image->colors > 256)
{
index=ConstrainColormapIndex(image,((size_t) index << 8)+(*p));
p++;
}
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (y < (ssize_t) image->rows)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMAPImage() adds attributes for the MAP image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMAPImage method is:
%
% size_t RegisterMAPImage(void)
%
*/
ModuleExport size_t RegisterMAPImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MAP");
entry->decoder=(DecodeImageHandler *) ReadMAPImage;
entry->encoder=(EncodeImageHandler *) WriteMAPImage;
entry->adjoin=MagickFalse;
entry->format_type=ExplicitFormatType;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Colormap intensities and indices");
entry->module=ConstantString("MAP");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMAPImage() removes format registrations made by the
% MAP module from the list of supported formats.
%
% The format of the UnregisterMAPImage method is:
%
% UnregisterMAPImage(void)
%
*/
ModuleExport void UnregisterMAPImage(void)
{
(void) UnregisterMagickInfo("MAP");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M A P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMAPImage() writes an image to a file as red, green, and blue
% colormap bytes followed by the colormap indexes.
%
% The format of the WriteMAPImage method is:
%
% MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
*/
static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);;
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/bad_2617_0 |
crossvul-cpp_data_good_1162_1 | /* Copyright 2011-2014 Autronica Fire and Security AS
*
* 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.
*
* Author(s):
* 2011-2014 Arvid Brodin, arvid.brodin@alten.se
*
* The HSR spec says never to forward the same frame twice on the same
* interface. A frame is identified by its source MAC address and its HSR
* sequence number. This code keeps track of senders and their sequence numbers
* to allow filtering of duplicate frames, and to detect HSR ring errors.
*/
#include <linux/if_ether.h>
#include <linux/etherdevice.h>
#include <linux/slab.h>
#include <linux/rculist.h>
#include "hsr_main.h"
#include "hsr_framereg.h"
#include "hsr_netlink.h"
struct hsr_node {
struct list_head mac_list;
unsigned char MacAddressA[ETH_ALEN];
unsigned char MacAddressB[ETH_ALEN];
/* Local slave through which AddrB frames are received from this node */
enum hsr_port_type AddrB_port;
unsigned long time_in[HSR_PT_PORTS];
bool time_in_stale[HSR_PT_PORTS];
u16 seq_out[HSR_PT_PORTS];
struct rcu_head rcu_head;
};
/* TODO: use hash lists for mac addresses (linux/jhash.h)? */
/* seq_nr_after(a, b) - return true if a is after (higher in sequence than) b,
* false otherwise.
*/
static bool seq_nr_after(u16 a, u16 b)
{
/* Remove inconsistency where
* seq_nr_after(a, b) == seq_nr_before(a, b)
*/
if ((int) b - a == 32768)
return false;
return (((s16) (b - a)) < 0);
}
#define seq_nr_before(a, b) seq_nr_after((b), (a))
#define seq_nr_after_or_eq(a, b) (!seq_nr_before((a), (b)))
#define seq_nr_before_or_eq(a, b) (!seq_nr_after((a), (b)))
bool hsr_addr_is_self(struct hsr_priv *hsr, unsigned char *addr)
{
struct hsr_node *node;
node = list_first_or_null_rcu(&hsr->self_node_db, struct hsr_node,
mac_list);
if (!node) {
WARN_ONCE(1, "HSR: No self node\n");
return false;
}
if (ether_addr_equal(addr, node->MacAddressA))
return true;
if (ether_addr_equal(addr, node->MacAddressB))
return true;
return false;
}
/* Search for mac entry. Caller must hold rcu read lock.
*/
static struct hsr_node *find_node_by_AddrA(struct list_head *node_db,
const unsigned char addr[ETH_ALEN])
{
struct hsr_node *node;
list_for_each_entry_rcu(node, node_db, mac_list) {
if (ether_addr_equal(node->MacAddressA, addr))
return node;
}
return NULL;
}
/* Helper for device init; the self_node_db is used in hsr_rcv() to recognize
* frames from self that's been looped over the HSR ring.
*/
int hsr_create_self_node(struct list_head *self_node_db,
unsigned char addr_a[ETH_ALEN],
unsigned char addr_b[ETH_ALEN])
{
struct hsr_node *node, *oldnode;
node = kmalloc(sizeof(*node), GFP_KERNEL);
if (!node)
return -ENOMEM;
ether_addr_copy(node->MacAddressA, addr_a);
ether_addr_copy(node->MacAddressB, addr_b);
rcu_read_lock();
oldnode = list_first_or_null_rcu(self_node_db,
struct hsr_node, mac_list);
if (oldnode) {
list_replace_rcu(&oldnode->mac_list, &node->mac_list);
rcu_read_unlock();
synchronize_rcu();
kfree(oldnode);
} else {
rcu_read_unlock();
list_add_tail_rcu(&node->mac_list, self_node_db);
}
return 0;
}
void hsr_del_node(struct list_head *self_node_db)
{
struct hsr_node *node;
rcu_read_lock();
node = list_first_or_null_rcu(self_node_db, struct hsr_node, mac_list);
rcu_read_unlock();
if (node) {
list_del_rcu(&node->mac_list);
kfree(node);
}
}
/* Allocate an hsr_node and add it to node_db. 'addr' is the node's AddressA;
* seq_out is used to initialize filtering of outgoing duplicate frames
* originating from the newly added node.
*/
struct hsr_node *hsr_add_node(struct list_head *node_db, unsigned char addr[],
u16 seq_out)
{
struct hsr_node *node;
unsigned long now;
int i;
node = kzalloc(sizeof(*node), GFP_ATOMIC);
if (!node)
return NULL;
ether_addr_copy(node->MacAddressA, addr);
/* We are only interested in time diffs here, so use current jiffies
* as initialization. (0 could trigger an spurious ring error warning).
*/
now = jiffies;
for (i = 0; i < HSR_PT_PORTS; i++)
node->time_in[i] = now;
for (i = 0; i < HSR_PT_PORTS; i++)
node->seq_out[i] = seq_out;
list_add_tail_rcu(&node->mac_list, node_db);
return node;
}
/* Get the hsr_node from which 'skb' was sent.
*/
struct hsr_node *hsr_get_node(struct hsr_port *port, struct sk_buff *skb,
bool is_sup)
{
struct list_head *node_db = &port->hsr->node_db;
struct hsr_node *node;
struct ethhdr *ethhdr;
u16 seq_out;
if (!skb_mac_header_was_set(skb))
return NULL;
ethhdr = (struct ethhdr *) skb_mac_header(skb);
list_for_each_entry_rcu(node, node_db, mac_list) {
if (ether_addr_equal(node->MacAddressA, ethhdr->h_source))
return node;
if (ether_addr_equal(node->MacAddressB, ethhdr->h_source))
return node;
}
/* Everyone may create a node entry, connected node to a HSR device. */
if (ethhdr->h_proto == htons(ETH_P_PRP)
|| ethhdr->h_proto == htons(ETH_P_HSR)) {
/* Use the existing sequence_nr from the tag as starting point
* for filtering duplicate frames.
*/
seq_out = hsr_get_skb_sequence_nr(skb) - 1;
} else {
/* this is called also for frames from master port and
* so warn only for non master ports
*/
if (port->type != HSR_PT_MASTER)
WARN_ONCE(1, "%s: Non-HSR frame\n", __func__);
seq_out = HSR_SEQNR_START;
}
return hsr_add_node(node_db, ethhdr->h_source, seq_out);
}
/* Use the Supervision frame's info about an eventual MacAddressB for merging
* nodes that has previously had their MacAddressB registered as a separate
* node.
*/
void hsr_handle_sup_frame(struct sk_buff *skb, struct hsr_node *node_curr,
struct hsr_port *port_rcv)
{
struct ethhdr *ethhdr;
struct hsr_node *node_real;
struct hsr_sup_payload *hsr_sp;
struct list_head *node_db;
int i;
ethhdr = (struct ethhdr *) skb_mac_header(skb);
/* Leave the ethernet header. */
skb_pull(skb, sizeof(struct ethhdr));
/* And leave the HSR tag. */
if (ethhdr->h_proto == htons(ETH_P_HSR))
skb_pull(skb, sizeof(struct hsr_tag));
/* And leave the HSR sup tag. */
skb_pull(skb, sizeof(struct hsr_sup_tag));
hsr_sp = (struct hsr_sup_payload *) skb->data;
/* Merge node_curr (registered on MacAddressB) into node_real */
node_db = &port_rcv->hsr->node_db;
node_real = find_node_by_AddrA(node_db, hsr_sp->MacAddressA);
if (!node_real)
/* No frame received from AddrA of this node yet */
node_real = hsr_add_node(node_db, hsr_sp->MacAddressA,
HSR_SEQNR_START - 1);
if (!node_real)
goto done; /* No mem */
if (node_real == node_curr)
/* Node has already been merged */
goto done;
ether_addr_copy(node_real->MacAddressB, ethhdr->h_source);
for (i = 0; i < HSR_PT_PORTS; i++) {
if (!node_curr->time_in_stale[i] &&
time_after(node_curr->time_in[i], node_real->time_in[i])) {
node_real->time_in[i] = node_curr->time_in[i];
node_real->time_in_stale[i] = node_curr->time_in_stale[i];
}
if (seq_nr_after(node_curr->seq_out[i], node_real->seq_out[i]))
node_real->seq_out[i] = node_curr->seq_out[i];
}
node_real->AddrB_port = port_rcv->type;
list_del_rcu(&node_curr->mac_list);
kfree_rcu(node_curr, rcu_head);
done:
skb_push(skb, sizeof(struct hsrv1_ethhdr_sp));
}
/* 'skb' is a frame meant for this host, that is to be passed to upper layers.
*
* If the frame was sent by a node's B interface, replace the source
* address with that node's "official" address (MacAddressA) so that upper
* layers recognize where it came from.
*/
void hsr_addr_subst_source(struct hsr_node *node, struct sk_buff *skb)
{
if (!skb_mac_header_was_set(skb)) {
WARN_ONCE(1, "%s: Mac header not set\n", __func__);
return;
}
memcpy(ð_hdr(skb)->h_source, node->MacAddressA, ETH_ALEN);
}
/* 'skb' is a frame meant for another host.
* 'port' is the outgoing interface
*
* Substitute the target (dest) MAC address if necessary, so the it matches the
* recipient interface MAC address, regardless of whether that is the
* recipient's A or B interface.
* This is needed to keep the packets flowing through switches that learn on
* which "side" the different interfaces are.
*/
void hsr_addr_subst_dest(struct hsr_node *node_src, struct sk_buff *skb,
struct hsr_port *port)
{
struct hsr_node *node_dst;
if (!skb_mac_header_was_set(skb)) {
WARN_ONCE(1, "%s: Mac header not set\n", __func__);
return;
}
if (!is_unicast_ether_addr(eth_hdr(skb)->h_dest))
return;
node_dst = find_node_by_AddrA(&port->hsr->node_db, eth_hdr(skb)->h_dest);
if (!node_dst) {
WARN_ONCE(1, "%s: Unknown node\n", __func__);
return;
}
if (port->type != node_dst->AddrB_port)
return;
ether_addr_copy(eth_hdr(skb)->h_dest, node_dst->MacAddressB);
}
void hsr_register_frame_in(struct hsr_node *node, struct hsr_port *port,
u16 sequence_nr)
{
/* Don't register incoming frames without a valid sequence number. This
* ensures entries of restarted nodes gets pruned so that they can
* re-register and resume communications.
*/
if (seq_nr_before(sequence_nr, node->seq_out[port->type]))
return;
node->time_in[port->type] = jiffies;
node->time_in_stale[port->type] = false;
}
/* 'skb' is a HSR Ethernet frame (with a HSR tag inserted), with a valid
* ethhdr->h_source address and skb->mac_header set.
*
* Return:
* 1 if frame can be shown to have been sent recently on this interface,
* 0 otherwise, or
* negative error code on error
*/
int hsr_register_frame_out(struct hsr_port *port, struct hsr_node *node,
u16 sequence_nr)
{
if (seq_nr_before_or_eq(sequence_nr, node->seq_out[port->type]))
return 1;
node->seq_out[port->type] = sequence_nr;
return 0;
}
static struct hsr_port *get_late_port(struct hsr_priv *hsr,
struct hsr_node *node)
{
if (node->time_in_stale[HSR_PT_SLAVE_A])
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_A);
if (node->time_in_stale[HSR_PT_SLAVE_B])
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_B);
if (time_after(node->time_in[HSR_PT_SLAVE_B],
node->time_in[HSR_PT_SLAVE_A] +
msecs_to_jiffies(MAX_SLAVE_DIFF)))
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_A);
if (time_after(node->time_in[HSR_PT_SLAVE_A],
node->time_in[HSR_PT_SLAVE_B] +
msecs_to_jiffies(MAX_SLAVE_DIFF)))
return hsr_port_get_hsr(hsr, HSR_PT_SLAVE_B);
return NULL;
}
/* Remove stale sequence_nr records. Called by timer every
* HSR_LIFE_CHECK_INTERVAL (two seconds or so).
*/
void hsr_prune_nodes(struct timer_list *t)
{
struct hsr_priv *hsr = from_timer(hsr, t, prune_timer);
struct hsr_node *node;
struct hsr_port *port;
unsigned long timestamp;
unsigned long time_a, time_b;
rcu_read_lock();
list_for_each_entry_rcu(node, &hsr->node_db, mac_list) {
/* Shorthand */
time_a = node->time_in[HSR_PT_SLAVE_A];
time_b = node->time_in[HSR_PT_SLAVE_B];
/* Check for timestamps old enough to risk wrap-around */
if (time_after(jiffies, time_a + MAX_JIFFY_OFFSET/2))
node->time_in_stale[HSR_PT_SLAVE_A] = true;
if (time_after(jiffies, time_b + MAX_JIFFY_OFFSET/2))
node->time_in_stale[HSR_PT_SLAVE_B] = true;
/* Get age of newest frame from node.
* At least one time_in is OK here; nodes get pruned long
* before both time_ins can get stale
*/
timestamp = time_a;
if (node->time_in_stale[HSR_PT_SLAVE_A] ||
(!node->time_in_stale[HSR_PT_SLAVE_B] &&
time_after(time_b, time_a)))
timestamp = time_b;
/* Warn of ring error only as long as we get frames at all */
if (time_is_after_jiffies(timestamp +
msecs_to_jiffies(1.5*MAX_SLAVE_DIFF))) {
rcu_read_lock();
port = get_late_port(hsr, node);
if (port != NULL)
hsr_nl_ringerror(hsr, node->MacAddressA, port);
rcu_read_unlock();
}
/* Prune old entries */
if (time_is_before_jiffies(timestamp +
msecs_to_jiffies(HSR_NODE_FORGET_TIME))) {
hsr_nl_nodedown(hsr, node->MacAddressA);
list_del_rcu(&node->mac_list);
/* Note that we need to free this entry later: */
kfree_rcu(node, rcu_head);
}
}
rcu_read_unlock();
}
void *hsr_get_next_node(struct hsr_priv *hsr, void *_pos,
unsigned char addr[ETH_ALEN])
{
struct hsr_node *node;
if (!_pos) {
node = list_first_or_null_rcu(&hsr->node_db,
struct hsr_node, mac_list);
if (node)
ether_addr_copy(addr, node->MacAddressA);
return node;
}
node = _pos;
list_for_each_entry_continue_rcu(node, &hsr->node_db, mac_list) {
ether_addr_copy(addr, node->MacAddressA);
return node;
}
return NULL;
}
int hsr_get_node_data(struct hsr_priv *hsr,
const unsigned char *addr,
unsigned char addr_b[ETH_ALEN],
unsigned int *addr_b_ifindex,
int *if1_age,
u16 *if1_seq,
int *if2_age,
u16 *if2_seq)
{
struct hsr_node *node;
struct hsr_port *port;
unsigned long tdiff;
rcu_read_lock();
node = find_node_by_AddrA(&hsr->node_db, addr);
if (!node) {
rcu_read_unlock();
return -ENOENT; /* No such entry */
}
ether_addr_copy(addr_b, node->MacAddressB);
tdiff = jiffies - node->time_in[HSR_PT_SLAVE_A];
if (node->time_in_stale[HSR_PT_SLAVE_A])
*if1_age = INT_MAX;
#if HZ <= MSEC_PER_SEC
else if (tdiff > msecs_to_jiffies(INT_MAX))
*if1_age = INT_MAX;
#endif
else
*if1_age = jiffies_to_msecs(tdiff);
tdiff = jiffies - node->time_in[HSR_PT_SLAVE_B];
if (node->time_in_stale[HSR_PT_SLAVE_B])
*if2_age = INT_MAX;
#if HZ <= MSEC_PER_SEC
else if (tdiff > msecs_to_jiffies(INT_MAX))
*if2_age = INT_MAX;
#endif
else
*if2_age = jiffies_to_msecs(tdiff);
/* Present sequence numbers as if they were incoming on interface */
*if1_seq = node->seq_out[HSR_PT_SLAVE_B];
*if2_seq = node->seq_out[HSR_PT_SLAVE_A];
if (node->AddrB_port != HSR_PT_NONE) {
port = hsr_port_get_hsr(hsr, node->AddrB_port);
*addr_b_ifindex = port->dev->ifindex;
} else {
*addr_b_ifindex = -1;
}
rcu_read_unlock();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_1162_1 |
crossvul-cpp_data_good_2615_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD CCCC M M %
% D D C MM MM %
% D D C M M M %
% D D C M M %
% DDDD CCCC M M %
% %
% %
% Read DICOM Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/constitute.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
/*
Dicom medical image declarations.
*/
typedef struct _DicomInfo
{
const unsigned short
group,
element;
const char
*vr,
*description;
} DicomInfo;
static const DicomInfo
dicom_info[] =
{
{ 0x0000, 0x0000, "UL", "Group Length" },
{ 0x0000, 0x0001, "UL", "Command Length to End" },
{ 0x0000, 0x0002, "UI", "Affected SOP Class UID" },
{ 0x0000, 0x0003, "UI", "Requested SOP Class UID" },
{ 0x0000, 0x0010, "LO", "Command Recognition Code" },
{ 0x0000, 0x0100, "US", "Command Field" },
{ 0x0000, 0x0110, "US", "Message ID" },
{ 0x0000, 0x0120, "US", "Message ID Being Responded To" },
{ 0x0000, 0x0200, "AE", "Initiator" },
{ 0x0000, 0x0300, "AE", "Receiver" },
{ 0x0000, 0x0400, "AE", "Find Location" },
{ 0x0000, 0x0600, "AE", "Move Destination" },
{ 0x0000, 0x0700, "US", "Priority" },
{ 0x0000, 0x0800, "US", "Data Set Type" },
{ 0x0000, 0x0850, "US", "Number of Matches" },
{ 0x0000, 0x0860, "US", "Response Sequence Number" },
{ 0x0000, 0x0900, "US", "Status" },
{ 0x0000, 0x0901, "AT", "Offending Element" },
{ 0x0000, 0x0902, "LO", "Exception Comment" },
{ 0x0000, 0x0903, "US", "Exception ID" },
{ 0x0000, 0x1000, "UI", "Affected SOP Instance UID" },
{ 0x0000, 0x1001, "UI", "Requested SOP Instance UID" },
{ 0x0000, 0x1002, "US", "Event Type ID" },
{ 0x0000, 0x1005, "AT", "Attribute Identifier List" },
{ 0x0000, 0x1008, "US", "Action Type ID" },
{ 0x0000, 0x1020, "US", "Number of Remaining Suboperations" },
{ 0x0000, 0x1021, "US", "Number of Completed Suboperations" },
{ 0x0000, 0x1022, "US", "Number of Failed Suboperations" },
{ 0x0000, 0x1023, "US", "Number of Warning Suboperations" },
{ 0x0000, 0x1030, "AE", "Move Originator Application Entity Title" },
{ 0x0000, 0x1031, "US", "Move Originator Message ID" },
{ 0x0000, 0x4000, "LO", "Dialog Receiver" },
{ 0x0000, 0x4010, "LO", "Terminal Type" },
{ 0x0000, 0x5010, "SH", "Message Set ID" },
{ 0x0000, 0x5020, "SH", "End Message Set" },
{ 0x0000, 0x5110, "LO", "Display Format" },
{ 0x0000, 0x5120, "LO", "Page Position ID" },
{ 0x0000, 0x5130, "LO", "Text Format ID" },
{ 0x0000, 0x5140, "LO", "Normal Reverse" },
{ 0x0000, 0x5150, "LO", "Add Gray Scale" },
{ 0x0000, 0x5160, "LO", "Borders" },
{ 0x0000, 0x5170, "IS", "Copies" },
{ 0x0000, 0x5180, "LO", "OldMagnificationType" },
{ 0x0000, 0x5190, "LO", "Erase" },
{ 0x0000, 0x51a0, "LO", "Print" },
{ 0x0000, 0x51b0, "US", "Overlays" },
{ 0x0002, 0x0000, "UL", "Meta Element Group Length" },
{ 0x0002, 0x0001, "OB", "File Meta Information Version" },
{ 0x0002, 0x0002, "UI", "Media Storage SOP Class UID" },
{ 0x0002, 0x0003, "UI", "Media Storage SOP Instance UID" },
{ 0x0002, 0x0010, "UI", "Transfer Syntax UID" },
{ 0x0002, 0x0012, "UI", "Implementation Class UID" },
{ 0x0002, 0x0013, "SH", "Implementation Version Name" },
{ 0x0002, 0x0016, "AE", "Source Application Entity Title" },
{ 0x0002, 0x0100, "UI", "Private Information Creator UID" },
{ 0x0002, 0x0102, "OB", "Private Information" },
{ 0x0003, 0x0000, "US", "?" },
{ 0x0003, 0x0008, "US", "ISI Command Field" },
{ 0x0003, 0x0011, "US", "Attach ID Application Code" },
{ 0x0003, 0x0012, "UL", "Attach ID Message Count" },
{ 0x0003, 0x0013, "DA", "Attach ID Date" },
{ 0x0003, 0x0014, "TM", "Attach ID Time" },
{ 0x0003, 0x0020, "US", "Message Type" },
{ 0x0003, 0x0030, "DA", "Max Waiting Date" },
{ 0x0003, 0x0031, "TM", "Max Waiting Time" },
{ 0x0004, 0x0000, "UL", "File Set Group Length" },
{ 0x0004, 0x1130, "CS", "File Set ID" },
{ 0x0004, 0x1141, "CS", "File Set Descriptor File ID" },
{ 0x0004, 0x1142, "CS", "File Set Descriptor File Specific Character Set" },
{ 0x0004, 0x1200, "UL", "Root Directory Entity First Directory Record Offset" },
{ 0x0004, 0x1202, "UL", "Root Directory Entity Last Directory Record Offset" },
{ 0x0004, 0x1212, "US", "File Set Consistency Flag" },
{ 0x0004, 0x1220, "SQ", "Directory Record Sequence" },
{ 0x0004, 0x1400, "UL", "Next Directory Record Offset" },
{ 0x0004, 0x1410, "US", "Record In Use Flag" },
{ 0x0004, 0x1420, "UL", "Referenced Lower Level Directory Entity Offset" },
{ 0x0004, 0x1430, "CS", "Directory Record Type" },
{ 0x0004, 0x1432, "UI", "Private Record UID" },
{ 0x0004, 0x1500, "CS", "Referenced File ID" },
{ 0x0004, 0x1504, "UL", "MRDR Directory Record Offset" },
{ 0x0004, 0x1510, "UI", "Referenced SOP Class UID In File" },
{ 0x0004, 0x1511, "UI", "Referenced SOP Instance UID In File" },
{ 0x0004, 0x1512, "UI", "Referenced Transfer Syntax UID In File" },
{ 0x0004, 0x1600, "UL", "Number of References" },
{ 0x0005, 0x0000, "US", "?" },
{ 0x0006, 0x0000, "US", "?" },
{ 0x0008, 0x0000, "UL", "Identifying Group Length" },
{ 0x0008, 0x0001, "UL", "Length to End" },
{ 0x0008, 0x0005, "CS", "Specific Character Set" },
{ 0x0008, 0x0008, "CS", "Image Type" },
{ 0x0008, 0x0010, "LO", "Recognition Code" },
{ 0x0008, 0x0012, "DA", "Instance Creation Date" },
{ 0x0008, 0x0013, "TM", "Instance Creation Time" },
{ 0x0008, 0x0014, "UI", "Instance Creator UID" },
{ 0x0008, 0x0016, "UI", "SOP Class UID" },
{ 0x0008, 0x0018, "UI", "SOP Instance UID" },
{ 0x0008, 0x0020, "DA", "Study Date" },
{ 0x0008, 0x0021, "DA", "Series Date" },
{ 0x0008, 0x0022, "DA", "Acquisition Date" },
{ 0x0008, 0x0023, "DA", "Image Date" },
{ 0x0008, 0x0024, "DA", "Overlay Date" },
{ 0x0008, 0x0025, "DA", "Curve Date" },
{ 0x0008, 0x0030, "TM", "Study Time" },
{ 0x0008, 0x0031, "TM", "Series Time" },
{ 0x0008, 0x0032, "TM", "Acquisition Time" },
{ 0x0008, 0x0033, "TM", "Image Time" },
{ 0x0008, 0x0034, "TM", "Overlay Time" },
{ 0x0008, 0x0035, "TM", "Curve Time" },
{ 0x0008, 0x0040, "xs", "Old Data Set Type" },
{ 0x0008, 0x0041, "xs", "Old Data Set Subtype" },
{ 0x0008, 0x0042, "CS", "Nuclear Medicine Series Type" },
{ 0x0008, 0x0050, "SH", "Accession Number" },
{ 0x0008, 0x0052, "CS", "Query/Retrieve Level" },
{ 0x0008, 0x0054, "AE", "Retrieve AE Title" },
{ 0x0008, 0x0058, "UI", "Failed SOP Instance UID List" },
{ 0x0008, 0x0060, "CS", "Modality" },
{ 0x0008, 0x0062, "SQ", "Modality Subtype" },
{ 0x0008, 0x0064, "CS", "Conversion Type" },
{ 0x0008, 0x0068, "CS", "Presentation Intent Type" },
{ 0x0008, 0x0070, "LO", "Manufacturer" },
{ 0x0008, 0x0080, "LO", "Institution Name" },
{ 0x0008, 0x0081, "ST", "Institution Address" },
{ 0x0008, 0x0082, "SQ", "Institution Code Sequence" },
{ 0x0008, 0x0090, "PN", "Referring Physician's Name" },
{ 0x0008, 0x0092, "ST", "Referring Physician's Address" },
{ 0x0008, 0x0094, "SH", "Referring Physician's Telephone Numbers" },
{ 0x0008, 0x0100, "SH", "Code Value" },
{ 0x0008, 0x0102, "SH", "Coding Scheme Designator" },
{ 0x0008, 0x0103, "SH", "Coding Scheme Version" },
{ 0x0008, 0x0104, "LO", "Code Meaning" },
{ 0x0008, 0x0105, "CS", "Mapping Resource" },
{ 0x0008, 0x0106, "DT", "Context Group Version" },
{ 0x0008, 0x010b, "CS", "Code Set Extension Flag" },
{ 0x0008, 0x010c, "UI", "Private Coding Scheme Creator UID" },
{ 0x0008, 0x010d, "UI", "Code Set Extension Creator UID" },
{ 0x0008, 0x010f, "CS", "Context Identifier" },
{ 0x0008, 0x1000, "LT", "Network ID" },
{ 0x0008, 0x1010, "SH", "Station Name" },
{ 0x0008, 0x1030, "LO", "Study Description" },
{ 0x0008, 0x1032, "SQ", "Procedure Code Sequence" },
{ 0x0008, 0x103e, "LO", "Series Description" },
{ 0x0008, 0x1040, "LO", "Institutional Department Name" },
{ 0x0008, 0x1048, "PN", "Physician of Record" },
{ 0x0008, 0x1050, "PN", "Performing Physician's Name" },
{ 0x0008, 0x1060, "PN", "Name of Physician(s) Reading Study" },
{ 0x0008, 0x1070, "PN", "Operator's Name" },
{ 0x0008, 0x1080, "LO", "Admitting Diagnosis Description" },
{ 0x0008, 0x1084, "SQ", "Admitting Diagnosis Code Sequence" },
{ 0x0008, 0x1090, "LO", "Manufacturer's Model Name" },
{ 0x0008, 0x1100, "SQ", "Referenced Results Sequence" },
{ 0x0008, 0x1110, "SQ", "Referenced Study Sequence" },
{ 0x0008, 0x1111, "SQ", "Referenced Study Component Sequence" },
{ 0x0008, 0x1115, "SQ", "Referenced Series Sequence" },
{ 0x0008, 0x1120, "SQ", "Referenced Patient Sequence" },
{ 0x0008, 0x1125, "SQ", "Referenced Visit Sequence" },
{ 0x0008, 0x1130, "SQ", "Referenced Overlay Sequence" },
{ 0x0008, 0x1140, "SQ", "Referenced Image Sequence" },
{ 0x0008, 0x1145, "SQ", "Referenced Curve Sequence" },
{ 0x0008, 0x1148, "SQ", "Referenced Previous Waveform" },
{ 0x0008, 0x114a, "SQ", "Referenced Simultaneous Waveforms" },
{ 0x0008, 0x114c, "SQ", "Referenced Subsequent Waveform" },
{ 0x0008, 0x1150, "UI", "Referenced SOP Class UID" },
{ 0x0008, 0x1155, "UI", "Referenced SOP Instance UID" },
{ 0x0008, 0x1160, "IS", "Referenced Frame Number" },
{ 0x0008, 0x1195, "UI", "Transaction UID" },
{ 0x0008, 0x1197, "US", "Failure Reason" },
{ 0x0008, 0x1198, "SQ", "Failed SOP Sequence" },
{ 0x0008, 0x1199, "SQ", "Referenced SOP Sequence" },
{ 0x0008, 0x2110, "CS", "Old Lossy Image Compression" },
{ 0x0008, 0x2111, "ST", "Derivation Description" },
{ 0x0008, 0x2112, "SQ", "Source Image Sequence" },
{ 0x0008, 0x2120, "SH", "Stage Name" },
{ 0x0008, 0x2122, "IS", "Stage Number" },
{ 0x0008, 0x2124, "IS", "Number of Stages" },
{ 0x0008, 0x2128, "IS", "View Number" },
{ 0x0008, 0x2129, "IS", "Number of Event Timers" },
{ 0x0008, 0x212a, "IS", "Number of Views in Stage" },
{ 0x0008, 0x2130, "DS", "Event Elapsed Time(s)" },
{ 0x0008, 0x2132, "LO", "Event Timer Name(s)" },
{ 0x0008, 0x2142, "IS", "Start Trim" },
{ 0x0008, 0x2143, "IS", "Stop Trim" },
{ 0x0008, 0x2144, "IS", "Recommended Display Frame Rate" },
{ 0x0008, 0x2200, "CS", "Transducer Position" },
{ 0x0008, 0x2204, "CS", "Transducer Orientation" },
{ 0x0008, 0x2208, "CS", "Anatomic Structure" },
{ 0x0008, 0x2218, "SQ", "Anatomic Region Sequence" },
{ 0x0008, 0x2220, "SQ", "Anatomic Region Modifier Sequence" },
{ 0x0008, 0x2228, "SQ", "Primary Anatomic Structure Sequence" },
{ 0x0008, 0x2230, "SQ", "Primary Anatomic Structure Modifier Sequence" },
{ 0x0008, 0x2240, "SQ", "Transducer Position Sequence" },
{ 0x0008, 0x2242, "SQ", "Transducer Position Modifier Sequence" },
{ 0x0008, 0x2244, "SQ", "Transducer Orientation Sequence" },
{ 0x0008, 0x2246, "SQ", "Transducer Orientation Modifier Sequence" },
{ 0x0008, 0x2251, "SQ", "Anatomic Structure Space Or Region Code Sequence" },
{ 0x0008, 0x2253, "SQ", "Anatomic Portal Of Entrance Code Sequence" },
{ 0x0008, 0x2255, "SQ", "Anatomic Approach Direction Code Sequence" },
{ 0x0008, 0x2256, "ST", "Anatomic Perspective Description" },
{ 0x0008, 0x2257, "SQ", "Anatomic Perspective Code Sequence" },
{ 0x0008, 0x2258, "ST", "Anatomic Location Of Examining Instrument Description" },
{ 0x0008, 0x2259, "SQ", "Anatomic Location Of Examining Instrument Code Sequence" },
{ 0x0008, 0x225a, "SQ", "Anatomic Structure Space Or Region Modifier Code Sequence" },
{ 0x0008, 0x225c, "SQ", "OnAxis Background Anatomic Structure Code Sequence" },
{ 0x0008, 0x4000, "LT", "Identifying Comments" },
{ 0x0009, 0x0000, "xs", "?" },
{ 0x0009, 0x0001, "xs", "?" },
{ 0x0009, 0x0002, "xs", "?" },
{ 0x0009, 0x0003, "xs", "?" },
{ 0x0009, 0x0004, "xs", "?" },
{ 0x0009, 0x0005, "UN", "?" },
{ 0x0009, 0x0006, "UN", "?" },
{ 0x0009, 0x0007, "UN", "?" },
{ 0x0009, 0x0008, "xs", "?" },
{ 0x0009, 0x0009, "LT", "?" },
{ 0x0009, 0x000a, "IS", "?" },
{ 0x0009, 0x000b, "IS", "?" },
{ 0x0009, 0x000c, "IS", "?" },
{ 0x0009, 0x000d, "IS", "?" },
{ 0x0009, 0x000e, "IS", "?" },
{ 0x0009, 0x000f, "UN", "?" },
{ 0x0009, 0x0010, "xs", "?" },
{ 0x0009, 0x0011, "xs", "?" },
{ 0x0009, 0x0012, "xs", "?" },
{ 0x0009, 0x0013, "xs", "?" },
{ 0x0009, 0x0014, "xs", "?" },
{ 0x0009, 0x0015, "xs", "?" },
{ 0x0009, 0x0016, "xs", "?" },
{ 0x0009, 0x0017, "LT", "?" },
{ 0x0009, 0x0018, "LT", "Data Set Identifier" },
{ 0x0009, 0x001a, "US", "?" },
{ 0x0009, 0x001e, "UI", "?" },
{ 0x0009, 0x0020, "xs", "?" },
{ 0x0009, 0x0021, "xs", "?" },
{ 0x0009, 0x0022, "SH", "User Orientation" },
{ 0x0009, 0x0023, "SL", "Initiation Type" },
{ 0x0009, 0x0024, "xs", "?" },
{ 0x0009, 0x0025, "xs", "?" },
{ 0x0009, 0x0026, "xs", "?" },
{ 0x0009, 0x0027, "xs", "?" },
{ 0x0009, 0x0029, "xs", "?" },
{ 0x0009, 0x002a, "SL", "?" },
{ 0x0009, 0x002c, "LO", "Series Comments" },
{ 0x0009, 0x002d, "SL", "Track Beat Average" },
{ 0x0009, 0x002e, "FD", "Distance Prescribed" },
{ 0x0009, 0x002f, "LT", "?" },
{ 0x0009, 0x0030, "xs", "?" },
{ 0x0009, 0x0031, "xs", "?" },
{ 0x0009, 0x0032, "LT", "?" },
{ 0x0009, 0x0034, "xs", "?" },
{ 0x0009, 0x0035, "SL", "Gantry Locus Type" },
{ 0x0009, 0x0037, "SL", "Starting Heart Rate" },
{ 0x0009, 0x0038, "xs", "?" },
{ 0x0009, 0x0039, "SL", "RR Window Offset" },
{ 0x0009, 0x003a, "SL", "Percent Cycle Imaged" },
{ 0x0009, 0x003e, "US", "?" },
{ 0x0009, 0x003f, "US", "?" },
{ 0x0009, 0x0040, "xs", "?" },
{ 0x0009, 0x0041, "xs", "?" },
{ 0x0009, 0x0042, "xs", "?" },
{ 0x0009, 0x0043, "xs", "?" },
{ 0x0009, 0x0050, "LT", "?" },
{ 0x0009, 0x0051, "xs", "?" },
{ 0x0009, 0x0060, "LT", "?" },
{ 0x0009, 0x0061, "LT", "Series Unique Identifier" },
{ 0x0009, 0x0070, "LT", "?" },
{ 0x0009, 0x0080, "LT", "?" },
{ 0x0009, 0x0091, "LT", "?" },
{ 0x0009, 0x00e2, "LT", "?" },
{ 0x0009, 0x00e3, "UI", "Equipment UID" },
{ 0x0009, 0x00e6, "SH", "Genesis Version Now" },
{ 0x0009, 0x00e7, "UL", "Exam Record Checksum" },
{ 0x0009, 0x00e8, "UL", "?" },
{ 0x0009, 0x00e9, "SL", "Actual Series Data Time Stamp" },
{ 0x0009, 0x00f2, "UN", "?" },
{ 0x0009, 0x00f3, "UN", "?" },
{ 0x0009, 0x00f4, "LT", "?" },
{ 0x0009, 0x00f5, "xs", "?" },
{ 0x0009, 0x00f6, "LT", "PDM Data Object Type Extension" },
{ 0x0009, 0x00f8, "US", "?" },
{ 0x0009, 0x00fb, "IS", "?" },
{ 0x0009, 0x1002, "OB", "?" },
{ 0x0009, 0x1003, "OB", "?" },
{ 0x0009, 0x1010, "UN", "?" },
{ 0x0010, 0x0000, "UL", "Patient Group Length" },
{ 0x0010, 0x0010, "PN", "Patient's Name" },
{ 0x0010, 0x0020, "LO", "Patient's ID" },
{ 0x0010, 0x0021, "LO", "Issuer of Patient's ID" },
{ 0x0010, 0x0030, "DA", "Patient's Birth Date" },
{ 0x0010, 0x0032, "TM", "Patient's Birth Time" },
{ 0x0010, 0x0040, "CS", "Patient's Sex" },
{ 0x0010, 0x0050, "SQ", "Patient's Insurance Plan Code Sequence" },
{ 0x0010, 0x1000, "LO", "Other Patient's ID's" },
{ 0x0010, 0x1001, "PN", "Other Patient's Names" },
{ 0x0010, 0x1005, "PN", "Patient's Birth Name" },
{ 0x0010, 0x1010, "AS", "Patient's Age" },
{ 0x0010, 0x1020, "DS", "Patient's Size" },
{ 0x0010, 0x1030, "DS", "Patient's Weight" },
{ 0x0010, 0x1040, "LO", "Patient's Address" },
{ 0x0010, 0x1050, "LT", "Insurance Plan Identification" },
{ 0x0010, 0x1060, "PN", "Patient's Mother's Birth Name" },
{ 0x0010, 0x1080, "LO", "Military Rank" },
{ 0x0010, 0x1081, "LO", "Branch of Service" },
{ 0x0010, 0x1090, "LO", "Medical Record Locator" },
{ 0x0010, 0x2000, "LO", "Medical Alerts" },
{ 0x0010, 0x2110, "LO", "Contrast Allergies" },
{ 0x0010, 0x2150, "LO", "Country of Residence" },
{ 0x0010, 0x2152, "LO", "Region of Residence" },
{ 0x0010, 0x2154, "SH", "Patients Telephone Numbers" },
{ 0x0010, 0x2160, "SH", "Ethnic Group" },
{ 0x0010, 0x2180, "SH", "Occupation" },
{ 0x0010, 0x21a0, "CS", "Smoking Status" },
{ 0x0010, 0x21b0, "LT", "Additional Patient History" },
{ 0x0010, 0x21c0, "US", "Pregnancy Status" },
{ 0x0010, 0x21d0, "DA", "Last Menstrual Date" },
{ 0x0010, 0x21f0, "LO", "Patients Religious Preference" },
{ 0x0010, 0x4000, "LT", "Patient Comments" },
{ 0x0011, 0x0001, "xs", "?" },
{ 0x0011, 0x0002, "US", "?" },
{ 0x0011, 0x0003, "LT", "Patient UID" },
{ 0x0011, 0x0004, "LT", "Patient ID" },
{ 0x0011, 0x000a, "xs", "?" },
{ 0x0011, 0x000b, "SL", "Effective Series Duration" },
{ 0x0011, 0x000c, "SL", "Num Beats" },
{ 0x0011, 0x000d, "LO", "Radio Nuclide Name" },
{ 0x0011, 0x0010, "xs", "?" },
{ 0x0011, 0x0011, "xs", "?" },
{ 0x0011, 0x0012, "LO", "Dataset Name" },
{ 0x0011, 0x0013, "LO", "Dataset Type" },
{ 0x0011, 0x0015, "xs", "?" },
{ 0x0011, 0x0016, "SL", "Energy Number" },
{ 0x0011, 0x0017, "SL", "RR Interval Window Number" },
{ 0x0011, 0x0018, "SL", "MG Bin Number" },
{ 0x0011, 0x0019, "FD", "Radius Of Rotation" },
{ 0x0011, 0x001a, "SL", "Detector Count Zone" },
{ 0x0011, 0x001b, "SL", "Num Energy Windows" },
{ 0x0011, 0x001c, "SL", "Energy Offset" },
{ 0x0011, 0x001d, "SL", "Energy Range" },
{ 0x0011, 0x001f, "SL", "Image Orientation" },
{ 0x0011, 0x0020, "xs", "?" },
{ 0x0011, 0x0021, "xs", "?" },
{ 0x0011, 0x0022, "xs", "?" },
{ 0x0011, 0x0023, "xs", "?" },
{ 0x0011, 0x0024, "SL", "FOV Mask Y Cutoff Angle" },
{ 0x0011, 0x0025, "xs", "?" },
{ 0x0011, 0x0026, "SL", "Table Orientation" },
{ 0x0011, 0x0027, "SL", "ROI Top Left" },
{ 0x0011, 0x0028, "SL", "ROI Bottom Right" },
{ 0x0011, 0x0030, "xs", "?" },
{ 0x0011, 0x0031, "xs", "?" },
{ 0x0011, 0x0032, "UN", "?" },
{ 0x0011, 0x0033, "LO", "Energy Correct Name" },
{ 0x0011, 0x0034, "LO", "Spatial Correct Name" },
{ 0x0011, 0x0035, "xs", "?" },
{ 0x0011, 0x0036, "LO", "Uniformity Correct Name" },
{ 0x0011, 0x0037, "LO", "Acquisition Specific Correct Name" },
{ 0x0011, 0x0038, "SL", "Byte Order" },
{ 0x0011, 0x003a, "SL", "Picture Format" },
{ 0x0011, 0x003b, "FD", "Pixel Scale" },
{ 0x0011, 0x003c, "FD", "Pixel Offset" },
{ 0x0011, 0x003e, "SL", "FOV Shape" },
{ 0x0011, 0x003f, "SL", "Dataset Flags" },
{ 0x0011, 0x0040, "xs", "?" },
{ 0x0011, 0x0041, "LT", "Medical Alerts" },
{ 0x0011, 0x0042, "LT", "Contrast Allergies" },
{ 0x0011, 0x0044, "FD", "Threshold Center" },
{ 0x0011, 0x0045, "FD", "Threshold Width" },
{ 0x0011, 0x0046, "SL", "Interpolation Type" },
{ 0x0011, 0x0055, "FD", "Period" },
{ 0x0011, 0x0056, "FD", "ElapsedTime" },
{ 0x0011, 0x00a1, "DA", "Patient Registration Date" },
{ 0x0011, 0x00a2, "TM", "Patient Registration Time" },
{ 0x0011, 0x00b0, "LT", "Patient Last Name" },
{ 0x0011, 0x00b2, "LT", "Patient First Name" },
{ 0x0011, 0x00b4, "LT", "Patient Hospital Status" },
{ 0x0011, 0x00bc, "TM", "Current Location Time" },
{ 0x0011, 0x00c0, "LT", "Patient Insurance Status" },
{ 0x0011, 0x00d0, "LT", "Patient Billing Type" },
{ 0x0011, 0x00d2, "LT", "Patient Billing Address" },
{ 0x0013, 0x0000, "LT", "Modifying Physician" },
{ 0x0013, 0x0010, "xs", "?" },
{ 0x0013, 0x0011, "SL", "?" },
{ 0x0013, 0x0012, "xs", "?" },
{ 0x0013, 0x0016, "SL", "AutoTrack Peak" },
{ 0x0013, 0x0017, "SL", "AutoTrack Width" },
{ 0x0013, 0x0018, "FD", "Transmission Scan Time" },
{ 0x0013, 0x0019, "FD", "Transmission Mask Width" },
{ 0x0013, 0x001a, "FD", "Copper Attenuator Thickness" },
{ 0x0013, 0x001c, "FD", "?" },
{ 0x0013, 0x001d, "FD", "?" },
{ 0x0013, 0x001e, "FD", "Tomo View Offset" },
{ 0x0013, 0x0020, "LT", "Patient Name" },
{ 0x0013, 0x0022, "LT", "Patient Id" },
{ 0x0013, 0x0026, "LT", "Study Comments" },
{ 0x0013, 0x0030, "DA", "Patient Birthdate" },
{ 0x0013, 0x0031, "DS", "Patient Weight" },
{ 0x0013, 0x0032, "LT", "Patients Maiden Name" },
{ 0x0013, 0x0033, "LT", "Referring Physician" },
{ 0x0013, 0x0034, "LT", "Admitting Diagnosis" },
{ 0x0013, 0x0035, "LT", "Patient Sex" },
{ 0x0013, 0x0040, "LT", "Procedure Description" },
{ 0x0013, 0x0042, "LT", "Patient Rest Direction" },
{ 0x0013, 0x0044, "LT", "Patient Position" },
{ 0x0013, 0x0046, "LT", "View Direction" },
{ 0x0015, 0x0001, "DS", "Stenosis Calibration Ratio" },
{ 0x0015, 0x0002, "DS", "Stenosis Magnification" },
{ 0x0015, 0x0003, "DS", "Cardiac Calibration Ratio" },
{ 0x0018, 0x0000, "UL", "Acquisition Group Length" },
{ 0x0018, 0x0010, "LO", "Contrast/Bolus Agent" },
{ 0x0018, 0x0012, "SQ", "Contrast/Bolus Agent Sequence" },
{ 0x0018, 0x0014, "SQ", "Contrast/Bolus Administration Route Sequence" },
{ 0x0018, 0x0015, "CS", "Body Part Examined" },
{ 0x0018, 0x0020, "CS", "Scanning Sequence" },
{ 0x0018, 0x0021, "CS", "Sequence Variant" },
{ 0x0018, 0x0022, "CS", "Scan Options" },
{ 0x0018, 0x0023, "CS", "MR Acquisition Type" },
{ 0x0018, 0x0024, "SH", "Sequence Name" },
{ 0x0018, 0x0025, "CS", "Angio Flag" },
{ 0x0018, 0x0026, "SQ", "Intervention Drug Information Sequence" },
{ 0x0018, 0x0027, "TM", "Intervention Drug Stop Time" },
{ 0x0018, 0x0028, "DS", "Intervention Drug Dose" },
{ 0x0018, 0x0029, "SQ", "Intervention Drug Code Sequence" },
{ 0x0018, 0x002a, "SQ", "Additional Drug Sequence" },
{ 0x0018, 0x0030, "LO", "Radionuclide" },
{ 0x0018, 0x0031, "LO", "Radiopharmaceutical" },
{ 0x0018, 0x0032, "DS", "Energy Window Centerline" },
{ 0x0018, 0x0033, "DS", "Energy Window Total Width" },
{ 0x0018, 0x0034, "LO", "Intervention Drug Name" },
{ 0x0018, 0x0035, "TM", "Intervention Drug Start Time" },
{ 0x0018, 0x0036, "SQ", "Intervention Therapy Sequence" },
{ 0x0018, 0x0037, "CS", "Therapy Type" },
{ 0x0018, 0x0038, "CS", "Intervention Status" },
{ 0x0018, 0x0039, "CS", "Therapy Description" },
{ 0x0018, 0x0040, "IS", "Cine Rate" },
{ 0x0018, 0x0050, "DS", "Slice Thickness" },
{ 0x0018, 0x0060, "DS", "KVP" },
{ 0x0018, 0x0070, "IS", "Counts Accumulated" },
{ 0x0018, 0x0071, "CS", "Acquisition Termination Condition" },
{ 0x0018, 0x0072, "DS", "Effective Series Duration" },
{ 0x0018, 0x0073, "CS", "Acquisition Start Condition" },
{ 0x0018, 0x0074, "IS", "Acquisition Start Condition Data" },
{ 0x0018, 0x0075, "IS", "Acquisition Termination Condition Data" },
{ 0x0018, 0x0080, "DS", "Repetition Time" },
{ 0x0018, 0x0081, "DS", "Echo Time" },
{ 0x0018, 0x0082, "DS", "Inversion Time" },
{ 0x0018, 0x0083, "DS", "Number of Averages" },
{ 0x0018, 0x0084, "DS", "Imaging Frequency" },
{ 0x0018, 0x0085, "SH", "Imaged Nucleus" },
{ 0x0018, 0x0086, "IS", "Echo Number(s)" },
{ 0x0018, 0x0087, "DS", "Magnetic Field Strength" },
{ 0x0018, 0x0088, "DS", "Spacing Between Slices" },
{ 0x0018, 0x0089, "IS", "Number of Phase Encoding Steps" },
{ 0x0018, 0x0090, "DS", "Data Collection Diameter" },
{ 0x0018, 0x0091, "IS", "Echo Train Length" },
{ 0x0018, 0x0093, "DS", "Percent Sampling" },
{ 0x0018, 0x0094, "DS", "Percent Phase Field of View" },
{ 0x0018, 0x0095, "DS", "Pixel Bandwidth" },
{ 0x0018, 0x1000, "LO", "Device Serial Number" },
{ 0x0018, 0x1004, "LO", "Plate ID" },
{ 0x0018, 0x1010, "LO", "Secondary Capture Device ID" },
{ 0x0018, 0x1012, "DA", "Date of Secondary Capture" },
{ 0x0018, 0x1014, "TM", "Time of Secondary Capture" },
{ 0x0018, 0x1016, "LO", "Secondary Capture Device Manufacturer" },
{ 0x0018, 0x1018, "LO", "Secondary Capture Device Manufacturer Model Name" },
{ 0x0018, 0x1019, "LO", "Secondary Capture Device Software Version(s)" },
{ 0x0018, 0x1020, "LO", "Software Version(s)" },
{ 0x0018, 0x1022, "SH", "Video Image Format Acquired" },
{ 0x0018, 0x1023, "LO", "Digital Image Format Acquired" },
{ 0x0018, 0x1030, "LO", "Protocol Name" },
{ 0x0018, 0x1040, "LO", "Contrast/Bolus Route" },
{ 0x0018, 0x1041, "DS", "Contrast/Bolus Volume" },
{ 0x0018, 0x1042, "TM", "Contrast/Bolus Start Time" },
{ 0x0018, 0x1043, "TM", "Contrast/Bolus Stop Time" },
{ 0x0018, 0x1044, "DS", "Contrast/Bolus Total Dose" },
{ 0x0018, 0x1045, "IS", "Syringe Counts" },
{ 0x0018, 0x1046, "DS", "Contrast Flow Rate" },
{ 0x0018, 0x1047, "DS", "Contrast Flow Duration" },
{ 0x0018, 0x1048, "CS", "Contrast/Bolus Ingredient" },
{ 0x0018, 0x1049, "DS", "Contrast/Bolus Ingredient Concentration" },
{ 0x0018, 0x1050, "DS", "Spatial Resolution" },
{ 0x0018, 0x1060, "DS", "Trigger Time" },
{ 0x0018, 0x1061, "LO", "Trigger Source or Type" },
{ 0x0018, 0x1062, "IS", "Nominal Interval" },
{ 0x0018, 0x1063, "DS", "Frame Time" },
{ 0x0018, 0x1064, "LO", "Framing Type" },
{ 0x0018, 0x1065, "DS", "Frame Time Vector" },
{ 0x0018, 0x1066, "DS", "Frame Delay" },
{ 0x0018, 0x1067, "DS", "Image Trigger Delay" },
{ 0x0018, 0x1068, "DS", "Group Time Offset" },
{ 0x0018, 0x1069, "DS", "Trigger Time Offset" },
{ 0x0018, 0x106a, "CS", "Synchronization Trigger" },
{ 0x0018, 0x106b, "UI", "Synchronization Frame of Reference" },
{ 0x0018, 0x106e, "UL", "Trigger Sample Position" },
{ 0x0018, 0x1070, "LO", "Radiopharmaceutical Route" },
{ 0x0018, 0x1071, "DS", "Radiopharmaceutical Volume" },
{ 0x0018, 0x1072, "TM", "Radiopharmaceutical Start Time" },
{ 0x0018, 0x1073, "TM", "Radiopharmaceutical Stop Time" },
{ 0x0018, 0x1074, "DS", "Radionuclide Total Dose" },
{ 0x0018, 0x1075, "DS", "Radionuclide Half Life" },
{ 0x0018, 0x1076, "DS", "Radionuclide Positron Fraction" },
{ 0x0018, 0x1077, "DS", "Radiopharmaceutical Specific Activity" },
{ 0x0018, 0x1080, "CS", "Beat Rejection Flag" },
{ 0x0018, 0x1081, "IS", "Low R-R Value" },
{ 0x0018, 0x1082, "IS", "High R-R Value" },
{ 0x0018, 0x1083, "IS", "Intervals Acquired" },
{ 0x0018, 0x1084, "IS", "Intervals Rejected" },
{ 0x0018, 0x1085, "LO", "PVC Rejection" },
{ 0x0018, 0x1086, "IS", "Skip Beats" },
{ 0x0018, 0x1088, "IS", "Heart Rate" },
{ 0x0018, 0x1090, "IS", "Cardiac Number of Images" },
{ 0x0018, 0x1094, "IS", "Trigger Window" },
{ 0x0018, 0x1100, "DS", "Reconstruction Diameter" },
{ 0x0018, 0x1110, "DS", "Distance Source to Detector" },
{ 0x0018, 0x1111, "DS", "Distance Source to Patient" },
{ 0x0018, 0x1114, "DS", "Estimated Radiographic Magnification Factor" },
{ 0x0018, 0x1120, "DS", "Gantry/Detector Tilt" },
{ 0x0018, 0x1121, "DS", "Gantry/Detector Slew" },
{ 0x0018, 0x1130, "DS", "Table Height" },
{ 0x0018, 0x1131, "DS", "Table Traverse" },
{ 0x0018, 0x1134, "CS", "Table Motion" },
{ 0x0018, 0x1135, "DS", "Table Vertical Increment" },
{ 0x0018, 0x1136, "DS", "Table Lateral Increment" },
{ 0x0018, 0x1137, "DS", "Table Longitudinal Increment" },
{ 0x0018, 0x1138, "DS", "Table Angle" },
{ 0x0018, 0x113a, "CS", "Table Type" },
{ 0x0018, 0x1140, "CS", "Rotation Direction" },
{ 0x0018, 0x1141, "DS", "Angular Position" },
{ 0x0018, 0x1142, "DS", "Radial Position" },
{ 0x0018, 0x1143, "DS", "Scan Arc" },
{ 0x0018, 0x1144, "DS", "Angular Step" },
{ 0x0018, 0x1145, "DS", "Center of Rotation Offset" },
{ 0x0018, 0x1146, "DS", "Rotation Offset" },
{ 0x0018, 0x1147, "CS", "Field of View Shape" },
{ 0x0018, 0x1149, "IS", "Field of View Dimension(s)" },
{ 0x0018, 0x1150, "IS", "Exposure Time" },
{ 0x0018, 0x1151, "IS", "X-ray Tube Current" },
{ 0x0018, 0x1152, "IS", "Exposure" },
{ 0x0018, 0x1153, "IS", "Exposure in uAs" },
{ 0x0018, 0x1154, "DS", "AveragePulseWidth" },
{ 0x0018, 0x1155, "CS", "RadiationSetting" },
{ 0x0018, 0x1156, "CS", "Rectification Type" },
{ 0x0018, 0x115a, "CS", "RadiationMode" },
{ 0x0018, 0x115e, "DS", "ImageAreaDoseProduct" },
{ 0x0018, 0x1160, "SH", "Filter Type" },
{ 0x0018, 0x1161, "LO", "TypeOfFilters" },
{ 0x0018, 0x1162, "DS", "IntensifierSize" },
{ 0x0018, 0x1164, "DS", "ImagerPixelSpacing" },
{ 0x0018, 0x1166, "CS", "Grid" },
{ 0x0018, 0x1170, "IS", "Generator Power" },
{ 0x0018, 0x1180, "SH", "Collimator/Grid Name" },
{ 0x0018, 0x1181, "CS", "Collimator Type" },
{ 0x0018, 0x1182, "IS", "Focal Distance" },
{ 0x0018, 0x1183, "DS", "X Focus Center" },
{ 0x0018, 0x1184, "DS", "Y Focus Center" },
{ 0x0018, 0x1190, "DS", "Focal Spot(s)" },
{ 0x0018, 0x1191, "CS", "Anode Target Material" },
{ 0x0018, 0x11a0, "DS", "Body Part Thickness" },
{ 0x0018, 0x11a2, "DS", "Compression Force" },
{ 0x0018, 0x1200, "DA", "Date of Last Calibration" },
{ 0x0018, 0x1201, "TM", "Time of Last Calibration" },
{ 0x0018, 0x1210, "SH", "Convolution Kernel" },
{ 0x0018, 0x1240, "IS", "Upper/Lower Pixel Values" },
{ 0x0018, 0x1242, "IS", "Actual Frame Duration" },
{ 0x0018, 0x1243, "IS", "Count Rate" },
{ 0x0018, 0x1244, "US", "Preferred Playback Sequencing" },
{ 0x0018, 0x1250, "SH", "Receiving Coil" },
{ 0x0018, 0x1251, "SH", "Transmitting Coil" },
{ 0x0018, 0x1260, "SH", "Plate Type" },
{ 0x0018, 0x1261, "LO", "Phosphor Type" },
{ 0x0018, 0x1300, "DS", "Scan Velocity" },
{ 0x0018, 0x1301, "CS", "Whole Body Technique" },
{ 0x0018, 0x1302, "IS", "Scan Length" },
{ 0x0018, 0x1310, "US", "Acquisition Matrix" },
{ 0x0018, 0x1312, "CS", "Phase Encoding Direction" },
{ 0x0018, 0x1314, "DS", "Flip Angle" },
{ 0x0018, 0x1315, "CS", "Variable Flip Angle Flag" },
{ 0x0018, 0x1316, "DS", "SAR" },
{ 0x0018, 0x1318, "DS", "dB/dt" },
{ 0x0018, 0x1400, "LO", "Acquisition Device Processing Description" },
{ 0x0018, 0x1401, "LO", "Acquisition Device Processing Code" },
{ 0x0018, 0x1402, "CS", "Cassette Orientation" },
{ 0x0018, 0x1403, "CS", "Cassette Size" },
{ 0x0018, 0x1404, "US", "Exposures on Plate" },
{ 0x0018, 0x1405, "IS", "Relative X-ray Exposure" },
{ 0x0018, 0x1450, "DS", "Column Angulation" },
{ 0x0018, 0x1460, "DS", "Tomo Layer Height" },
{ 0x0018, 0x1470, "DS", "Tomo Angle" },
{ 0x0018, 0x1480, "DS", "Tomo Time" },
{ 0x0018, 0x1490, "CS", "Tomo Type" },
{ 0x0018, 0x1491, "CS", "Tomo Class" },
{ 0x0018, 0x1495, "IS", "Number of Tomosynthesis Source Images" },
{ 0x0018, 0x1500, "CS", "PositionerMotion" },
{ 0x0018, 0x1508, "CS", "Positioner Type" },
{ 0x0018, 0x1510, "DS", "PositionerPrimaryAngle" },
{ 0x0018, 0x1511, "DS", "PositionerSecondaryAngle" },
{ 0x0018, 0x1520, "DS", "PositionerPrimaryAngleIncrement" },
{ 0x0018, 0x1521, "DS", "PositionerSecondaryAngleIncrement" },
{ 0x0018, 0x1530, "DS", "DetectorPrimaryAngle" },
{ 0x0018, 0x1531, "DS", "DetectorSecondaryAngle" },
{ 0x0018, 0x1600, "CS", "Shutter Shape" },
{ 0x0018, 0x1602, "IS", "Shutter Left Vertical Edge" },
{ 0x0018, 0x1604, "IS", "Shutter Right Vertical Edge" },
{ 0x0018, 0x1606, "IS", "Shutter Upper Horizontal Edge" },
{ 0x0018, 0x1608, "IS", "Shutter Lower Horizonta lEdge" },
{ 0x0018, 0x1610, "IS", "Center of Circular Shutter" },
{ 0x0018, 0x1612, "IS", "Radius of Circular Shutter" },
{ 0x0018, 0x1620, "IS", "Vertices of Polygonal Shutter" },
{ 0x0018, 0x1622, "US", "Shutter Presentation Value" },
{ 0x0018, 0x1623, "US", "Shutter Overlay Group" },
{ 0x0018, 0x1700, "CS", "Collimator Shape" },
{ 0x0018, 0x1702, "IS", "Collimator Left Vertical Edge" },
{ 0x0018, 0x1704, "IS", "Collimator Right Vertical Edge" },
{ 0x0018, 0x1706, "IS", "Collimator Upper Horizontal Edge" },
{ 0x0018, 0x1708, "IS", "Collimator Lower Horizontal Edge" },
{ 0x0018, 0x1710, "IS", "Center of Circular Collimator" },
{ 0x0018, 0x1712, "IS", "Radius of Circular Collimator" },
{ 0x0018, 0x1720, "IS", "Vertices of Polygonal Collimator" },
{ 0x0018, 0x1800, "CS", "Acquisition Time Synchronized" },
{ 0x0018, 0x1801, "SH", "Time Source" },
{ 0x0018, 0x1802, "CS", "Time Distribution Protocol" },
{ 0x0018, 0x4000, "LT", "Acquisition Comments" },
{ 0x0018, 0x5000, "SH", "Output Power" },
{ 0x0018, 0x5010, "LO", "Transducer Data" },
{ 0x0018, 0x5012, "DS", "Focus Depth" },
{ 0x0018, 0x5020, "LO", "Processing Function" },
{ 0x0018, 0x5021, "LO", "Postprocessing Function" },
{ 0x0018, 0x5022, "DS", "Mechanical Index" },
{ 0x0018, 0x5024, "DS", "Thermal Index" },
{ 0x0018, 0x5026, "DS", "Cranial Thermal Index" },
{ 0x0018, 0x5027, "DS", "Soft Tissue Thermal Index" },
{ 0x0018, 0x5028, "DS", "Soft Tissue-Focus Thermal Index" },
{ 0x0018, 0x5029, "DS", "Soft Tissue-Surface Thermal Index" },
{ 0x0018, 0x5030, "DS", "Dynamic Range" },
{ 0x0018, 0x5040, "DS", "Total Gain" },
{ 0x0018, 0x5050, "IS", "Depth of Scan Field" },
{ 0x0018, 0x5100, "CS", "Patient Position" },
{ 0x0018, 0x5101, "CS", "View Position" },
{ 0x0018, 0x5104, "SQ", "Projection Eponymous Name Code Sequence" },
{ 0x0018, 0x5210, "DS", "Image Transformation Matrix" },
{ 0x0018, 0x5212, "DS", "Image Translation Vector" },
{ 0x0018, 0x6000, "DS", "Sensitivity" },
{ 0x0018, 0x6011, "IS", "Sequence of Ultrasound Regions" },
{ 0x0018, 0x6012, "US", "Region Spatial Format" },
{ 0x0018, 0x6014, "US", "Region Data Type" },
{ 0x0018, 0x6016, "UL", "Region Flags" },
{ 0x0018, 0x6018, "UL", "Region Location Min X0" },
{ 0x0018, 0x601a, "UL", "Region Location Min Y0" },
{ 0x0018, 0x601c, "UL", "Region Location Max X1" },
{ 0x0018, 0x601e, "UL", "Region Location Max Y1" },
{ 0x0018, 0x6020, "SL", "Reference Pixel X0" },
{ 0x0018, 0x6022, "SL", "Reference Pixel Y0" },
{ 0x0018, 0x6024, "US", "Physical Units X Direction" },
{ 0x0018, 0x6026, "US", "Physical Units Y Direction" },
{ 0x0018, 0x6028, "FD", "Reference Pixel Physical Value X" },
{ 0x0018, 0x602a, "US", "Reference Pixel Physical Value Y" },
{ 0x0018, 0x602c, "US", "Physical Delta X" },
{ 0x0018, 0x602e, "US", "Physical Delta Y" },
{ 0x0018, 0x6030, "UL", "Transducer Frequency" },
{ 0x0018, 0x6031, "CS", "Transducer Type" },
{ 0x0018, 0x6032, "UL", "Pulse Repetition Frequency" },
{ 0x0018, 0x6034, "FD", "Doppler Correction Angle" },
{ 0x0018, 0x6036, "FD", "Steering Angle" },
{ 0x0018, 0x6038, "UL", "Doppler Sample Volume X Position" },
{ 0x0018, 0x603a, "UL", "Doppler Sample Volume Y Position" },
{ 0x0018, 0x603c, "UL", "TM-Line Position X0" },
{ 0x0018, 0x603e, "UL", "TM-Line Position Y0" },
{ 0x0018, 0x6040, "UL", "TM-Line Position X1" },
{ 0x0018, 0x6042, "UL", "TM-Line Position Y1" },
{ 0x0018, 0x6044, "US", "Pixel Component Organization" },
{ 0x0018, 0x6046, "UL", "Pixel Component Mask" },
{ 0x0018, 0x6048, "UL", "Pixel Component Range Start" },
{ 0x0018, 0x604a, "UL", "Pixel Component Range Stop" },
{ 0x0018, 0x604c, "US", "Pixel Component Physical Units" },
{ 0x0018, 0x604e, "US", "Pixel Component Data Type" },
{ 0x0018, 0x6050, "UL", "Number of Table Break Points" },
{ 0x0018, 0x6052, "UL", "Table of X Break Points" },
{ 0x0018, 0x6054, "FD", "Table of Y Break Points" },
{ 0x0018, 0x6056, "UL", "Number of Table Entries" },
{ 0x0018, 0x6058, "UL", "Table of Pixel Values" },
{ 0x0018, 0x605a, "FL", "Table of Parameter Values" },
{ 0x0018, 0x7000, "CS", "Detector Conditions Nominal Flag" },
{ 0x0018, 0x7001, "DS", "Detector Temperature" },
{ 0x0018, 0x7004, "CS", "Detector Type" },
{ 0x0018, 0x7005, "CS", "Detector Configuration" },
{ 0x0018, 0x7006, "LT", "Detector Description" },
{ 0x0018, 0x7008, "LT", "Detector Mode" },
{ 0x0018, 0x700a, "SH", "Detector ID" },
{ 0x0018, 0x700c, "DA", "Date of Last Detector Calibration " },
{ 0x0018, 0x700e, "TM", "Time of Last Detector Calibration" },
{ 0x0018, 0x7010, "IS", "Exposures on Detector Since Last Calibration" },
{ 0x0018, 0x7011, "IS", "Exposures on Detector Since Manufactured" },
{ 0x0018, 0x7012, "DS", "Detector Time Since Last Exposure" },
{ 0x0018, 0x7014, "DS", "Detector Active Time" },
{ 0x0018, 0x7016, "DS", "Detector Activation Offset From Exposure" },
{ 0x0018, 0x701a, "DS", "Detector Binning" },
{ 0x0018, 0x7020, "DS", "Detector Element Physical Size" },
{ 0x0018, 0x7022, "DS", "Detector Element Spacing" },
{ 0x0018, 0x7024, "CS", "Detector Active Shape" },
{ 0x0018, 0x7026, "DS", "Detector Active Dimensions" },
{ 0x0018, 0x7028, "DS", "Detector Active Origin" },
{ 0x0018, 0x7030, "DS", "Field of View Origin" },
{ 0x0018, 0x7032, "DS", "Field of View Rotation" },
{ 0x0018, 0x7034, "CS", "Field of View Horizontal Flip" },
{ 0x0018, 0x7040, "LT", "Grid Absorbing Material" },
{ 0x0018, 0x7041, "LT", "Grid Spacing Material" },
{ 0x0018, 0x7042, "DS", "Grid Thickness" },
{ 0x0018, 0x7044, "DS", "Grid Pitch" },
{ 0x0018, 0x7046, "IS", "Grid Aspect Ratio" },
{ 0x0018, 0x7048, "DS", "Grid Period" },
{ 0x0018, 0x704c, "DS", "Grid Focal Distance" },
{ 0x0018, 0x7050, "LT", "Filter Material" },
{ 0x0018, 0x7052, "DS", "Filter Thickness Minimum" },
{ 0x0018, 0x7054, "DS", "Filter Thickness Maximum" },
{ 0x0018, 0x7060, "CS", "Exposure Control Mode" },
{ 0x0018, 0x7062, "LT", "Exposure Control Mode Description" },
{ 0x0018, 0x7064, "CS", "Exposure Status" },
{ 0x0018, 0x7065, "DS", "Phototimer Setting" },
{ 0x0019, 0x0000, "xs", "?" },
{ 0x0019, 0x0001, "xs", "?" },
{ 0x0019, 0x0002, "xs", "?" },
{ 0x0019, 0x0003, "xs", "?" },
{ 0x0019, 0x0004, "xs", "?" },
{ 0x0019, 0x0005, "xs", "?" },
{ 0x0019, 0x0006, "xs", "?" },
{ 0x0019, 0x0007, "xs", "?" },
{ 0x0019, 0x0008, "xs", "?" },
{ 0x0019, 0x0009, "xs", "?" },
{ 0x0019, 0x000a, "xs", "?" },
{ 0x0019, 0x000b, "DS", "?" },
{ 0x0019, 0x000c, "US", "?" },
{ 0x0019, 0x000d, "TM", "Time" },
{ 0x0019, 0x000e, "xs", "?" },
{ 0x0019, 0x000f, "DS", "Horizontal Frame Of Reference" },
{ 0x0019, 0x0010, "xs", "?" },
{ 0x0019, 0x0011, "xs", "?" },
{ 0x0019, 0x0012, "xs", "?" },
{ 0x0019, 0x0013, "xs", "?" },
{ 0x0019, 0x0014, "xs", "?" },
{ 0x0019, 0x0015, "xs", "?" },
{ 0x0019, 0x0016, "xs", "?" },
{ 0x0019, 0x0017, "xs", "?" },
{ 0x0019, 0x0018, "xs", "?" },
{ 0x0019, 0x0019, "xs", "?" },
{ 0x0019, 0x001a, "xs", "?" },
{ 0x0019, 0x001b, "xs", "?" },
{ 0x0019, 0x001c, "CS", "Dose" },
{ 0x0019, 0x001d, "IS", "Side Mark" },
{ 0x0019, 0x001e, "xs", "?" },
{ 0x0019, 0x001f, "DS", "Exposure Duration" },
{ 0x0019, 0x0020, "xs", "?" },
{ 0x0019, 0x0021, "xs", "?" },
{ 0x0019, 0x0022, "xs", "?" },
{ 0x0019, 0x0023, "xs", "?" },
{ 0x0019, 0x0024, "xs", "?" },
{ 0x0019, 0x0025, "xs", "?" },
{ 0x0019, 0x0026, "xs", "?" },
{ 0x0019, 0x0027, "xs", "?" },
{ 0x0019, 0x0028, "xs", "?" },
{ 0x0019, 0x0029, "IS", "?" },
{ 0x0019, 0x002a, "xs", "?" },
{ 0x0019, 0x002b, "DS", "Xray Off Position" },
{ 0x0019, 0x002c, "xs", "?" },
{ 0x0019, 0x002d, "US", "?" },
{ 0x0019, 0x002e, "xs", "?" },
{ 0x0019, 0x002f, "DS", "Trigger Frequency" },
{ 0x0019, 0x0030, "xs", "?" },
{ 0x0019, 0x0031, "xs", "?" },
{ 0x0019, 0x0032, "xs", "?" },
{ 0x0019, 0x0033, "UN", "ECG 2 Offset 2" },
{ 0x0019, 0x0034, "US", "?" },
{ 0x0019, 0x0036, "US", "?" },
{ 0x0019, 0x0038, "US", "?" },
{ 0x0019, 0x0039, "xs", "?" },
{ 0x0019, 0x003a, "xs", "?" },
{ 0x0019, 0x003b, "LT", "?" },
{ 0x0019, 0x003c, "xs", "?" },
{ 0x0019, 0x003e, "xs", "?" },
{ 0x0019, 0x003f, "UN", "?" },
{ 0x0019, 0x0040, "xs", "?" },
{ 0x0019, 0x0041, "xs", "?" },
{ 0x0019, 0x0042, "xs", "?" },
{ 0x0019, 0x0043, "xs", "?" },
{ 0x0019, 0x0044, "xs", "?" },
{ 0x0019, 0x0045, "xs", "?" },
{ 0x0019, 0x0046, "xs", "?" },
{ 0x0019, 0x0047, "xs", "?" },
{ 0x0019, 0x0048, "xs", "?" },
{ 0x0019, 0x0049, "US", "?" },
{ 0x0019, 0x004a, "xs", "?" },
{ 0x0019, 0x004b, "SL", "Data Size For Scan Data" },
{ 0x0019, 0x004c, "US", "?" },
{ 0x0019, 0x004e, "US", "?" },
{ 0x0019, 0x0050, "xs", "?" },
{ 0x0019, 0x0051, "xs", "?" },
{ 0x0019, 0x0052, "xs", "?" },
{ 0x0019, 0x0053, "LT", "Barcode" },
{ 0x0019, 0x0054, "xs", "?" },
{ 0x0019, 0x0055, "DS", "Receiver Reference Gain" },
{ 0x0019, 0x0056, "xs", "?" },
{ 0x0019, 0x0057, "SS", "CT Water Number" },
{ 0x0019, 0x0058, "xs", "?" },
{ 0x0019, 0x005a, "xs", "?" },
{ 0x0019, 0x005c, "xs", "?" },
{ 0x0019, 0x005d, "US", "?" },
{ 0x0019, 0x005e, "xs", "?" },
{ 0x0019, 0x005f, "SL", "Increment Between Channels" },
{ 0x0019, 0x0060, "xs", "?" },
{ 0x0019, 0x0061, "xs", "?" },
{ 0x0019, 0x0062, "xs", "?" },
{ 0x0019, 0x0063, "xs", "?" },
{ 0x0019, 0x0064, "xs", "?" },
{ 0x0019, 0x0065, "xs", "?" },
{ 0x0019, 0x0066, "xs", "?" },
{ 0x0019, 0x0067, "xs", "?" },
{ 0x0019, 0x0068, "xs", "?" },
{ 0x0019, 0x0069, "UL", "Convolution Mode" },
{ 0x0019, 0x006a, "xs", "?" },
{ 0x0019, 0x006b, "SS", "Field Of View In Detector Cells" },
{ 0x0019, 0x006c, "US", "?" },
{ 0x0019, 0x006e, "US", "?" },
{ 0x0019, 0x0070, "xs", "?" },
{ 0x0019, 0x0071, "xs", "?" },
{ 0x0019, 0x0072, "xs", "?" },
{ 0x0019, 0x0073, "xs", "?" },
{ 0x0019, 0x0074, "xs", "?" },
{ 0x0019, 0x0075, "xs", "?" },
{ 0x0019, 0x0076, "xs", "?" },
{ 0x0019, 0x0077, "US", "?" },
{ 0x0019, 0x0078, "US", "?" },
{ 0x0019, 0x007a, "US", "?" },
{ 0x0019, 0x007c, "US", "?" },
{ 0x0019, 0x007d, "DS", "Second Echo" },
{ 0x0019, 0x007e, "xs", "?" },
{ 0x0019, 0x007f, "DS", "Table Delta" },
{ 0x0019, 0x0080, "xs", "?" },
{ 0x0019, 0x0081, "xs", "?" },
{ 0x0019, 0x0082, "xs", "?" },
{ 0x0019, 0x0083, "xs", "?" },
{ 0x0019, 0x0084, "xs", "?" },
{ 0x0019, 0x0085, "xs", "?" },
{ 0x0019, 0x0086, "xs", "?" },
{ 0x0019, 0x0087, "xs", "?" },
{ 0x0019, 0x0088, "xs", "?" },
{ 0x0019, 0x008a, "xs", "?" },
{ 0x0019, 0x008b, "SS", "Actual Receive Gain Digital" },
{ 0x0019, 0x008c, "US", "?" },
{ 0x0019, 0x008d, "DS", "Delay After Trigger" },
{ 0x0019, 0x008e, "US", "?" },
{ 0x0019, 0x008f, "SS", "Swap Phase Frequency" },
{ 0x0019, 0x0090, "xs", "?" },
{ 0x0019, 0x0091, "xs", "?" },
{ 0x0019, 0x0092, "xs", "?" },
{ 0x0019, 0x0093, "xs", "?" },
{ 0x0019, 0x0094, "xs", "?" },
{ 0x0019, 0x0095, "SS", "Analog Receiver Gain" },
{ 0x0019, 0x0096, "xs", "?" },
{ 0x0019, 0x0097, "xs", "?" },
{ 0x0019, 0x0098, "xs", "?" },
{ 0x0019, 0x0099, "US", "?" },
{ 0x0019, 0x009a, "US", "?" },
{ 0x0019, 0x009b, "SS", "Pulse Sequence Mode" },
{ 0x0019, 0x009c, "xs", "?" },
{ 0x0019, 0x009d, "DT", "Pulse Sequence Date" },
{ 0x0019, 0x009e, "xs", "?" },
{ 0x0019, 0x009f, "xs", "?" },
{ 0x0019, 0x00a0, "xs", "?" },
{ 0x0019, 0x00a1, "xs", "?" },
{ 0x0019, 0x00a2, "xs", "?" },
{ 0x0019, 0x00a3, "xs", "?" },
{ 0x0019, 0x00a4, "xs", "?" },
{ 0x0019, 0x00a5, "xs", "?" },
{ 0x0019, 0x00a6, "xs", "?" },
{ 0x0019, 0x00a7, "xs", "?" },
{ 0x0019, 0x00a8, "xs", "?" },
{ 0x0019, 0x00a9, "xs", "?" },
{ 0x0019, 0x00aa, "xs", "?" },
{ 0x0019, 0x00ab, "xs", "?" },
{ 0x0019, 0x00ac, "xs", "?" },
{ 0x0019, 0x00ad, "xs", "?" },
{ 0x0019, 0x00ae, "xs", "?" },
{ 0x0019, 0x00af, "xs", "?" },
{ 0x0019, 0x00b0, "xs", "?" },
{ 0x0019, 0x00b1, "xs", "?" },
{ 0x0019, 0x00b2, "xs", "?" },
{ 0x0019, 0x00b3, "xs", "?" },
{ 0x0019, 0x00b4, "xs", "?" },
{ 0x0019, 0x00b5, "xs", "?" },
{ 0x0019, 0x00b6, "DS", "User Data" },
{ 0x0019, 0x00b7, "DS", "User Data" },
{ 0x0019, 0x00b8, "DS", "User Data" },
{ 0x0019, 0x00b9, "DS", "User Data" },
{ 0x0019, 0x00ba, "DS", "User Data" },
{ 0x0019, 0x00bb, "DS", "User Data" },
{ 0x0019, 0x00bc, "DS", "User Data" },
{ 0x0019, 0x00bd, "DS", "User Data" },
{ 0x0019, 0x00be, "DS", "Projection Angle" },
{ 0x0019, 0x00c0, "xs", "?" },
{ 0x0019, 0x00c1, "xs", "?" },
{ 0x0019, 0x00c2, "xs", "?" },
{ 0x0019, 0x00c3, "xs", "?" },
{ 0x0019, 0x00c4, "xs", "?" },
{ 0x0019, 0x00c5, "xs", "?" },
{ 0x0019, 0x00c6, "SS", "SAT Location H" },
{ 0x0019, 0x00c7, "SS", "SAT Location F" },
{ 0x0019, 0x00c8, "SS", "SAT Thickness R L" },
{ 0x0019, 0x00c9, "SS", "SAT Thickness A P" },
{ 0x0019, 0x00ca, "SS", "SAT Thickness H F" },
{ 0x0019, 0x00cb, "xs", "?" },
{ 0x0019, 0x00cc, "xs", "?" },
{ 0x0019, 0x00cd, "SS", "Thickness Disclaimer" },
{ 0x0019, 0x00ce, "SS", "Prescan Type" },
{ 0x0019, 0x00cf, "SS", "Prescan Status" },
{ 0x0019, 0x00d0, "SH", "Raw Data Type" },
{ 0x0019, 0x00d1, "DS", "Flow Sensitivity" },
{ 0x0019, 0x00d2, "xs", "?" },
{ 0x0019, 0x00d3, "xs", "?" },
{ 0x0019, 0x00d4, "xs", "?" },
{ 0x0019, 0x00d5, "xs", "?" },
{ 0x0019, 0x00d6, "xs", "?" },
{ 0x0019, 0x00d7, "xs", "?" },
{ 0x0019, 0x00d8, "xs", "?" },
{ 0x0019, 0x00d9, "xs", "?" },
{ 0x0019, 0x00da, "xs", "?" },
{ 0x0019, 0x00db, "DS", "Back Projector Coefficient" },
{ 0x0019, 0x00dc, "SS", "Primary Speed Correction Used" },
{ 0x0019, 0x00dd, "SS", "Overrange Correction Used" },
{ 0x0019, 0x00de, "DS", "Dynamic Z Alpha Value" },
{ 0x0019, 0x00df, "DS", "User Data" },
{ 0x0019, 0x00e0, "DS", "User Data" },
{ 0x0019, 0x00e1, "xs", "?" },
{ 0x0019, 0x00e2, "xs", "?" },
{ 0x0019, 0x00e3, "xs", "?" },
{ 0x0019, 0x00e4, "LT", "?" },
{ 0x0019, 0x00e5, "IS", "?" },
{ 0x0019, 0x00e6, "US", "?" },
{ 0x0019, 0x00e8, "DS", "?" },
{ 0x0019, 0x00e9, "DS", "?" },
{ 0x0019, 0x00eb, "DS", "?" },
{ 0x0019, 0x00ec, "US", "?" },
{ 0x0019, 0x00f0, "xs", "?" },
{ 0x0019, 0x00f1, "xs", "?" },
{ 0x0019, 0x00f2, "xs", "?" },
{ 0x0019, 0x00f3, "xs", "?" },
{ 0x0019, 0x00f4, "LT", "?" },
{ 0x0019, 0x00f9, "DS", "Transmission Gain" },
{ 0x0019, 0x1015, "UN", "?" },
{ 0x0020, 0x0000, "UL", "Relationship Group Length" },
{ 0x0020, 0x000d, "UI", "Study Instance UID" },
{ 0x0020, 0x000e, "UI", "Series Instance UID" },
{ 0x0020, 0x0010, "SH", "Study ID" },
{ 0x0020, 0x0011, "IS", "Series Number" },
{ 0x0020, 0x0012, "IS", "Acquisition Number" },
{ 0x0020, 0x0013, "IS", "Instance (formerly Image) Number" },
{ 0x0020, 0x0014, "IS", "Isotope Number" },
{ 0x0020, 0x0015, "IS", "Phase Number" },
{ 0x0020, 0x0016, "IS", "Interval Number" },
{ 0x0020, 0x0017, "IS", "Time Slot Number" },
{ 0x0020, 0x0018, "IS", "Angle Number" },
{ 0x0020, 0x0020, "CS", "Patient Orientation" },
{ 0x0020, 0x0022, "IS", "Overlay Number" },
{ 0x0020, 0x0024, "IS", "Curve Number" },
{ 0x0020, 0x0026, "IS", "LUT Number" },
{ 0x0020, 0x0030, "DS", "Image Position" },
{ 0x0020, 0x0032, "DS", "Image Position (Patient)" },
{ 0x0020, 0x0035, "DS", "Image Orientation" },
{ 0x0020, 0x0037, "DS", "Image Orientation (Patient)" },
{ 0x0020, 0x0050, "DS", "Location" },
{ 0x0020, 0x0052, "UI", "Frame of Reference UID" },
{ 0x0020, 0x0060, "CS", "Laterality" },
{ 0x0020, 0x0062, "CS", "Image Laterality" },
{ 0x0020, 0x0070, "LT", "Image Geometry Type" },
{ 0x0020, 0x0080, "LO", "Masking Image" },
{ 0x0020, 0x0100, "IS", "Temporal Position Identifier" },
{ 0x0020, 0x0105, "IS", "Number of Temporal Positions" },
{ 0x0020, 0x0110, "DS", "Temporal Resolution" },
{ 0x0020, 0x1000, "IS", "Series in Study" },
{ 0x0020, 0x1001, "DS", "Acquisitions in Series" },
{ 0x0020, 0x1002, "IS", "Images in Acquisition" },
{ 0x0020, 0x1003, "IS", "Images in Series" },
{ 0x0020, 0x1004, "IS", "Acquisitions in Study" },
{ 0x0020, 0x1005, "IS", "Images in Study" },
{ 0x0020, 0x1020, "LO", "Reference" },
{ 0x0020, 0x1040, "LO", "Position Reference Indicator" },
{ 0x0020, 0x1041, "DS", "Slice Location" },
{ 0x0020, 0x1070, "IS", "Other Study Numbers" },
{ 0x0020, 0x1200, "IS", "Number of Patient Related Studies" },
{ 0x0020, 0x1202, "IS", "Number of Patient Related Series" },
{ 0x0020, 0x1204, "IS", "Number of Patient Related Images" },
{ 0x0020, 0x1206, "IS", "Number of Study Related Series" },
{ 0x0020, 0x1208, "IS", "Number of Study Related Series" },
{ 0x0020, 0x3100, "LO", "Source Image IDs" },
{ 0x0020, 0x3401, "LO", "Modifying Device ID" },
{ 0x0020, 0x3402, "LO", "Modified Image ID" },
{ 0x0020, 0x3403, "xs", "Modified Image Date" },
{ 0x0020, 0x3404, "LO", "Modifying Device Manufacturer" },
{ 0x0020, 0x3405, "xs", "Modified Image Time" },
{ 0x0020, 0x3406, "xs", "Modified Image Description" },
{ 0x0020, 0x4000, "LT", "Image Comments" },
{ 0x0020, 0x5000, "AT", "Original Image Identification" },
{ 0x0020, 0x5002, "LO", "Original Image Identification Nomenclature" },
{ 0x0021, 0x0000, "xs", "?" },
{ 0x0021, 0x0001, "xs", "?" },
{ 0x0021, 0x0002, "xs", "?" },
{ 0x0021, 0x0003, "xs", "?" },
{ 0x0021, 0x0004, "DS", "VOI Position" },
{ 0x0021, 0x0005, "xs", "?" },
{ 0x0021, 0x0006, "IS", "CSI Matrix Size Original" },
{ 0x0021, 0x0007, "xs", "?" },
{ 0x0021, 0x0008, "DS", "Spatial Grid Shift" },
{ 0x0021, 0x0009, "DS", "Signal Limits Minimum" },
{ 0x0021, 0x0010, "xs", "?" },
{ 0x0021, 0x0011, "xs", "?" },
{ 0x0021, 0x0012, "xs", "?" },
{ 0x0021, 0x0013, "xs", "?" },
{ 0x0021, 0x0014, "xs", "?" },
{ 0x0021, 0x0015, "xs", "?" },
{ 0x0021, 0x0016, "xs", "?" },
{ 0x0021, 0x0017, "DS", "EPI Operation Mode Flag" },
{ 0x0021, 0x0018, "xs", "?" },
{ 0x0021, 0x0019, "xs", "?" },
{ 0x0021, 0x0020, "xs", "?" },
{ 0x0021, 0x0021, "xs", "?" },
{ 0x0021, 0x0022, "xs", "?" },
{ 0x0021, 0x0024, "xs", "?" },
{ 0x0021, 0x0025, "US", "?" },
{ 0x0021, 0x0026, "IS", "Image Pixel Offset" },
{ 0x0021, 0x0030, "xs", "?" },
{ 0x0021, 0x0031, "xs", "?" },
{ 0x0021, 0x0032, "xs", "?" },
{ 0x0021, 0x0034, "xs", "?" },
{ 0x0021, 0x0035, "SS", "Series From Which Prescribed" },
{ 0x0021, 0x0036, "xs", "?" },
{ 0x0021, 0x0037, "SS", "Screen Format" },
{ 0x0021, 0x0039, "DS", "Slab Thickness" },
{ 0x0021, 0x0040, "xs", "?" },
{ 0x0021, 0x0041, "xs", "?" },
{ 0x0021, 0x0042, "xs", "?" },
{ 0x0021, 0x0043, "xs", "?" },
{ 0x0021, 0x0044, "xs", "?" },
{ 0x0021, 0x0045, "xs", "?" },
{ 0x0021, 0x0046, "xs", "?" },
{ 0x0021, 0x0047, "xs", "?" },
{ 0x0021, 0x0048, "xs", "?" },
{ 0x0021, 0x0049, "xs", "?" },
{ 0x0021, 0x004a, "xs", "?" },
{ 0x0021, 0x004e, "US", "?" },
{ 0x0021, 0x004f, "xs", "?" },
{ 0x0021, 0x0050, "xs", "?" },
{ 0x0021, 0x0051, "xs", "?" },
{ 0x0021, 0x0052, "xs", "?" },
{ 0x0021, 0x0053, "xs", "?" },
{ 0x0021, 0x0054, "xs", "?" },
{ 0x0021, 0x0055, "xs", "?" },
{ 0x0021, 0x0056, "xs", "?" },
{ 0x0021, 0x0057, "xs", "?" },
{ 0x0021, 0x0058, "xs", "?" },
{ 0x0021, 0x0059, "xs", "?" },
{ 0x0021, 0x005a, "SL", "Integer Slop" },
{ 0x0021, 0x005b, "DS", "Float Slop" },
{ 0x0021, 0x005c, "DS", "Float Slop" },
{ 0x0021, 0x005d, "DS", "Float Slop" },
{ 0x0021, 0x005e, "DS", "Float Slop" },
{ 0x0021, 0x005f, "DS", "Float Slop" },
{ 0x0021, 0x0060, "xs", "?" },
{ 0x0021, 0x0061, "DS", "Image Normal" },
{ 0x0021, 0x0062, "IS", "Reference Type Code" },
{ 0x0021, 0x0063, "DS", "Image Distance" },
{ 0x0021, 0x0065, "US", "Image Positioning History Mask" },
{ 0x0021, 0x006a, "DS", "Image Row" },
{ 0x0021, 0x006b, "DS", "Image Column" },
{ 0x0021, 0x0070, "xs", "?" },
{ 0x0021, 0x0071, "xs", "?" },
{ 0x0021, 0x0072, "xs", "?" },
{ 0x0021, 0x0073, "DS", "Second Repetition Time" },
{ 0x0021, 0x0075, "DS", "Light Brightness" },
{ 0x0021, 0x0076, "DS", "Light Contrast" },
{ 0x0021, 0x007a, "IS", "Overlay Threshold" },
{ 0x0021, 0x007b, "IS", "Surface Threshold" },
{ 0x0021, 0x007c, "IS", "Grey Scale Threshold" },
{ 0x0021, 0x0080, "xs", "?" },
{ 0x0021, 0x0081, "DS", "Auto Window Level Alpha" },
{ 0x0021, 0x0082, "xs", "?" },
{ 0x0021, 0x0083, "DS", "Auto Window Level Window" },
{ 0x0021, 0x0084, "DS", "Auto Window Level Level" },
{ 0x0021, 0x0090, "xs", "?" },
{ 0x0021, 0x0091, "xs", "?" },
{ 0x0021, 0x0092, "xs", "?" },
{ 0x0021, 0x0093, "xs", "?" },
{ 0x0021, 0x0094, "DS", "EPI Change Value of X Component" },
{ 0x0021, 0x0095, "DS", "EPI Change Value of Y Component" },
{ 0x0021, 0x0096, "DS", "EPI Change Value of Z Component" },
{ 0x0021, 0x00a0, "xs", "?" },
{ 0x0021, 0x00a1, "DS", "?" },
{ 0x0021, 0x00a2, "xs", "?" },
{ 0x0021, 0x00a3, "LT", "?" },
{ 0x0021, 0x00a4, "LT", "?" },
{ 0x0021, 0x00a7, "LT", "?" },
{ 0x0021, 0x00b0, "IS", "?" },
{ 0x0021, 0x00c0, "IS", "?" },
{ 0x0023, 0x0000, "xs", "?" },
{ 0x0023, 0x0001, "SL", "Number Of Series In Study" },
{ 0x0023, 0x0002, "SL", "Number Of Unarchived Series" },
{ 0x0023, 0x0010, "xs", "?" },
{ 0x0023, 0x0020, "xs", "?" },
{ 0x0023, 0x0030, "xs", "?" },
{ 0x0023, 0x0040, "xs", "?" },
{ 0x0023, 0x0050, "xs", "?" },
{ 0x0023, 0x0060, "xs", "?" },
{ 0x0023, 0x0070, "xs", "?" },
{ 0x0023, 0x0074, "SL", "Number Of Updates To Info" },
{ 0x0023, 0x007d, "SS", "Indicates If Study Has Complete Info" },
{ 0x0023, 0x0080, "xs", "?" },
{ 0x0023, 0x0090, "xs", "?" },
{ 0x0023, 0x00ff, "US", "?" },
{ 0x0025, 0x0000, "UL", "Group Length" },
{ 0x0025, 0x0006, "SS", "Last Pulse Sequence Used" },
{ 0x0025, 0x0007, "SL", "Images In Series" },
{ 0x0025, 0x0010, "SS", "Landmark Counter" },
{ 0x0025, 0x0011, "SS", "Number Of Acquisitions" },
{ 0x0025, 0x0014, "SL", "Indicates Number Of Updates To Info" },
{ 0x0025, 0x0017, "SL", "Series Complete Flag" },
{ 0x0025, 0x0018, "SL", "Number Of Images Archived" },
{ 0x0025, 0x0019, "SL", "Last Image Number Used" },
{ 0x0025, 0x001a, "SH", "Primary Receiver Suite And Host" },
{ 0x0027, 0x0000, "US", "?" },
{ 0x0027, 0x0006, "SL", "Image Archive Flag" },
{ 0x0027, 0x0010, "SS", "Scout Type" },
{ 0x0027, 0x0011, "UN", "?" },
{ 0x0027, 0x0012, "IS", "?" },
{ 0x0027, 0x0013, "IS", "?" },
{ 0x0027, 0x0014, "IS", "?" },
{ 0x0027, 0x0015, "IS", "?" },
{ 0x0027, 0x0016, "LT", "?" },
{ 0x0027, 0x001c, "SL", "Vma Mamp" },
{ 0x0027, 0x001d, "SS", "Vma Phase" },
{ 0x0027, 0x001e, "SL", "Vma Mod" },
{ 0x0027, 0x001f, "SL", "Vma Clip" },
{ 0x0027, 0x0020, "SS", "Smart Scan On Off Flag" },
{ 0x0027, 0x0030, "SH", "Foreign Image Revision" },
{ 0x0027, 0x0031, "SS", "Imaging Mode" },
{ 0x0027, 0x0032, "SS", "Pulse Sequence" },
{ 0x0027, 0x0033, "SL", "Imaging Options" },
{ 0x0027, 0x0035, "SS", "Plane Type" },
{ 0x0027, 0x0036, "SL", "Oblique Plane" },
{ 0x0027, 0x0040, "SH", "RAS Letter Of Image Location" },
{ 0x0027, 0x0041, "FL", "Image Location" },
{ 0x0027, 0x0042, "FL", "Center R Coord Of Plane Image" },
{ 0x0027, 0x0043, "FL", "Center A Coord Of Plane Image" },
{ 0x0027, 0x0044, "FL", "Center S Coord Of Plane Image" },
{ 0x0027, 0x0045, "FL", "Normal R Coord" },
{ 0x0027, 0x0046, "FL", "Normal A Coord" },
{ 0x0027, 0x0047, "FL", "Normal S Coord" },
{ 0x0027, 0x0048, "FL", "R Coord Of Top Right Corner" },
{ 0x0027, 0x0049, "FL", "A Coord Of Top Right Corner" },
{ 0x0027, 0x004a, "FL", "S Coord Of Top Right Corner" },
{ 0x0027, 0x004b, "FL", "R Coord Of Bottom Right Corner" },
{ 0x0027, 0x004c, "FL", "A Coord Of Bottom Right Corner" },
{ 0x0027, 0x004d, "FL", "S Coord Of Bottom Right Corner" },
{ 0x0027, 0x0050, "FL", "Table Start Location" },
{ 0x0027, 0x0051, "FL", "Table End Location" },
{ 0x0027, 0x0052, "SH", "RAS Letter For Side Of Image" },
{ 0x0027, 0x0053, "SH", "RAS Letter For Anterior Posterior" },
{ 0x0027, 0x0054, "SH", "RAS Letter For Scout Start Loc" },
{ 0x0027, 0x0055, "SH", "RAS Letter For Scout End Loc" },
{ 0x0027, 0x0060, "FL", "Image Dimension X" },
{ 0x0027, 0x0061, "FL", "Image Dimension Y" },
{ 0x0027, 0x0062, "FL", "Number Of Excitations" },
{ 0x0028, 0x0000, "UL", "Image Presentation Group Length" },
{ 0x0028, 0x0002, "US", "Samples per Pixel" },
{ 0x0028, 0x0004, "CS", "Photometric Interpretation" },
{ 0x0028, 0x0005, "US", "Image Dimensions" },
{ 0x0028, 0x0006, "US", "Planar Configuration" },
{ 0x0028, 0x0008, "IS", "Number of Frames" },
{ 0x0028, 0x0009, "AT", "Frame Increment Pointer" },
{ 0x0028, 0x0010, "US", "Rows" },
{ 0x0028, 0x0011, "US", "Columns" },
{ 0x0028, 0x0012, "US", "Planes" },
{ 0x0028, 0x0014, "US", "Ultrasound Color Data Present" },
{ 0x0028, 0x0030, "DS", "Pixel Spacing" },
{ 0x0028, 0x0031, "DS", "Zoom Factor" },
{ 0x0028, 0x0032, "DS", "Zoom Center" },
{ 0x0028, 0x0034, "IS", "Pixel Aspect Ratio" },
{ 0x0028, 0x0040, "LO", "Image Format" },
{ 0x0028, 0x0050, "LT", "Manipulated Image" },
{ 0x0028, 0x0051, "CS", "Corrected Image" },
{ 0x0028, 0x005f, "LO", "Compression Recognition Code" },
{ 0x0028, 0x0060, "LO", "Compression Code" },
{ 0x0028, 0x0061, "SH", "Compression Originator" },
{ 0x0028, 0x0062, "SH", "Compression Label" },
{ 0x0028, 0x0063, "SH", "Compression Description" },
{ 0x0028, 0x0065, "LO", "Compression Sequence" },
{ 0x0028, 0x0066, "AT", "Compression Step Pointers" },
{ 0x0028, 0x0068, "US", "Repeat Interval" },
{ 0x0028, 0x0069, "US", "Bits Grouped" },
{ 0x0028, 0x0070, "US", "Perimeter Table" },
{ 0x0028, 0x0071, "xs", "Perimeter Value" },
{ 0x0028, 0x0080, "US", "Predictor Rows" },
{ 0x0028, 0x0081, "US", "Predictor Columns" },
{ 0x0028, 0x0082, "US", "Predictor Constants" },
{ 0x0028, 0x0090, "LO", "Blocked Pixels" },
{ 0x0028, 0x0091, "US", "Block Rows" },
{ 0x0028, 0x0092, "US", "Block Columns" },
{ 0x0028, 0x0093, "US", "Row Overlap" },
{ 0x0028, 0x0094, "US", "Column Overlap" },
{ 0x0028, 0x0100, "US", "Bits Allocated" },
{ 0x0028, 0x0101, "US", "Bits Stored" },
{ 0x0028, 0x0102, "US", "High Bit" },
{ 0x0028, 0x0103, "US", "Pixel Representation" },
{ 0x0028, 0x0104, "xs", "Smallest Valid Pixel Value" },
{ 0x0028, 0x0105, "xs", "Largest Valid Pixel Value" },
{ 0x0028, 0x0106, "xs", "Smallest Image Pixel Value" },
{ 0x0028, 0x0107, "xs", "Largest Image Pixel Value" },
{ 0x0028, 0x0108, "xs", "Smallest Pixel Value in Series" },
{ 0x0028, 0x0109, "xs", "Largest Pixel Value in Series" },
{ 0x0028, 0x0110, "xs", "Smallest Pixel Value in Plane" },
{ 0x0028, 0x0111, "xs", "Largest Pixel Value in Plane" },
{ 0x0028, 0x0120, "xs", "Pixel Padding Value" },
{ 0x0028, 0x0200, "xs", "Image Location" },
{ 0x0028, 0x0300, "CS", "Quality Control Image" },
{ 0x0028, 0x0301, "CS", "Burned In Annotation" },
{ 0x0028, 0x0400, "xs", "?" },
{ 0x0028, 0x0401, "xs", "?" },
{ 0x0028, 0x0402, "xs", "?" },
{ 0x0028, 0x0403, "xs", "?" },
{ 0x0028, 0x0404, "AT", "Details of Coefficients" },
{ 0x0028, 0x0700, "LO", "DCT Label" },
{ 0x0028, 0x0701, "LO", "Data Block Description" },
{ 0x0028, 0x0702, "AT", "Data Block" },
{ 0x0028, 0x0710, "US", "Normalization Factor Format" },
{ 0x0028, 0x0720, "US", "Zonal Map Number Format" },
{ 0x0028, 0x0721, "AT", "Zonal Map Location" },
{ 0x0028, 0x0722, "US", "Zonal Map Format" },
{ 0x0028, 0x0730, "US", "Adaptive Map Format" },
{ 0x0028, 0x0740, "US", "Code Number Format" },
{ 0x0028, 0x0800, "LO", "Code Label" },
{ 0x0028, 0x0802, "US", "Number of Tables" },
{ 0x0028, 0x0803, "AT", "Code Table Location" },
{ 0x0028, 0x0804, "US", "Bits For Code Word" },
{ 0x0028, 0x0808, "AT", "Image Data Location" },
{ 0x0028, 0x1040, "CS", "Pixel Intensity Relationship" },
{ 0x0028, 0x1041, "SS", "Pixel Intensity Relationship Sign" },
{ 0x0028, 0x1050, "DS", "Window Center" },
{ 0x0028, 0x1051, "DS", "Window Width" },
{ 0x0028, 0x1052, "DS", "Rescale Intercept" },
{ 0x0028, 0x1053, "DS", "Rescale Slope" },
{ 0x0028, 0x1054, "LO", "Rescale Type" },
{ 0x0028, 0x1055, "LO", "Window Center & Width Explanation" },
{ 0x0028, 0x1080, "LO", "Gray Scale" },
{ 0x0028, 0x1090, "CS", "Recommended Viewing Mode" },
{ 0x0028, 0x1100, "xs", "Gray Lookup Table Descriptor" },
{ 0x0028, 0x1101, "xs", "Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1102, "xs", "Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1103, "xs", "Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1111, "OW", "Large Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1112, "OW", "Large Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1113, "OW", "Large Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1199, "UI", "Palette Color Lookup Table UID" },
{ 0x0028, 0x1200, "xs", "Gray Lookup Table Data" },
{ 0x0028, 0x1201, "OW", "Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1202, "OW", "Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1203, "OW", "Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1211, "OW", "Large Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1212, "OW", "Large Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1213, "OW", "Large Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1214, "UI", "Large Palette Color Lookup Table UID" },
{ 0x0028, 0x1221, "OW", "Segmented Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1222, "OW", "Segmented Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1223, "OW", "Segmented Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1300, "CS", "Implant Present" },
{ 0x0028, 0x2110, "CS", "Lossy Image Compression" },
{ 0x0028, 0x2112, "DS", "Lossy Image Compression Ratio" },
{ 0x0028, 0x3000, "SQ", "Modality LUT Sequence" },
{ 0x0028, 0x3002, "US", "LUT Descriptor" },
{ 0x0028, 0x3003, "LO", "LUT Explanation" },
{ 0x0028, 0x3004, "LO", "Modality LUT Type" },
{ 0x0028, 0x3006, "US", "LUT Data" },
{ 0x0028, 0x3010, "xs", "VOI LUT Sequence" },
{ 0x0028, 0x4000, "LT", "Image Presentation Comments" },
{ 0x0028, 0x5000, "SQ", "Biplane Acquisition Sequence" },
{ 0x0028, 0x6010, "US", "Representative Frame Number" },
{ 0x0028, 0x6020, "US", "Frame Numbers of Interest" },
{ 0x0028, 0x6022, "LO", "Frame of Interest Description" },
{ 0x0028, 0x6030, "US", "Mask Pointer" },
{ 0x0028, 0x6040, "US", "R Wave Pointer" },
{ 0x0028, 0x6100, "SQ", "Mask Subtraction Sequence" },
{ 0x0028, 0x6101, "CS", "Mask Operation" },
{ 0x0028, 0x6102, "US", "Applicable Frame Range" },
{ 0x0028, 0x6110, "US", "Mask Frame Numbers" },
{ 0x0028, 0x6112, "US", "Contrast Frame Averaging" },
{ 0x0028, 0x6114, "FL", "Mask Sub-Pixel Shift" },
{ 0x0028, 0x6120, "SS", "TID Offset" },
{ 0x0028, 0x6190, "ST", "Mask Operation Explanation" },
{ 0x0029, 0x0000, "xs", "?" },
{ 0x0029, 0x0001, "xs", "?" },
{ 0x0029, 0x0002, "xs", "?" },
{ 0x0029, 0x0003, "xs", "?" },
{ 0x0029, 0x0004, "xs", "?" },
{ 0x0029, 0x0005, "xs", "?" },
{ 0x0029, 0x0006, "xs", "?" },
{ 0x0029, 0x0007, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0008, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x0009, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x000a, "SS", "Lower Range Of Pixels" },
{ 0x0029, 0x000c, "xs", "?" },
{ 0x0029, 0x000e, "CS", "Zoom Enable Status" },
{ 0x0029, 0x000f, "CS", "Zoom Select Status" },
{ 0x0029, 0x0010, "xs", "?" },
{ 0x0029, 0x0011, "xs", "?" },
{ 0x0029, 0x0013, "LT", "?" },
{ 0x0029, 0x0015, "xs", "?" },
{ 0x0029, 0x0016, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0017, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0018, "SL", "Upper Range Of Pixels" },
{ 0x0029, 0x001a, "SL", "Length Of Total Info In Bytes" },
{ 0x0029, 0x001e, "xs", "?" },
{ 0x0029, 0x001f, "xs", "?" },
{ 0x0029, 0x0020, "xs", "?" },
{ 0x0029, 0x0022, "IS", "Pixel Quality Value" },
{ 0x0029, 0x0025, "LT", "Processed Pixel Data Quality" },
{ 0x0029, 0x0026, "SS", "Version Of Info Structure" },
{ 0x0029, 0x0030, "xs", "?" },
{ 0x0029, 0x0031, "xs", "?" },
{ 0x0029, 0x0032, "xs", "?" },
{ 0x0029, 0x0033, "xs", "?" },
{ 0x0029, 0x0034, "xs", "?" },
{ 0x0029, 0x0035, "SL", "Advantage Comp Underflow" },
{ 0x0029, 0x0038, "US", "?" },
{ 0x0029, 0x0040, "xs", "?" },
{ 0x0029, 0x0041, "DS", "Magnifying Glass Rectangle" },
{ 0x0029, 0x0043, "DS", "Magnifying Glass Factor" },
{ 0x0029, 0x0044, "US", "Magnifying Glass Function" },
{ 0x0029, 0x004e, "CS", "Magnifying Glass Enable Status" },
{ 0x0029, 0x004f, "CS", "Magnifying Glass Select Status" },
{ 0x0029, 0x0050, "xs", "?" },
{ 0x0029, 0x0051, "LT", "Exposure Code" },
{ 0x0029, 0x0052, "LT", "Sort Code" },
{ 0x0029, 0x0053, "LT", "?" },
{ 0x0029, 0x0060, "xs", "?" },
{ 0x0029, 0x0061, "xs", "?" },
{ 0x0029, 0x0067, "LT", "?" },
{ 0x0029, 0x0070, "xs", "?" },
{ 0x0029, 0x0071, "xs", "?" },
{ 0x0029, 0x0072, "xs", "?" },
{ 0x0029, 0x0077, "CS", "Window Select Status" },
{ 0x0029, 0x0078, "LT", "ECG Display Printing ID" },
{ 0x0029, 0x0079, "CS", "ECG Display Printing" },
{ 0x0029, 0x007e, "CS", "ECG Display Printing Enable Status" },
{ 0x0029, 0x007f, "CS", "ECG Display Printing Select Status" },
{ 0x0029, 0x0080, "xs", "?" },
{ 0x0029, 0x0081, "xs", "?" },
{ 0x0029, 0x0082, "IS", "View Zoom" },
{ 0x0029, 0x0083, "IS", "View Transform" },
{ 0x0029, 0x008e, "CS", "Physiological Display Enable Status" },
{ 0x0029, 0x008f, "CS", "Physiological Display Select Status" },
{ 0x0029, 0x0090, "IS", "?" },
{ 0x0029, 0x0099, "LT", "Shutter Type" },
{ 0x0029, 0x00a0, "US", "Rows of Rectangular Shutter" },
{ 0x0029, 0x00a1, "US", "Columns of Rectangular Shutter" },
{ 0x0029, 0x00a2, "US", "Origin of Rectangular Shutter" },
{ 0x0029, 0x00b0, "US", "Radius of Circular Shutter" },
{ 0x0029, 0x00b2, "US", "Origin of Circular Shutter" },
{ 0x0029, 0x00c0, "LT", "Functional Shutter ID" },
{ 0x0029, 0x00c1, "xs", "?" },
{ 0x0029, 0x00c3, "IS", "Scan Resolution" },
{ 0x0029, 0x00c4, "IS", "Field of View" },
{ 0x0029, 0x00c5, "LT", "Field Of Shutter Rectangle" },
{ 0x0029, 0x00ce, "CS", "Shutter Enable Status" },
{ 0x0029, 0x00cf, "CS", "Shutter Select Status" },
{ 0x0029, 0x00d0, "IS", "?" },
{ 0x0029, 0x00d1, "IS", "?" },
{ 0x0029, 0x00d5, "LT", "Slice Thickness" },
{ 0x0031, 0x0010, "LT", "Request UID" },
{ 0x0031, 0x0012, "LT", "Examination Reason" },
{ 0x0031, 0x0030, "DA", "Requested Date" },
{ 0x0031, 0x0032, "TM", "Worklist Request Start Time" },
{ 0x0031, 0x0033, "TM", "Worklist Request End Time" },
{ 0x0031, 0x0045, "LT", "Requesting Physician" },
{ 0x0031, 0x004a, "TM", "Requested Time" },
{ 0x0031, 0x0050, "LT", "Requested Physician" },
{ 0x0031, 0x0080, "LT", "Requested Location" },
{ 0x0032, 0x0000, "UL", "Study Group Length" },
{ 0x0032, 0x000a, "CS", "Study Status ID" },
{ 0x0032, 0x000c, "CS", "Study Priority ID" },
{ 0x0032, 0x0012, "LO", "Study ID Issuer" },
{ 0x0032, 0x0032, "DA", "Study Verified Date" },
{ 0x0032, 0x0033, "TM", "Study Verified Time" },
{ 0x0032, 0x0034, "DA", "Study Read Date" },
{ 0x0032, 0x0035, "TM", "Study Read Time" },
{ 0x0032, 0x1000, "DA", "Scheduled Study Start Date" },
{ 0x0032, 0x1001, "TM", "Scheduled Study Start Time" },
{ 0x0032, 0x1010, "DA", "Scheduled Study Stop Date" },
{ 0x0032, 0x1011, "TM", "Scheduled Study Stop Time" },
{ 0x0032, 0x1020, "LO", "Scheduled Study Location" },
{ 0x0032, 0x1021, "AE", "Scheduled Study Location AE Title(s)" },
{ 0x0032, 0x1030, "LO", "Reason for Study" },
{ 0x0032, 0x1032, "PN", "Requesting Physician" },
{ 0x0032, 0x1033, "LO", "Requesting Service" },
{ 0x0032, 0x1040, "DA", "Study Arrival Date" },
{ 0x0032, 0x1041, "TM", "Study Arrival Time" },
{ 0x0032, 0x1050, "DA", "Study Completion Date" },
{ 0x0032, 0x1051, "TM", "Study Completion Time" },
{ 0x0032, 0x1055, "CS", "Study Component Status ID" },
{ 0x0032, 0x1060, "LO", "Requested Procedure Description" },
{ 0x0032, 0x1064, "SQ", "Requested Procedure Code Sequence" },
{ 0x0032, 0x1070, "LO", "Requested Contrast Agent" },
{ 0x0032, 0x4000, "LT", "Study Comments" },
{ 0x0033, 0x0001, "UN", "?" },
{ 0x0033, 0x0002, "UN", "?" },
{ 0x0033, 0x0005, "UN", "?" },
{ 0x0033, 0x0006, "UN", "?" },
{ 0x0033, 0x0010, "LT", "Patient Study UID" },
{ 0x0037, 0x0010, "LO", "ReferringDepartment" },
{ 0x0037, 0x0020, "US", "ScreenNumber" },
{ 0x0037, 0x0040, "SH", "LeftOrientation" },
{ 0x0037, 0x0042, "SH", "RightOrientation" },
{ 0x0037, 0x0050, "CS", "Inversion" },
{ 0x0037, 0x0060, "US", "DSA" },
{ 0x0038, 0x0000, "UL", "Visit Group Length" },
{ 0x0038, 0x0004, "SQ", "Referenced Patient Alias Sequence" },
{ 0x0038, 0x0008, "CS", "Visit Status ID" },
{ 0x0038, 0x0010, "LO", "Admission ID" },
{ 0x0038, 0x0011, "LO", "Issuer of Admission ID" },
{ 0x0038, 0x0016, "LO", "Route of Admissions" },
{ 0x0038, 0x001a, "DA", "Scheduled Admission Date" },
{ 0x0038, 0x001b, "TM", "Scheduled Admission Time" },
{ 0x0038, 0x001c, "DA", "Scheduled Discharge Date" },
{ 0x0038, 0x001d, "TM", "Scheduled Discharge Time" },
{ 0x0038, 0x001e, "LO", "Scheduled Patient Institution Residence" },
{ 0x0038, 0x0020, "DA", "Admitting Date" },
{ 0x0038, 0x0021, "TM", "Admitting Time" },
{ 0x0038, 0x0030, "DA", "Discharge Date" },
{ 0x0038, 0x0032, "TM", "Discharge Time" },
{ 0x0038, 0x0040, "LO", "Discharge Diagnosis Description" },
{ 0x0038, 0x0044, "SQ", "Discharge Diagnosis Code Sequence" },
{ 0x0038, 0x0050, "LO", "Special Needs" },
{ 0x0038, 0x0300, "LO", "Current Patient Location" },
{ 0x0038, 0x0400, "LO", "Patient's Institution Residence" },
{ 0x0038, 0x0500, "LO", "Patient State" },
{ 0x0038, 0x4000, "LT", "Visit Comments" },
{ 0x0039, 0x0080, "IS", "Private Entity Number" },
{ 0x0039, 0x0085, "DA", "Private Entity Date" },
{ 0x0039, 0x0090, "TM", "Private Entity Time" },
{ 0x0039, 0x0095, "LO", "Private Entity Launch Command" },
{ 0x0039, 0x00aa, "CS", "Private Entity Type" },
{ 0x003a, 0x0002, "SQ", "Waveform Sequence" },
{ 0x003a, 0x0005, "US", "Waveform Number of Channels" },
{ 0x003a, 0x0010, "UL", "Waveform Number of Samples" },
{ 0x003a, 0x001a, "DS", "Sampling Frequency" },
{ 0x003a, 0x0020, "SH", "Group Label" },
{ 0x003a, 0x0103, "CS", "Waveform Sample Value Representation" },
{ 0x003a, 0x0122, "OB", "Waveform Padding Value" },
{ 0x003a, 0x0200, "SQ", "Channel Definition" },
{ 0x003a, 0x0202, "IS", "Waveform Channel Number" },
{ 0x003a, 0x0203, "SH", "Channel Label" },
{ 0x003a, 0x0205, "CS", "Channel Status" },
{ 0x003a, 0x0208, "SQ", "Channel Source" },
{ 0x003a, 0x0209, "SQ", "Channel Source Modifiers" },
{ 0x003a, 0x020a, "SQ", "Differential Channel Source" },
{ 0x003a, 0x020b, "SQ", "Differential Channel Source Modifiers" },
{ 0x003a, 0x0210, "DS", "Channel Sensitivity" },
{ 0x003a, 0x0211, "SQ", "Channel Sensitivity Units" },
{ 0x003a, 0x0212, "DS", "Channel Sensitivity Correction Factor" },
{ 0x003a, 0x0213, "DS", "Channel Baseline" },
{ 0x003a, 0x0214, "DS", "Channel Time Skew" },
{ 0x003a, 0x0215, "DS", "Channel Sample Skew" },
{ 0x003a, 0x0216, "OB", "Channel Minimum Value" },
{ 0x003a, 0x0217, "OB", "Channel Maximum Value" },
{ 0x003a, 0x0218, "DS", "Channel Offset" },
{ 0x003a, 0x021a, "US", "Bits Per Sample" },
{ 0x003a, 0x0220, "DS", "Filter Low Frequency" },
{ 0x003a, 0x0221, "DS", "Filter High Frequency" },
{ 0x003a, 0x0222, "DS", "Notch Filter Frequency" },
{ 0x003a, 0x0223, "DS", "Notch Filter Bandwidth" },
{ 0x003a, 0x1000, "OB", "Waveform Data" },
{ 0x0040, 0x0001, "AE", "Scheduled Station AE Title" },
{ 0x0040, 0x0002, "DA", "Scheduled Procedure Step Start Date" },
{ 0x0040, 0x0003, "TM", "Scheduled Procedure Step Start Time" },
{ 0x0040, 0x0004, "DA", "Scheduled Procedure Step End Date" },
{ 0x0040, 0x0005, "TM", "Scheduled Procedure Step End Time" },
{ 0x0040, 0x0006, "PN", "Scheduled Performing Physician Name" },
{ 0x0040, 0x0007, "LO", "Scheduled Procedure Step Description" },
{ 0x0040, 0x0008, "SQ", "Scheduled Action Item Code Sequence" },
{ 0x0040, 0x0009, "SH", "Scheduled Procedure Step ID" },
{ 0x0040, 0x0010, "SH", "Scheduled Station Name" },
{ 0x0040, 0x0011, "SH", "Scheduled Procedure Step Location" },
{ 0x0040, 0x0012, "LO", "Pre-Medication" },
{ 0x0040, 0x0020, "CS", "Scheduled Procedure Step Status" },
{ 0x0040, 0x0100, "SQ", "Scheduled Procedure Step Sequence" },
{ 0x0040, 0x0302, "US", "Entrance Dose" },
{ 0x0040, 0x0303, "US", "Exposed Area" },
{ 0x0040, 0x0306, "DS", "Distance Source to Entrance" },
{ 0x0040, 0x0307, "DS", "Distance Source to Support" },
{ 0x0040, 0x0310, "ST", "Comments On Radiation Dose" },
{ 0x0040, 0x0312, "DS", "X-Ray Output" },
{ 0x0040, 0x0314, "DS", "Half Value Layer" },
{ 0x0040, 0x0316, "DS", "Organ Dose" },
{ 0x0040, 0x0318, "CS", "Organ Exposed" },
{ 0x0040, 0x0400, "LT", "Comments On Scheduled Procedure Step" },
{ 0x0040, 0x050a, "LO", "Specimen Accession Number" },
{ 0x0040, 0x0550, "SQ", "Specimen Sequence" },
{ 0x0040, 0x0551, "LO", "Specimen Identifier" },
{ 0x0040, 0x0552, "SQ", "Specimen Description Sequence" },
{ 0x0040, 0x0553, "ST", "Specimen Description" },
{ 0x0040, 0x0555, "SQ", "Acquisition Context Sequence" },
{ 0x0040, 0x0556, "ST", "Acquisition Context Description" },
{ 0x0040, 0x059a, "SQ", "Specimen Type Code Sequence" },
{ 0x0040, 0x06fa, "LO", "Slide Identifier" },
{ 0x0040, 0x071a, "SQ", "Image Center Point Coordinates Sequence" },
{ 0x0040, 0x072a, "DS", "X Offset In Slide Coordinate System" },
{ 0x0040, 0x073a, "DS", "Y Offset In Slide Coordinate System" },
{ 0x0040, 0x074a, "DS", "Z Offset In Slide Coordinate System" },
{ 0x0040, 0x08d8, "SQ", "Pixel Spacing Sequence" },
{ 0x0040, 0x08da, "SQ", "Coordinate System Axis Code Sequence" },
{ 0x0040, 0x08ea, "SQ", "Measurement Units Code Sequence" },
{ 0x0040, 0x09f8, "SQ", "Vital Stain Code Sequence" },
{ 0x0040, 0x1001, "SH", "Requested Procedure ID" },
{ 0x0040, 0x1002, "LO", "Reason For Requested Procedure" },
{ 0x0040, 0x1003, "SH", "Requested Procedure Priority" },
{ 0x0040, 0x1004, "LO", "Patient Transport Arrangements" },
{ 0x0040, 0x1005, "LO", "Requested Procedure Location" },
{ 0x0040, 0x1006, "SH", "Placer Order Number of Procedure" },
{ 0x0040, 0x1007, "SH", "Filler Order Number of Procedure" },
{ 0x0040, 0x1008, "LO", "Confidentiality Code" },
{ 0x0040, 0x1009, "SH", "Reporting Priority" },
{ 0x0040, 0x1010, "PN", "Names of Intended Recipients of Results" },
{ 0x0040, 0x1400, "LT", "Requested Procedure Comments" },
{ 0x0040, 0x2001, "LO", "Reason For Imaging Service Request" },
{ 0x0040, 0x2004, "DA", "Issue Date of Imaging Service Request" },
{ 0x0040, 0x2005, "TM", "Issue Time of Imaging Service Request" },
{ 0x0040, 0x2006, "SH", "Placer Order Number of Imaging Service Request" },
{ 0x0040, 0x2007, "SH", "Filler Order Number of Imaging Service Request" },
{ 0x0040, 0x2008, "PN", "Order Entered By" },
{ 0x0040, 0x2009, "SH", "Order Enterer Location" },
{ 0x0040, 0x2010, "SH", "Order Callback Phone Number" },
{ 0x0040, 0x2400, "LT", "Imaging Service Request Comments" },
{ 0x0040, 0x3001, "LO", "Confidentiality Constraint On Patient Data" },
{ 0x0040, 0xa007, "CS", "Findings Flag" },
{ 0x0040, 0xa020, "SQ", "Findings Sequence" },
{ 0x0040, 0xa021, "UI", "Findings Group UID" },
{ 0x0040, 0xa022, "UI", "Referenced Findings Group UID" },
{ 0x0040, 0xa023, "DA", "Findings Group Recording Date" },
{ 0x0040, 0xa024, "TM", "Findings Group Recording Time" },
{ 0x0040, 0xa026, "SQ", "Findings Source Category Code Sequence" },
{ 0x0040, 0xa027, "LO", "Documenting Organization" },
{ 0x0040, 0xa028, "SQ", "Documenting Organization Identifier Code Sequence" },
{ 0x0040, 0xa032, "LO", "History Reliability Qualifier Description" },
{ 0x0040, 0xa043, "SQ", "Concept Name Code Sequence" },
{ 0x0040, 0xa047, "LO", "Measurement Precision Description" },
{ 0x0040, 0xa057, "CS", "Urgency or Priority Alerts" },
{ 0x0040, 0xa060, "LO", "Sequencing Indicator" },
{ 0x0040, 0xa066, "SQ", "Document Identifier Code Sequence" },
{ 0x0040, 0xa067, "PN", "Document Author" },
{ 0x0040, 0xa068, "SQ", "Document Author Identifier Code Sequence" },
{ 0x0040, 0xa070, "SQ", "Identifier Code Sequence" },
{ 0x0040, 0xa073, "LO", "Object String Identifier" },
{ 0x0040, 0xa074, "OB", "Object Binary Identifier" },
{ 0x0040, 0xa075, "PN", "Documenting Observer" },
{ 0x0040, 0xa076, "SQ", "Documenting Observer Identifier Code Sequence" },
{ 0x0040, 0xa078, "SQ", "Observation Subject Identifier Code Sequence" },
{ 0x0040, 0xa080, "SQ", "Person Identifier Code Sequence" },
{ 0x0040, 0xa085, "SQ", "Procedure Identifier Code Sequence" },
{ 0x0040, 0xa088, "LO", "Object Directory String Identifier" },
{ 0x0040, 0xa089, "OB", "Object Directory Binary Identifier" },
{ 0x0040, 0xa090, "CS", "History Reliability Qualifier" },
{ 0x0040, 0xa0a0, "CS", "Referenced Type of Data" },
{ 0x0040, 0xa0b0, "US", "Referenced Waveform Channels" },
{ 0x0040, 0xa110, "DA", "Date of Document or Verbal Transaction" },
{ 0x0040, 0xa112, "TM", "Time of Document Creation or Verbal Transaction" },
{ 0x0040, 0xa121, "DA", "Date" },
{ 0x0040, 0xa122, "TM", "Time" },
{ 0x0040, 0xa123, "PN", "Person Name" },
{ 0x0040, 0xa124, "SQ", "Referenced Person Sequence" },
{ 0x0040, 0xa125, "CS", "Report Status ID" },
{ 0x0040, 0xa130, "CS", "Temporal Range Type" },
{ 0x0040, 0xa132, "UL", "Referenced Sample Offsets" },
{ 0x0040, 0xa136, "US", "Referenced Frame Numbers" },
{ 0x0040, 0xa138, "DS", "Referenced Time Offsets" },
{ 0x0040, 0xa13a, "DT", "Referenced Datetime" },
{ 0x0040, 0xa160, "UT", "Text Value" },
{ 0x0040, 0xa167, "SQ", "Observation Category Code Sequence" },
{ 0x0040, 0xa168, "SQ", "Concept Code Sequence" },
{ 0x0040, 0xa16a, "ST", "Bibliographic Citation" },
{ 0x0040, 0xa170, "CS", "Observation Class" },
{ 0x0040, 0xa171, "UI", "Observation UID" },
{ 0x0040, 0xa172, "UI", "Referenced Observation UID" },
{ 0x0040, 0xa173, "CS", "Referenced Observation Class" },
{ 0x0040, 0xa174, "CS", "Referenced Object Observation Class" },
{ 0x0040, 0xa180, "US", "Annotation Group Number" },
{ 0x0040, 0xa192, "DA", "Observation Date" },
{ 0x0040, 0xa193, "TM", "Observation Time" },
{ 0x0040, 0xa194, "CS", "Measurement Automation" },
{ 0x0040, 0xa195, "SQ", "Concept Name Code Sequence Modifier" },
{ 0x0040, 0xa224, "ST", "Identification Description" },
{ 0x0040, 0xa290, "CS", "Coordinates Set Geometric Type" },
{ 0x0040, 0xa296, "SQ", "Algorithm Code Sequence" },
{ 0x0040, 0xa297, "ST", "Algorithm Description" },
{ 0x0040, 0xa29a, "SL", "Pixel Coordinates Set" },
{ 0x0040, 0xa300, "SQ", "Measured Value Sequence" },
{ 0x0040, 0xa307, "PN", "Current Observer" },
{ 0x0040, 0xa30a, "DS", "Numeric Value" },
{ 0x0040, 0xa313, "SQ", "Referenced Accession Sequence" },
{ 0x0040, 0xa33a, "ST", "Report Status Comment" },
{ 0x0040, 0xa340, "SQ", "Procedure Context Sequence" },
{ 0x0040, 0xa352, "PN", "Verbal Source" },
{ 0x0040, 0xa353, "ST", "Address" },
{ 0x0040, 0xa354, "LO", "Telephone Number" },
{ 0x0040, 0xa358, "SQ", "Verbal Source Identifier Code Sequence" },
{ 0x0040, 0xa380, "SQ", "Report Detail Sequence" },
{ 0x0040, 0xa402, "UI", "Observation Subject UID" },
{ 0x0040, 0xa403, "CS", "Observation Subject Class" },
{ 0x0040, 0xa404, "SQ", "Observation Subject Type Code Sequence" },
{ 0x0040, 0xa600, "CS", "Observation Subject Context Flag" },
{ 0x0040, 0xa601, "CS", "Observer Context Flag" },
{ 0x0040, 0xa603, "CS", "Procedure Context Flag" },
{ 0x0040, 0xa730, "SQ", "Observations Sequence" },
{ 0x0040, 0xa731, "SQ", "Relationship Sequence" },
{ 0x0040, 0xa732, "SQ", "Relationship Type Code Sequence" },
{ 0x0040, 0xa744, "SQ", "Language Code Sequence" },
{ 0x0040, 0xa992, "ST", "Uniform Resource Locator" },
{ 0x0040, 0xb020, "SQ", "Annotation Sequence" },
{ 0x0040, 0xdb73, "SQ", "Relationship Type Code Sequence Modifier" },
{ 0x0041, 0x0000, "LT", "Papyrus Comments" },
{ 0x0041, 0x0010, "xs", "?" },
{ 0x0041, 0x0011, "xs", "?" },
{ 0x0041, 0x0012, "UL", "Pixel Offset" },
{ 0x0041, 0x0013, "SQ", "Image Identifier Sequence" },
{ 0x0041, 0x0014, "SQ", "External File Reference Sequence" },
{ 0x0041, 0x0015, "US", "Number of Images" },
{ 0x0041, 0x0020, "xs", "?" },
{ 0x0041, 0x0021, "UI", "Referenced SOP Class UID" },
{ 0x0041, 0x0022, "UI", "Referenced SOP Instance UID" },
{ 0x0041, 0x0030, "xs", "?" },
{ 0x0041, 0x0031, "xs", "?" },
{ 0x0041, 0x0032, "xs", "?" },
{ 0x0041, 0x0034, "DA", "Modified Date" },
{ 0x0041, 0x0036, "TM", "Modified Time" },
{ 0x0041, 0x0040, "LT", "Owner Name" },
{ 0x0041, 0x0041, "UI", "Referenced Image SOP Class UID" },
{ 0x0041, 0x0042, "UI", "Referenced Image SOP Instance UID" },
{ 0x0041, 0x0050, "xs", "?" },
{ 0x0041, 0x0060, "UL", "Number of Images" },
{ 0x0041, 0x0062, "UL", "Number of Other" },
{ 0x0041, 0x00a0, "LT", "External Folder Element DSID" },
{ 0x0041, 0x00a1, "US", "External Folder Element Data Set Type" },
{ 0x0041, 0x00a2, "LT", "External Folder Element File Location" },
{ 0x0041, 0x00a3, "UL", "External Folder Element Length" },
{ 0x0041, 0x00b0, "LT", "Internal Folder Element DSID" },
{ 0x0041, 0x00b1, "US", "Internal Folder Element Data Set Type" },
{ 0x0041, 0x00b2, "UL", "Internal Offset To Data Set" },
{ 0x0041, 0x00b3, "UL", "Internal Offset To Image" },
{ 0x0043, 0x0001, "SS", "Bitmap Of Prescan Options" },
{ 0x0043, 0x0002, "SS", "Gradient Offset In X" },
{ 0x0043, 0x0003, "SS", "Gradient Offset In Y" },
{ 0x0043, 0x0004, "SS", "Gradient Offset In Z" },
{ 0x0043, 0x0005, "SS", "Image Is Original Or Unoriginal" },
{ 0x0043, 0x0006, "SS", "Number Of EPI Shots" },
{ 0x0043, 0x0007, "SS", "Views Per Segment" },
{ 0x0043, 0x0008, "SS", "Respiratory Rate In BPM" },
{ 0x0043, 0x0009, "SS", "Respiratory Trigger Point" },
{ 0x0043, 0x000a, "SS", "Type Of Receiver Used" },
{ 0x0043, 0x000b, "DS", "Peak Rate Of Change Of Gradient Field" },
{ 0x0043, 0x000c, "DS", "Limits In Units Of Percent" },
{ 0x0043, 0x000d, "DS", "PSD Estimated Limit" },
{ 0x0043, 0x000e, "DS", "PSD Estimated Limit In Tesla Per Second" },
{ 0x0043, 0x000f, "DS", "SAR Avg Head" },
{ 0x0043, 0x0010, "US", "Window Value" },
{ 0x0043, 0x0011, "US", "Total Input Views" },
{ 0x0043, 0x0012, "SS", "Xray Chain" },
{ 0x0043, 0x0013, "SS", "Recon Kernel Parameters" },
{ 0x0043, 0x0014, "SS", "Calibration Parameters" },
{ 0x0043, 0x0015, "SS", "Total Output Views" },
{ 0x0043, 0x0016, "SS", "Number Of Overranges" },
{ 0x0043, 0x0017, "DS", "IBH Image Scale Factors" },
{ 0x0043, 0x0018, "DS", "BBH Coefficients" },
{ 0x0043, 0x0019, "SS", "Number Of BBH Chains To Blend" },
{ 0x0043, 0x001a, "SL", "Starting Channel Number" },
{ 0x0043, 0x001b, "SS", "PPScan Parameters" },
{ 0x0043, 0x001c, "SS", "GE Image Integrity" },
{ 0x0043, 0x001d, "SS", "Level Value" },
{ 0x0043, 0x001e, "xs", "?" },
{ 0x0043, 0x001f, "SL", "Max Overranges In A View" },
{ 0x0043, 0x0020, "DS", "Avg Overranges All Views" },
{ 0x0043, 0x0021, "SS", "Corrected Afterglow Terms" },
{ 0x0043, 0x0025, "SS", "Reference Channels" },
{ 0x0043, 0x0026, "US", "No Views Ref Channels Blocked" },
{ 0x0043, 0x0027, "xs", "?" },
{ 0x0043, 0x0028, "OB", "Unique Image Identifier" },
{ 0x0043, 0x0029, "OB", "Histogram Tables" },
{ 0x0043, 0x002a, "OB", "User Defined Data" },
{ 0x0043, 0x002b, "SS", "Private Scan Options" },
{ 0x0043, 0x002c, "SS", "Effective Echo Spacing" },
{ 0x0043, 0x002d, "SH", "String Slop Field 1" },
{ 0x0043, 0x002e, "SH", "String Slop Field 2" },
{ 0x0043, 0x002f, "SS", "Raw Data Type" },
{ 0x0043, 0x0030, "SS", "Raw Data Type" },
{ 0x0043, 0x0031, "DS", "RA Coord Of Target Recon Centre" },
{ 0x0043, 0x0032, "SS", "Raw Data Type" },
{ 0x0043, 0x0033, "FL", "Neg Scan Spacing" },
{ 0x0043, 0x0034, "IS", "Offset Frequency" },
{ 0x0043, 0x0035, "UL", "User Usage Tag" },
{ 0x0043, 0x0036, "UL", "User Fill Map MSW" },
{ 0x0043, 0x0037, "UL", "User Fill Map LSW" },
{ 0x0043, 0x0038, "FL", "User 25 To User 48" },
{ 0x0043, 0x0039, "IS", "Slop Integer 6 To Slop Integer 9" },
{ 0x0043, 0x0040, "FL", "Trigger On Position" },
{ 0x0043, 0x0041, "FL", "Degree Of Rotation" },
{ 0x0043, 0x0042, "SL", "DAS Trigger Source" },
{ 0x0043, 0x0043, "SL", "DAS Fpa Gain" },
{ 0x0043, 0x0044, "SL", "DAS Output Source" },
{ 0x0043, 0x0045, "SL", "DAS Ad Input" },
{ 0x0043, 0x0046, "SL", "DAS Cal Mode" },
{ 0x0043, 0x0047, "SL", "DAS Cal Frequency" },
{ 0x0043, 0x0048, "SL", "DAS Reg Xm" },
{ 0x0043, 0x0049, "SL", "DAS Auto Zero" },
{ 0x0043, 0x004a, "SS", "Starting Channel Of View" },
{ 0x0043, 0x004b, "SL", "DAS Xm Pattern" },
{ 0x0043, 0x004c, "SS", "TGGC Trigger Mode" },
{ 0x0043, 0x004d, "FL", "Start Scan To Xray On Delay" },
{ 0x0043, 0x004e, "FL", "Duration Of Xray On" },
{ 0x0044, 0x0000, "UI", "?" },
{ 0x0045, 0x0004, "CS", "AES" },
{ 0x0045, 0x0006, "DS", "Angulation" },
{ 0x0045, 0x0009, "DS", "Real Magnification Factor" },
{ 0x0045, 0x000b, "CS", "Senograph Type" },
{ 0x0045, 0x000c, "DS", "Integration Time" },
{ 0x0045, 0x000d, "DS", "ROI Origin X and Y" },
{ 0x0045, 0x0011, "DS", "Receptor Size cm X and Y" },
{ 0x0045, 0x0012, "IS", "Receptor Size Pixels X and Y" },
{ 0x0045, 0x0013, "ST", "Screen" },
{ 0x0045, 0x0014, "DS", "Pixel Pitch Microns" },
{ 0x0045, 0x0015, "IS", "Pixel Depth Bits" },
{ 0x0045, 0x0016, "IS", "Binning Factor X and Y" },
{ 0x0045, 0x001b, "CS", "Clinical View" },
{ 0x0045, 0x001d, "DS", "Mean Of Raw Gray Levels" },
{ 0x0045, 0x001e, "DS", "Mean Of Offset Gray Levels" },
{ 0x0045, 0x001f, "DS", "Mean Of Corrected Gray Levels" },
{ 0x0045, 0x0020, "DS", "Mean Of Region Gray Levels" },
{ 0x0045, 0x0021, "DS", "Mean Of Log Region Gray Levels" },
{ 0x0045, 0x0022, "DS", "Standard Deviation Of Raw Gray Levels" },
{ 0x0045, 0x0023, "DS", "Standard Deviation Of Corrected Gray Levels" },
{ 0x0045, 0x0024, "DS", "Standard Deviation Of Region Gray Levels" },
{ 0x0045, 0x0025, "DS", "Standard Deviation Of Log Region Gray Levels" },
{ 0x0045, 0x0026, "OB", "MAO Buffer" },
{ 0x0045, 0x0027, "IS", "Set Number" },
{ 0x0045, 0x0028, "CS", "WindowingType (LINEAR or GAMMA)" },
{ 0x0045, 0x0029, "DS", "WindowingParameters" },
{ 0x0045, 0x002a, "IS", "Crosshair Cursor X Coordinates" },
{ 0x0045, 0x002b, "IS", "Crosshair Cursor Y Coordinates" },
{ 0x0045, 0x0039, "US", "Vignette Rows" },
{ 0x0045, 0x003a, "US", "Vignette Columns" },
{ 0x0045, 0x003b, "US", "Vignette Bits Allocated" },
{ 0x0045, 0x003c, "US", "Vignette Bits Stored" },
{ 0x0045, 0x003d, "US", "Vignette High Bit" },
{ 0x0045, 0x003e, "US", "Vignette Pixel Representation" },
{ 0x0045, 0x003f, "OB", "Vignette Pixel Data" },
{ 0x0047, 0x0001, "SQ", "Reconstruction Parameters Sequence" },
{ 0x0047, 0x0050, "UL", "Volume Voxel Count" },
{ 0x0047, 0x0051, "UL", "Volume Segment Count" },
{ 0x0047, 0x0053, "US", "Volume Slice Size" },
{ 0x0047, 0x0054, "US", "Volume Slice Count" },
{ 0x0047, 0x0055, "SL", "Volume Threshold Value" },
{ 0x0047, 0x0057, "DS", "Volume Voxel Ratio" },
{ 0x0047, 0x0058, "DS", "Volume Voxel Size" },
{ 0x0047, 0x0059, "US", "Volume Z Position Size" },
{ 0x0047, 0x0060, "DS", "Volume Base Line" },
{ 0x0047, 0x0061, "DS", "Volume Center Point" },
{ 0x0047, 0x0063, "SL", "Volume Skew Base" },
{ 0x0047, 0x0064, "DS", "Volume Registration Transform Rotation Matrix" },
{ 0x0047, 0x0065, "DS", "Volume Registration Transform Translation Vector" },
{ 0x0047, 0x0070, "DS", "KVP List" },
{ 0x0047, 0x0071, "IS", "XRay Tube Current List" },
{ 0x0047, 0x0072, "IS", "Exposure List" },
{ 0x0047, 0x0080, "LO", "Acquisition DLX Identifier" },
{ 0x0047, 0x0085, "SQ", "Acquisition DLX 2D Series Sequence" },
{ 0x0047, 0x0089, "DS", "Contrast Agent Volume List" },
{ 0x0047, 0x008a, "US", "Number Of Injections" },
{ 0x0047, 0x008b, "US", "Frame Count" },
{ 0x0047, 0x0096, "IS", "Used Frames" },
{ 0x0047, 0x0091, "LO", "XA 3D Reconstruction Algorithm Name" },
{ 0x0047, 0x0092, "CS", "XA 3D Reconstruction Algorithm Version" },
{ 0x0047, 0x0093, "DA", "DLX Calibration Date" },
{ 0x0047, 0x0094, "TM", "DLX Calibration Time" },
{ 0x0047, 0x0095, "CS", "DLX Calibration Status" },
{ 0x0047, 0x0098, "US", "Transform Count" },
{ 0x0047, 0x0099, "SQ", "Transform Sequence" },
{ 0x0047, 0x009a, "DS", "Transform Rotation Matrix" },
{ 0x0047, 0x009b, "DS", "Transform Translation Vector" },
{ 0x0047, 0x009c, "LO", "Transform Label" },
{ 0x0047, 0x00b1, "US", "Wireframe Count" },
{ 0x0047, 0x00b2, "US", "Location System" },
{ 0x0047, 0x00b0, "SQ", "Wireframe List" },
{ 0x0047, 0x00b5, "LO", "Wireframe Name" },
{ 0x0047, 0x00b6, "LO", "Wireframe Group Name" },
{ 0x0047, 0x00b7, "LO", "Wireframe Color" },
{ 0x0047, 0x00b8, "SL", "Wireframe Attributes" },
{ 0x0047, 0x00b9, "SL", "Wireframe Point Count" },
{ 0x0047, 0x00ba, "SL", "Wireframe Timestamp" },
{ 0x0047, 0x00bb, "SQ", "Wireframe Point List" },
{ 0x0047, 0x00bc, "DS", "Wireframe Points Coordinates" },
{ 0x0047, 0x00c0, "DS", "Volume Upper Left High Corner RAS" },
{ 0x0047, 0x00c1, "DS", "Volume Slice To RAS Rotation Matrix" },
{ 0x0047, 0x00c2, "DS", "Volume Upper Left High Corner TLOC" },
{ 0x0047, 0x00d1, "OB", "Volume Segment List" },
{ 0x0047, 0x00d2, "OB", "Volume Gradient List" },
{ 0x0047, 0x00d3, "OB", "Volume Density List" },
{ 0x0047, 0x00d4, "OB", "Volume Z Position List" },
{ 0x0047, 0x00d5, "OB", "Volume Original Index List" },
{ 0x0050, 0x0000, "UL", "Calibration Group Length" },
{ 0x0050, 0x0004, "CS", "Calibration Object" },
{ 0x0050, 0x0010, "SQ", "DeviceSequence" },
{ 0x0050, 0x0014, "DS", "DeviceLength" },
{ 0x0050, 0x0016, "DS", "DeviceDiameter" },
{ 0x0050, 0x0017, "CS", "DeviceDiameterUnits" },
{ 0x0050, 0x0018, "DS", "DeviceVolume" },
{ 0x0050, 0x0019, "DS", "InterMarkerDistance" },
{ 0x0050, 0x0020, "LO", "DeviceDescription" },
{ 0x0050, 0x0030, "SQ", "CodedInterventionDeviceSequence" },
{ 0x0051, 0x0010, "xs", "Image Text" },
{ 0x0054, 0x0000, "UL", "Nuclear Acquisition Group Length" },
{ 0x0054, 0x0010, "US", "Energy Window Vector" },
{ 0x0054, 0x0011, "US", "Number of Energy Windows" },
{ 0x0054, 0x0012, "SQ", "Energy Window Information Sequence" },
{ 0x0054, 0x0013, "SQ", "Energy Window Range Sequence" },
{ 0x0054, 0x0014, "DS", "Energy Window Lower Limit" },
{ 0x0054, 0x0015, "DS", "Energy Window Upper Limit" },
{ 0x0054, 0x0016, "SQ", "Radiopharmaceutical Information Sequence" },
{ 0x0054, 0x0017, "IS", "Residual Syringe Counts" },
{ 0x0054, 0x0018, "SH", "Energy Window Name" },
{ 0x0054, 0x0020, "US", "Detector Vector" },
{ 0x0054, 0x0021, "US", "Number of Detectors" },
{ 0x0054, 0x0022, "SQ", "Detector Information Sequence" },
{ 0x0054, 0x0030, "US", "Phase Vector" },
{ 0x0054, 0x0031, "US", "Number of Phases" },
{ 0x0054, 0x0032, "SQ", "Phase Information Sequence" },
{ 0x0054, 0x0033, "US", "Number of Frames In Phase" },
{ 0x0054, 0x0036, "IS", "Phase Delay" },
{ 0x0054, 0x0038, "IS", "Pause Between Frames" },
{ 0x0054, 0x0050, "US", "Rotation Vector" },
{ 0x0054, 0x0051, "US", "Number of Rotations" },
{ 0x0054, 0x0052, "SQ", "Rotation Information Sequence" },
{ 0x0054, 0x0053, "US", "Number of Frames In Rotation" },
{ 0x0054, 0x0060, "US", "R-R Interval Vector" },
{ 0x0054, 0x0061, "US", "Number of R-R Intervals" },
{ 0x0054, 0x0062, "SQ", "Gated Information Sequence" },
{ 0x0054, 0x0063, "SQ", "Data Information Sequence" },
{ 0x0054, 0x0070, "US", "Time Slot Vector" },
{ 0x0054, 0x0071, "US", "Number of Time Slots" },
{ 0x0054, 0x0072, "SQ", "Time Slot Information Sequence" },
{ 0x0054, 0x0073, "DS", "Time Slot Time" },
{ 0x0054, 0x0080, "US", "Slice Vector" },
{ 0x0054, 0x0081, "US", "Number of Slices" },
{ 0x0054, 0x0090, "US", "Angular View Vector" },
{ 0x0054, 0x0100, "US", "Time Slice Vector" },
{ 0x0054, 0x0101, "US", "Number Of Time Slices" },
{ 0x0054, 0x0200, "DS", "Start Angle" },
{ 0x0054, 0x0202, "CS", "Type of Detector Motion" },
{ 0x0054, 0x0210, "IS", "Trigger Vector" },
{ 0x0054, 0x0211, "US", "Number of Triggers in Phase" },
{ 0x0054, 0x0220, "SQ", "View Code Sequence" },
{ 0x0054, 0x0222, "SQ", "View Modifier Code Sequence" },
{ 0x0054, 0x0300, "SQ", "Radionuclide Code Sequence" },
{ 0x0054, 0x0302, "SQ", "Radiopharmaceutical Route Code Sequence" },
{ 0x0054, 0x0304, "SQ", "Radiopharmaceutical Code Sequence" },
{ 0x0054, 0x0306, "SQ", "Calibration Data Sequence" },
{ 0x0054, 0x0308, "US", "Energy Window Number" },
{ 0x0054, 0x0400, "SH", "Image ID" },
{ 0x0054, 0x0410, "SQ", "Patient Orientation Code Sequence" },
{ 0x0054, 0x0412, "SQ", "Patient Orientation Modifier Code Sequence" },
{ 0x0054, 0x0414, "SQ", "Patient Gantry Relationship Code Sequence" },
{ 0x0054, 0x1000, "CS", "Positron Emission Tomography Series Type" },
{ 0x0054, 0x1001, "CS", "Positron Emission Tomography Units" },
{ 0x0054, 0x1002, "CS", "Counts Source" },
{ 0x0054, 0x1004, "CS", "Reprojection Method" },
{ 0x0054, 0x1100, "CS", "Randoms Correction Method" },
{ 0x0054, 0x1101, "LO", "Attenuation Correction Method" },
{ 0x0054, 0x1102, "CS", "Decay Correction" },
{ 0x0054, 0x1103, "LO", "Reconstruction Method" },
{ 0x0054, 0x1104, "LO", "Detector Lines of Response Used" },
{ 0x0054, 0x1105, "LO", "Scatter Correction Method" },
{ 0x0054, 0x1200, "DS", "Axial Acceptance" },
{ 0x0054, 0x1201, "IS", "Axial Mash" },
{ 0x0054, 0x1202, "IS", "Transverse Mash" },
{ 0x0054, 0x1203, "DS", "Detector Element Size" },
{ 0x0054, 0x1210, "DS", "Coincidence Window Width" },
{ 0x0054, 0x1220, "CS", "Secondary Counts Type" },
{ 0x0054, 0x1300, "DS", "Frame Reference Time" },
{ 0x0054, 0x1310, "IS", "Primary Prompts Counts Accumulated" },
{ 0x0054, 0x1311, "IS", "Secondary Counts Accumulated" },
{ 0x0054, 0x1320, "DS", "Slice Sensitivity Factor" },
{ 0x0054, 0x1321, "DS", "Decay Factor" },
{ 0x0054, 0x1322, "DS", "Dose Calibration Factor" },
{ 0x0054, 0x1323, "DS", "Scatter Fraction Factor" },
{ 0x0054, 0x1324, "DS", "Dead Time Factor" },
{ 0x0054, 0x1330, "US", "Image Index" },
{ 0x0054, 0x1400, "CS", "Counts Included" },
{ 0x0054, 0x1401, "CS", "Dead Time Correction Flag" },
{ 0x0055, 0x0046, "LT", "Current Ward" },
{ 0x0058, 0x0000, "SQ", "?" },
{ 0x0060, 0x3000, "SQ", "Histogram Sequence" },
{ 0x0060, 0x3002, "US", "Histogram Number of Bins" },
{ 0x0060, 0x3004, "xs", "Histogram First Bin Value" },
{ 0x0060, 0x3006, "xs", "Histogram Last Bin Value" },
{ 0x0060, 0x3008, "US", "Histogram Bin Width" },
{ 0x0060, 0x3010, "LO", "Histogram Explanation" },
{ 0x0060, 0x3020, "UL", "Histogram Data" },
{ 0x0070, 0x0001, "SQ", "Graphic Annotation Sequence" },
{ 0x0070, 0x0002, "CS", "Graphic Layer" },
{ 0x0070, 0x0003, "CS", "Bounding Box Annotation Units" },
{ 0x0070, 0x0004, "CS", "Anchor Point Annotation Units" },
{ 0x0070, 0x0005, "CS", "Graphic Annotation Units" },
{ 0x0070, 0x0006, "ST", "Unformatted Text Value" },
{ 0x0070, 0x0008, "SQ", "Text Object Sequence" },
{ 0x0070, 0x0009, "SQ", "Graphic Object Sequence" },
{ 0x0070, 0x0010, "FL", "Bounding Box TLHC" },
{ 0x0070, 0x0011, "FL", "Bounding Box BRHC" },
{ 0x0070, 0x0014, "FL", "Anchor Point" },
{ 0x0070, 0x0015, "CS", "Anchor Point Visibility" },
{ 0x0070, 0x0020, "US", "Graphic Dimensions" },
{ 0x0070, 0x0021, "US", "Number Of Graphic Points" },
{ 0x0070, 0x0022, "FL", "Graphic Data" },
{ 0x0070, 0x0023, "CS", "Graphic Type" },
{ 0x0070, 0x0024, "CS", "Graphic Filled" },
{ 0x0070, 0x0040, "IS", "Image Rotation" },
{ 0x0070, 0x0041, "CS", "Image Horizontal Flip" },
{ 0x0070, 0x0050, "US", "Displayed Area TLHC" },
{ 0x0070, 0x0051, "US", "Displayed Area BRHC" },
{ 0x0070, 0x0060, "SQ", "Graphic Layer Sequence" },
{ 0x0070, 0x0062, "IS", "Graphic Layer Order" },
{ 0x0070, 0x0066, "US", "Graphic Layer Recommended Display Value" },
{ 0x0070, 0x0068, "LO", "Graphic Layer Description" },
{ 0x0070, 0x0080, "CS", "Presentation Label" },
{ 0x0070, 0x0081, "LO", "Presentation Description" },
{ 0x0070, 0x0082, "DA", "Presentation Creation Date" },
{ 0x0070, 0x0083, "TM", "Presentation Creation Time" },
{ 0x0070, 0x0084, "PN", "Presentation Creator's Name" },
{ 0x0087, 0x0010, "CS", "Media Type" },
{ 0x0087, 0x0020, "CS", "Media Location" },
{ 0x0087, 0x0050, "IS", "Estimated Retrieve Time" },
{ 0x0088, 0x0000, "UL", "Storage Group Length" },
{ 0x0088, 0x0130, "SH", "Storage Media FileSet ID" },
{ 0x0088, 0x0140, "UI", "Storage Media FileSet UID" },
{ 0x0088, 0x0200, "SQ", "Icon Image Sequence" },
{ 0x0088, 0x0904, "LO", "Topic Title" },
{ 0x0088, 0x0906, "ST", "Topic Subject" },
{ 0x0088, 0x0910, "LO", "Topic Author" },
{ 0x0088, 0x0912, "LO", "Topic Key Words" },
{ 0x0095, 0x0001, "LT", "Examination Folder ID" },
{ 0x0095, 0x0004, "UL", "Folder Reported Status" },
{ 0x0095, 0x0005, "LT", "Folder Reporting Radiologist" },
{ 0x0095, 0x0007, "LT", "SIENET ISA PLA" },
{ 0x0099, 0x0002, "UL", "Data Object Attributes" },
{ 0x00e1, 0x0001, "US", "Data Dictionary Version" },
{ 0x00e1, 0x0014, "LT", "?" },
{ 0x00e1, 0x0022, "DS", "?" },
{ 0x00e1, 0x0023, "DS", "?" },
{ 0x00e1, 0x0024, "LT", "?" },
{ 0x00e1, 0x0025, "LT", "?" },
{ 0x00e1, 0x0040, "SH", "Offset From CT MR Images" },
{ 0x0193, 0x0002, "DS", "RIS Key" },
{ 0x0307, 0x0001, "UN", "RIS Worklist IMGEF" },
{ 0x0309, 0x0001, "UN", "RIS Report IMGEF" },
{ 0x0601, 0x0000, "SH", "Implementation Version" },
{ 0x0601, 0x0020, "DS", "Relative Table Position" },
{ 0x0601, 0x0021, "DS", "Relative Table Height" },
{ 0x0601, 0x0030, "SH", "Surview Direction" },
{ 0x0601, 0x0031, "DS", "Surview Length" },
{ 0x0601, 0x0050, "SH", "Image View Type" },
{ 0x0601, 0x0070, "DS", "Batch Number" },
{ 0x0601, 0x0071, "DS", "Batch Size" },
{ 0x0601, 0x0072, "DS", "Batch Slice Number" },
{ 0x1000, 0x0000, "xs", "?" },
{ 0x1000, 0x0001, "US", "Run Length Triplet" },
{ 0x1000, 0x0002, "US", "Huffman Table Size" },
{ 0x1000, 0x0003, "US", "Huffman Table Triplet" },
{ 0x1000, 0x0004, "US", "Shift Table Size" },
{ 0x1000, 0x0005, "US", "Shift Table Triplet" },
{ 0x1010, 0x0000, "xs", "?" },
{ 0x1369, 0x0000, "US", "?" },
{ 0x2000, 0x0000, "UL", "Film Session Group Length" },
{ 0x2000, 0x0010, "IS", "Number of Copies" },
{ 0x2000, 0x0020, "CS", "Print Priority" },
{ 0x2000, 0x0030, "CS", "Medium Type" },
{ 0x2000, 0x0040, "CS", "Film Destination" },
{ 0x2000, 0x0050, "LO", "Film Session Label" },
{ 0x2000, 0x0060, "IS", "Memory Allocation" },
{ 0x2000, 0x0500, "SQ", "Referenced Film Box Sequence" },
{ 0x2010, 0x0000, "UL", "Film Box Group Length" },
{ 0x2010, 0x0010, "ST", "Image Display Format" },
{ 0x2010, 0x0030, "CS", "Annotation Display Format ID" },
{ 0x2010, 0x0040, "CS", "Film Orientation" },
{ 0x2010, 0x0050, "CS", "Film Size ID" },
{ 0x2010, 0x0060, "CS", "Magnification Type" },
{ 0x2010, 0x0080, "CS", "Smoothing Type" },
{ 0x2010, 0x0100, "CS", "Border Density" },
{ 0x2010, 0x0110, "CS", "Empty Image Density" },
{ 0x2010, 0x0120, "US", "Min Density" },
{ 0x2010, 0x0130, "US", "Max Density" },
{ 0x2010, 0x0140, "CS", "Trim" },
{ 0x2010, 0x0150, "ST", "Configuration Information" },
{ 0x2010, 0x0500, "SQ", "Referenced Film Session Sequence" },
{ 0x2010, 0x0510, "SQ", "Referenced Image Box Sequence" },
{ 0x2010, 0x0520, "SQ", "Referenced Basic Annotation Box Sequence" },
{ 0x2020, 0x0000, "UL", "Image Box Group Length" },
{ 0x2020, 0x0010, "US", "Image Box Position" },
{ 0x2020, 0x0020, "CS", "Polarity" },
{ 0x2020, 0x0030, "DS", "Requested Image Size" },
{ 0x2020, 0x0110, "SQ", "Preformatted Grayscale Image Sequence" },
{ 0x2020, 0x0111, "SQ", "Preformatted Color Image Sequence" },
{ 0x2020, 0x0130, "SQ", "Referenced Image Overlay Box Sequence" },
{ 0x2020, 0x0140, "SQ", "Referenced VOI LUT Box Sequence" },
{ 0x2030, 0x0000, "UL", "Annotation Group Length" },
{ 0x2030, 0x0010, "US", "Annotation Position" },
{ 0x2030, 0x0020, "LO", "Text String" },
{ 0x2040, 0x0000, "UL", "Overlay Box Group Length" },
{ 0x2040, 0x0010, "SQ", "Referenced Overlay Plane Sequence" },
{ 0x2040, 0x0011, "US", "Referenced Overlay Plane Groups" },
{ 0x2040, 0x0060, "CS", "Overlay Magnification Type" },
{ 0x2040, 0x0070, "CS", "Overlay Smoothing Type" },
{ 0x2040, 0x0080, "CS", "Overlay Foreground Density" },
{ 0x2040, 0x0090, "CS", "Overlay Mode" },
{ 0x2040, 0x0100, "CS", "Threshold Density" },
{ 0x2040, 0x0500, "SQ", "Referenced Overlay Image Box Sequence" },
{ 0x2050, 0x0010, "SQ", "Presentation LUT Sequence" },
{ 0x2050, 0x0020, "CS", "Presentation LUT Shape" },
{ 0x2100, 0x0000, "UL", "Print Job Group Length" },
{ 0x2100, 0x0020, "CS", "Execution Status" },
{ 0x2100, 0x0030, "CS", "Execution Status Info" },
{ 0x2100, 0x0040, "DA", "Creation Date" },
{ 0x2100, 0x0050, "TM", "Creation Time" },
{ 0x2100, 0x0070, "AE", "Originator" },
{ 0x2100, 0x0500, "SQ", "Referenced Print Job Sequence" },
{ 0x2110, 0x0000, "UL", "Printer Group Length" },
{ 0x2110, 0x0010, "CS", "Printer Status" },
{ 0x2110, 0x0020, "CS", "Printer Status Info" },
{ 0x2110, 0x0030, "LO", "Printer Name" },
{ 0x2110, 0x0099, "SH", "Print Queue ID" },
{ 0x3002, 0x0002, "SH", "RT Image Label" },
{ 0x3002, 0x0003, "LO", "RT Image Name" },
{ 0x3002, 0x0004, "ST", "RT Image Description" },
{ 0x3002, 0x000a, "CS", "Reported Values Origin" },
{ 0x3002, 0x000c, "CS", "RT Image Plane" },
{ 0x3002, 0x000e, "DS", "X-Ray Image Receptor Angle" },
{ 0x3002, 0x0010, "DS", "RTImageOrientation" },
{ 0x3002, 0x0011, "DS", "Image Plane Pixel Spacing" },
{ 0x3002, 0x0012, "DS", "RT Image Position" },
{ 0x3002, 0x0020, "SH", "Radiation Machine Name" },
{ 0x3002, 0x0022, "DS", "Radiation Machine SAD" },
{ 0x3002, 0x0024, "DS", "Radiation Machine SSD" },
{ 0x3002, 0x0026, "DS", "RT Image SID" },
{ 0x3002, 0x0028, "DS", "Source to Reference Object Distance" },
{ 0x3002, 0x0029, "IS", "Fraction Number" },
{ 0x3002, 0x0030, "SQ", "Exposure Sequence" },
{ 0x3002, 0x0032, "DS", "Meterset Exposure" },
{ 0x3004, 0x0001, "CS", "DVH Type" },
{ 0x3004, 0x0002, "CS", "Dose Units" },
{ 0x3004, 0x0004, "CS", "Dose Type" },
{ 0x3004, 0x0006, "LO", "Dose Comment" },
{ 0x3004, 0x0008, "DS", "Normalization Point" },
{ 0x3004, 0x000a, "CS", "Dose Summation Type" },
{ 0x3004, 0x000c, "DS", "GridFrame Offset Vector" },
{ 0x3004, 0x000e, "DS", "Dose Grid Scaling" },
{ 0x3004, 0x0010, "SQ", "RT Dose ROI Sequence" },
{ 0x3004, 0x0012, "DS", "Dose Value" },
{ 0x3004, 0x0040, "DS", "DVH Normalization Point" },
{ 0x3004, 0x0042, "DS", "DVH Normalization Dose Value" },
{ 0x3004, 0x0050, "SQ", "DVH Sequence" },
{ 0x3004, 0x0052, "DS", "DVH Dose Scaling" },
{ 0x3004, 0x0054, "CS", "DVH Volume Units" },
{ 0x3004, 0x0056, "IS", "DVH Number of Bins" },
{ 0x3004, 0x0058, "DS", "DVH Data" },
{ 0x3004, 0x0060, "SQ", "DVH Referenced ROI Sequence" },
{ 0x3004, 0x0062, "CS", "DVH ROI Contribution Type" },
{ 0x3004, 0x0070, "DS", "DVH Minimum Dose" },
{ 0x3004, 0x0072, "DS", "DVH Maximum Dose" },
{ 0x3004, 0x0074, "DS", "DVH Mean Dose" },
{ 0x3006, 0x0002, "SH", "Structure Set Label" },
{ 0x3006, 0x0004, "LO", "Structure Set Name" },
{ 0x3006, 0x0006, "ST", "Structure Set Description" },
{ 0x3006, 0x0008, "DA", "Structure Set Date" },
{ 0x3006, 0x0009, "TM", "Structure Set Time" },
{ 0x3006, 0x0010, "SQ", "Referenced Frame of Reference Sequence" },
{ 0x3006, 0x0012, "SQ", "RT Referenced Study Sequence" },
{ 0x3006, 0x0014, "SQ", "RT Referenced Series Sequence" },
{ 0x3006, 0x0016, "SQ", "Contour Image Sequence" },
{ 0x3006, 0x0020, "SQ", "Structure Set ROI Sequence" },
{ 0x3006, 0x0022, "IS", "ROI Number" },
{ 0x3006, 0x0024, "UI", "Referenced Frame of Reference UID" },
{ 0x3006, 0x0026, "LO", "ROI Name" },
{ 0x3006, 0x0028, "ST", "ROI Description" },
{ 0x3006, 0x002a, "IS", "ROI Display Color" },
{ 0x3006, 0x002c, "DS", "ROI Volume" },
{ 0x3006, 0x0030, "SQ", "RT Related ROI Sequence" },
{ 0x3006, 0x0033, "CS", "RT ROI Relationship" },
{ 0x3006, 0x0036, "CS", "ROI Generation Algorithm" },
{ 0x3006, 0x0038, "LO", "ROI Generation Description" },
{ 0x3006, 0x0039, "SQ", "ROI Contour Sequence" },
{ 0x3006, 0x0040, "SQ", "Contour Sequence" },
{ 0x3006, 0x0042, "CS", "Contour Geometric Type" },
{ 0x3006, 0x0044, "DS", "Contour SlabT hickness" },
{ 0x3006, 0x0045, "DS", "Contour Offset Vector" },
{ 0x3006, 0x0046, "IS", "Number of Contour Points" },
{ 0x3006, 0x0050, "DS", "Contour Data" },
{ 0x3006, 0x0080, "SQ", "RT ROI Observations Sequence" },
{ 0x3006, 0x0082, "IS", "Observation Number" },
{ 0x3006, 0x0084, "IS", "Referenced ROI Number" },
{ 0x3006, 0x0085, "SH", "ROI Observation Label" },
{ 0x3006, 0x0086, "SQ", "RT ROI Identification Code Sequence" },
{ 0x3006, 0x0088, "ST", "ROI Observation Description" },
{ 0x3006, 0x00a0, "SQ", "Related RT ROI Observations Sequence" },
{ 0x3006, 0x00a4, "CS", "RT ROI Interpreted Type" },
{ 0x3006, 0x00a6, "PN", "ROI Interpreter" },
{ 0x3006, 0x00b0, "SQ", "ROI Physical Properties Sequence" },
{ 0x3006, 0x00b2, "CS", "ROI Physical Property" },
{ 0x3006, 0x00b4, "DS", "ROI Physical Property Value" },
{ 0x3006, 0x00c0, "SQ", "Frame of Reference Relationship Sequence" },
{ 0x3006, 0x00c2, "UI", "Related Frame of Reference UID" },
{ 0x3006, 0x00c4, "CS", "Frame of Reference Transformation Type" },
{ 0x3006, 0x00c6, "DS", "Frame of Reference Transformation Matrix" },
{ 0x3006, 0x00c8, "LO", "Frame of Reference Transformation Comment" },
{ 0x300a, 0x0002, "SH", "RT Plan Label" },
{ 0x300a, 0x0003, "LO", "RT Plan Name" },
{ 0x300a, 0x0004, "ST", "RT Plan Description" },
{ 0x300a, 0x0006, "DA", "RT Plan Date" },
{ 0x300a, 0x0007, "TM", "RT Plan Time" },
{ 0x300a, 0x0009, "LO", "Treatment Protocols" },
{ 0x300a, 0x000a, "CS", "Treatment Intent" },
{ 0x300a, 0x000b, "LO", "Treatment Sites" },
{ 0x300a, 0x000c, "CS", "RT Plan Geometry" },
{ 0x300a, 0x000e, "ST", "Prescription Description" },
{ 0x300a, 0x0010, "SQ", "Dose ReferenceSequence" },
{ 0x300a, 0x0012, "IS", "Dose ReferenceNumber" },
{ 0x300a, 0x0014, "CS", "Dose Reference Structure Type" },
{ 0x300a, 0x0016, "LO", "Dose ReferenceDescription" },
{ 0x300a, 0x0018, "DS", "Dose Reference Point Coordinates" },
{ 0x300a, 0x001a, "DS", "Nominal Prior Dose" },
{ 0x300a, 0x0020, "CS", "Dose Reference Type" },
{ 0x300a, 0x0021, "DS", "Constraint Weight" },
{ 0x300a, 0x0022, "DS", "Delivery Warning Dose" },
{ 0x300a, 0x0023, "DS", "Delivery Maximum Dose" },
{ 0x300a, 0x0025, "DS", "Target Minimum Dose" },
{ 0x300a, 0x0026, "DS", "Target Prescription Dose" },
{ 0x300a, 0x0027, "DS", "Target Maximum Dose" },
{ 0x300a, 0x0028, "DS", "Target Underdose Volume Fraction" },
{ 0x300a, 0x002a, "DS", "Organ at Risk Full-volume Dose" },
{ 0x300a, 0x002b, "DS", "Organ at Risk Limit Dose" },
{ 0x300a, 0x002c, "DS", "Organ at Risk Maximum Dose" },
{ 0x300a, 0x002d, "DS", "Organ at Risk Overdose Volume Fraction" },
{ 0x300a, 0x0040, "SQ", "Tolerance Table Sequence" },
{ 0x300a, 0x0042, "IS", "Tolerance Table Number" },
{ 0x300a, 0x0043, "SH", "Tolerance Table Label" },
{ 0x300a, 0x0044, "DS", "Gantry Angle Tolerance" },
{ 0x300a, 0x0046, "DS", "Beam Limiting Device Angle Tolerance" },
{ 0x300a, 0x0048, "SQ", "Beam Limiting Device Tolerance Sequence" },
{ 0x300a, 0x004a, "DS", "Beam Limiting Device Position Tolerance" },
{ 0x300a, 0x004c, "DS", "Patient Support Angle Tolerance" },
{ 0x300a, 0x004e, "DS", "Table Top Eccentric Angle Tolerance" },
{ 0x300a, 0x0051, "DS", "Table Top Vertical Position Tolerance" },
{ 0x300a, 0x0052, "DS", "Table Top Longitudinal Position Tolerance" },
{ 0x300a, 0x0053, "DS", "Table Top Lateral Position Tolerance" },
{ 0x300a, 0x0055, "CS", "RT Plan Relationship" },
{ 0x300a, 0x0070, "SQ", "Fraction Group Sequence" },
{ 0x300a, 0x0071, "IS", "Fraction Group Number" },
{ 0x300a, 0x0078, "IS", "Number of Fractions Planned" },
{ 0x300a, 0x0079, "IS", "Number of Fractions Per Day" },
{ 0x300a, 0x007a, "IS", "Repeat Fraction Cycle Length" },
{ 0x300a, 0x007b, "LT", "Fraction Pattern" },
{ 0x300a, 0x0080, "IS", "Number of Beams" },
{ 0x300a, 0x0082, "DS", "Beam Dose Specification Point" },
{ 0x300a, 0x0084, "DS", "Beam Dose" },
{ 0x300a, 0x0086, "DS", "Beam Meterset" },
{ 0x300a, 0x00a0, "IS", "Number of Brachy Application Setups" },
{ 0x300a, 0x00a2, "DS", "Brachy Application Setup Dose Specification Point" },
{ 0x300a, 0x00a4, "DS", "Brachy Application Setup Dose" },
{ 0x300a, 0x00b0, "SQ", "Beam Sequence" },
{ 0x300a, 0x00b2, "SH", "Treatment Machine Name " },
{ 0x300a, 0x00b3, "CS", "Primary Dosimeter Unit" },
{ 0x300a, 0x00b4, "DS", "Source-Axis Distance" },
{ 0x300a, 0x00b6, "SQ", "Beam Limiting Device Sequence" },
{ 0x300a, 0x00b8, "CS", "RT Beam Limiting Device Type" },
{ 0x300a, 0x00ba, "DS", "Source to Beam Limiting Device Distance" },
{ 0x300a, 0x00bc, "IS", "Number of Leaf/Jaw Pairs" },
{ 0x300a, 0x00be, "DS", "Leaf Position Boundaries" },
{ 0x300a, 0x00c0, "IS", "Beam Number" },
{ 0x300a, 0x00c2, "LO", "Beam Name" },
{ 0x300a, 0x00c3, "ST", "Beam Description" },
{ 0x300a, 0x00c4, "CS", "Beam Type" },
{ 0x300a, 0x00c6, "CS", "Radiation Type" },
{ 0x300a, 0x00c8, "IS", "Reference Image Number" },
{ 0x300a, 0x00ca, "SQ", "Planned Verification Image Sequence" },
{ 0x300a, 0x00cc, "LO", "Imaging Device Specific Acquisition Parameters" },
{ 0x300a, 0x00ce, "CS", "Treatment Delivery Type" },
{ 0x300a, 0x00d0, "IS", "Number of Wedges" },
{ 0x300a, 0x00d1, "SQ", "Wedge Sequence" },
{ 0x300a, 0x00d2, "IS", "Wedge Number" },
{ 0x300a, 0x00d3, "CS", "Wedge Type" },
{ 0x300a, 0x00d4, "SH", "Wedge ID" },
{ 0x300a, 0x00d5, "IS", "Wedge Angle" },
{ 0x300a, 0x00d6, "DS", "Wedge Factor" },
{ 0x300a, 0x00d8, "DS", "Wedge Orientation" },
{ 0x300a, 0x00da, "DS", "Source to Wedge Tray Distance" },
{ 0x300a, 0x00e0, "IS", "Number of Compensators" },
{ 0x300a, 0x00e1, "SH", "Material ID" },
{ 0x300a, 0x00e2, "DS", "Total Compensator Tray Factor" },
{ 0x300a, 0x00e3, "SQ", "Compensator Sequence" },
{ 0x300a, 0x00e4, "IS", "Compensator Number" },
{ 0x300a, 0x00e5, "SH", "Compensator ID" },
{ 0x300a, 0x00e6, "DS", "Source to Compensator Tray Distance" },
{ 0x300a, 0x00e7, "IS", "Compensator Rows" },
{ 0x300a, 0x00e8, "IS", "Compensator Columns" },
{ 0x300a, 0x00e9, "DS", "Compensator Pixel Spacing" },
{ 0x300a, 0x00ea, "DS", "Compensator Position" },
{ 0x300a, 0x00eb, "DS", "Compensator Transmission Data" },
{ 0x300a, 0x00ec, "DS", "Compensator Thickness Data" },
{ 0x300a, 0x00ed, "IS", "Number of Boli" },
{ 0x300a, 0x00f0, "IS", "Number of Blocks" },
{ 0x300a, 0x00f2, "DS", "Total Block Tray Factor" },
{ 0x300a, 0x00f4, "SQ", "Block Sequence" },
{ 0x300a, 0x00f5, "SH", "Block Tray ID" },
{ 0x300a, 0x00f6, "DS", "Source to Block Tray Distance" },
{ 0x300a, 0x00f8, "CS", "Block Type" },
{ 0x300a, 0x00fa, "CS", "Block Divergence" },
{ 0x300a, 0x00fc, "IS", "Block Number" },
{ 0x300a, 0x00fe, "LO", "Block Name" },
{ 0x300a, 0x0100, "DS", "Block Thickness" },
{ 0x300a, 0x0102, "DS", "Block Transmission" },
{ 0x300a, 0x0104, "IS", "Block Number of Points" },
{ 0x300a, 0x0106, "DS", "Block Data" },
{ 0x300a, 0x0107, "SQ", "Applicator Sequence" },
{ 0x300a, 0x0108, "SH", "Applicator ID" },
{ 0x300a, 0x0109, "CS", "Applicator Type" },
{ 0x300a, 0x010a, "LO", "Applicator Description" },
{ 0x300a, 0x010c, "DS", "Cumulative Dose Reference Coefficient" },
{ 0x300a, 0x010e, "DS", "Final Cumulative Meterset Weight" },
{ 0x300a, 0x0110, "IS", "Number of Control Points" },
{ 0x300a, 0x0111, "SQ", "Control Point Sequence" },
{ 0x300a, 0x0112, "IS", "Control Point Index" },
{ 0x300a, 0x0114, "DS", "Nominal Beam Energy" },
{ 0x300a, 0x0115, "DS", "Dose Rate Set" },
{ 0x300a, 0x0116, "SQ", "Wedge Position Sequence" },
{ 0x300a, 0x0118, "CS", "Wedge Position" },
{ 0x300a, 0x011a, "SQ", "Beam Limiting Device Position Sequence" },
{ 0x300a, 0x011c, "DS", "Leaf Jaw Positions" },
{ 0x300a, 0x011e, "DS", "Gantry Angle" },
{ 0x300a, 0x011f, "CS", "Gantry Rotation Direction" },
{ 0x300a, 0x0120, "DS", "Beam Limiting Device Angle" },
{ 0x300a, 0x0121, "CS", "Beam Limiting Device Rotation Direction" },
{ 0x300a, 0x0122, "DS", "Patient Support Angle" },
{ 0x300a, 0x0123, "CS", "Patient Support Rotation Direction" },
{ 0x300a, 0x0124, "DS", "Table Top Eccentric Axis Distance" },
{ 0x300a, 0x0125, "DS", "Table Top Eccentric Angle" },
{ 0x300a, 0x0126, "CS", "Table Top Eccentric Rotation Direction" },
{ 0x300a, 0x0128, "DS", "Table Top Vertical Position" },
{ 0x300a, 0x0129, "DS", "Table Top Longitudinal Position" },
{ 0x300a, 0x012a, "DS", "Table Top Lateral Position" },
{ 0x300a, 0x012c, "DS", "Isocenter Position" },
{ 0x300a, 0x012e, "DS", "Surface Entry Point" },
{ 0x300a, 0x0130, "DS", "Source to Surface Distance" },
{ 0x300a, 0x0134, "DS", "Cumulative Meterset Weight" },
{ 0x300a, 0x0180, "SQ", "Patient Setup Sequence" },
{ 0x300a, 0x0182, "IS", "Patient Setup Number" },
{ 0x300a, 0x0184, "LO", "Patient Additional Position" },
{ 0x300a, 0x0190, "SQ", "Fixation Device Sequence" },
{ 0x300a, 0x0192, "CS", "Fixation Device Type" },
{ 0x300a, 0x0194, "SH", "Fixation Device Label" },
{ 0x300a, 0x0196, "ST", "Fixation Device Description" },
{ 0x300a, 0x0198, "SH", "Fixation Device Position" },
{ 0x300a, 0x01a0, "SQ", "Shielding Device Sequence" },
{ 0x300a, 0x01a2, "CS", "Shielding Device Type" },
{ 0x300a, 0x01a4, "SH", "Shielding Device Label" },
{ 0x300a, 0x01a6, "ST", "Shielding Device Description" },
{ 0x300a, 0x01a8, "SH", "Shielding Device Position" },
{ 0x300a, 0x01b0, "CS", "Setup Technique" },
{ 0x300a, 0x01b2, "ST", "Setup TechniqueDescription" },
{ 0x300a, 0x01b4, "SQ", "Setup Device Sequence" },
{ 0x300a, 0x01b6, "CS", "Setup Device Type" },
{ 0x300a, 0x01b8, "SH", "Setup Device Label" },
{ 0x300a, 0x01ba, "ST", "Setup Device Description" },
{ 0x300a, 0x01bc, "DS", "Setup Device Parameter" },
{ 0x300a, 0x01d0, "ST", "Setup ReferenceDescription" },
{ 0x300a, 0x01d2, "DS", "Table Top Vertical Setup Displacement" },
{ 0x300a, 0x01d4, "DS", "Table Top Longitudinal Setup Displacement" },
{ 0x300a, 0x01d6, "DS", "Table Top Lateral Setup Displacement" },
{ 0x300a, 0x0200, "CS", "Brachy Treatment Technique" },
{ 0x300a, 0x0202, "CS", "Brachy Treatment Type" },
{ 0x300a, 0x0206, "SQ", "Treatment Machine Sequence" },
{ 0x300a, 0x0210, "SQ", "Source Sequence" },
{ 0x300a, 0x0212, "IS", "Source Number" },
{ 0x300a, 0x0214, "CS", "Source Type" },
{ 0x300a, 0x0216, "LO", "Source Manufacturer" },
{ 0x300a, 0x0218, "DS", "Active Source Diameter" },
{ 0x300a, 0x021a, "DS", "Active Source Length" },
{ 0x300a, 0x0222, "DS", "Source Encapsulation Nominal Thickness" },
{ 0x300a, 0x0224, "DS", "Source Encapsulation Nominal Transmission" },
{ 0x300a, 0x0226, "LO", "Source IsotopeName" },
{ 0x300a, 0x0228, "DS", "Source Isotope Half Life" },
{ 0x300a, 0x022a, "DS", "Reference Air Kerma Rate" },
{ 0x300a, 0x022c, "DA", "Air Kerma Rate Reference Date" },
{ 0x300a, 0x022e, "TM", "Air Kerma Rate Reference Time" },
{ 0x300a, 0x0230, "SQ", "Application Setup Sequence" },
{ 0x300a, 0x0232, "CS", "Application Setup Type" },
{ 0x300a, 0x0234, "IS", "Application Setup Number" },
{ 0x300a, 0x0236, "LO", "Application Setup Name" },
{ 0x300a, 0x0238, "LO", "Application Setup Manufacturer" },
{ 0x300a, 0x0240, "IS", "Template Number" },
{ 0x300a, 0x0242, "SH", "Template Type" },
{ 0x300a, 0x0244, "LO", "Template Name" },
{ 0x300a, 0x0250, "DS", "Total Reference Air Kerma" },
{ 0x300a, 0x0260, "SQ", "Brachy Accessory Device Sequence" },
{ 0x300a, 0x0262, "IS", "Brachy Accessory Device Number" },
{ 0x300a, 0x0263, "SH", "Brachy Accessory Device ID" },
{ 0x300a, 0x0264, "CS", "Brachy Accessory Device Type" },
{ 0x300a, 0x0266, "LO", "Brachy Accessory Device Name" },
{ 0x300a, 0x026a, "DS", "Brachy Accessory Device Nominal Thickness" },
{ 0x300a, 0x026c, "DS", "Brachy Accessory Device Nominal Transmission" },
{ 0x300a, 0x0280, "SQ", "Channel Sequence" },
{ 0x300a, 0x0282, "IS", "Channel Number" },
{ 0x300a, 0x0284, "DS", "Channel Length" },
{ 0x300a, 0x0286, "DS", "Channel Total Time" },
{ 0x300a, 0x0288, "CS", "Source Movement Type" },
{ 0x300a, 0x028a, "IS", "Number of Pulses" },
{ 0x300a, 0x028c, "DS", "Pulse Repetition Interval" },
{ 0x300a, 0x0290, "IS", "Source Applicator Number" },
{ 0x300a, 0x0291, "SH", "Source Applicator ID" },
{ 0x300a, 0x0292, "CS", "Source Applicator Type" },
{ 0x300a, 0x0294, "LO", "Source Applicator Name" },
{ 0x300a, 0x0296, "DS", "Source Applicator Length" },
{ 0x300a, 0x0298, "LO", "Source Applicator Manufacturer" },
{ 0x300a, 0x029c, "DS", "Source Applicator Wall Nominal Thickness" },
{ 0x300a, 0x029e, "DS", "Source Applicator Wall Nominal Transmission" },
{ 0x300a, 0x02a0, "DS", "Source Applicator Step Size" },
{ 0x300a, 0x02a2, "IS", "Transfer Tube Number" },
{ 0x300a, 0x02a4, "DS", "Transfer Tube Length" },
{ 0x300a, 0x02b0, "SQ", "Channel Shield Sequence" },
{ 0x300a, 0x02b2, "IS", "Channel Shield Number" },
{ 0x300a, 0x02b3, "SH", "Channel Shield ID" },
{ 0x300a, 0x02b4, "LO", "Channel Shield Name" },
{ 0x300a, 0x02b8, "DS", "Channel Shield Nominal Thickness" },
{ 0x300a, 0x02ba, "DS", "Channel Shield Nominal Transmission" },
{ 0x300a, 0x02c8, "DS", "Final Cumulative Time Weight" },
{ 0x300a, 0x02d0, "SQ", "Brachy Control Point Sequence" },
{ 0x300a, 0x02d2, "DS", "Control Point Relative Position" },
{ 0x300a, 0x02d4, "DS", "Control Point 3D Position" },
{ 0x300a, 0x02d6, "DS", "Cumulative Time Weight" },
{ 0x300c, 0x0002, "SQ", "Referenced RT Plan Sequence" },
{ 0x300c, 0x0004, "SQ", "Referenced Beam Sequence" },
{ 0x300c, 0x0006, "IS", "Referenced Beam Number" },
{ 0x300c, 0x0007, "IS", "Referenced Reference Image Number" },
{ 0x300c, 0x0008, "DS", "Start Cumulative Meterset Weight" },
{ 0x300c, 0x0009, "DS", "End Cumulative Meterset Weight" },
{ 0x300c, 0x000a, "SQ", "Referenced Brachy Application Setup Sequence" },
{ 0x300c, 0x000c, "IS", "Referenced Brachy Application Setup Number" },
{ 0x300c, 0x000e, "IS", "Referenced Source Number" },
{ 0x300c, 0x0020, "SQ", "Referenced Fraction Group Sequence" },
{ 0x300c, 0x0022, "IS", "Referenced Fraction Group Number" },
{ 0x300c, 0x0040, "SQ", "Referenced Verification Image Sequence" },
{ 0x300c, 0x0042, "SQ", "Referenced Reference Image Sequence" },
{ 0x300c, 0x0050, "SQ", "Referenced Dose Reference Sequence" },
{ 0x300c, 0x0051, "IS", "Referenced Dose Reference Number" },
{ 0x300c, 0x0055, "SQ", "Brachy Referenced Dose Reference Sequence" },
{ 0x300c, 0x0060, "SQ", "Referenced Structure Set Sequence" },
{ 0x300c, 0x006a, "IS", "Referenced Patient Setup Number" },
{ 0x300c, 0x0080, "SQ", "Referenced Dose Sequence" },
{ 0x300c, 0x00a0, "IS", "Referenced Tolerance Table Number" },
{ 0x300c, 0x00b0, "SQ", "Referenced Bolus Sequence" },
{ 0x300c, 0x00c0, "IS", "Referenced Wedge Number" },
{ 0x300c, 0x00d0, "IS", "Referenced Compensato rNumber" },
{ 0x300c, 0x00e0, "IS", "Referenced Block Number" },
{ 0x300c, 0x00f0, "IS", "Referenced Control Point" },
{ 0x300e, 0x0002, "CS", "Approval Status" },
{ 0x300e, 0x0004, "DA", "Review Date" },
{ 0x300e, 0x0005, "TM", "Review Time" },
{ 0x300e, 0x0008, "PN", "Reviewer Name" },
{ 0x4000, 0x0000, "UL", "Text Group Length" },
{ 0x4000, 0x0010, "LT", "Text Arbitrary" },
{ 0x4000, 0x4000, "LT", "Text Comments" },
{ 0x4008, 0x0000, "UL", "Results Group Length" },
{ 0x4008, 0x0040, "SH", "Results ID" },
{ 0x4008, 0x0042, "LO", "Results ID Issuer" },
{ 0x4008, 0x0050, "SQ", "Referenced Interpretation Sequence" },
{ 0x4008, 0x00ff, "CS", "Report Production Status" },
{ 0x4008, 0x0100, "DA", "Interpretation Recorded Date" },
{ 0x4008, 0x0101, "TM", "Interpretation Recorded Time" },
{ 0x4008, 0x0102, "PN", "Interpretation Recorder" },
{ 0x4008, 0x0103, "LO", "Reference to Recorded Sound" },
{ 0x4008, 0x0108, "DA", "Interpretation Transcription Date" },
{ 0x4008, 0x0109, "TM", "Interpretation Transcription Time" },
{ 0x4008, 0x010a, "PN", "Interpretation Transcriber" },
{ 0x4008, 0x010b, "ST", "Interpretation Text" },
{ 0x4008, 0x010c, "PN", "Interpretation Author" },
{ 0x4008, 0x0111, "SQ", "Interpretation Approver Sequence" },
{ 0x4008, 0x0112, "DA", "Interpretation Approval Date" },
{ 0x4008, 0x0113, "TM", "Interpretation Approval Time" },
{ 0x4008, 0x0114, "PN", "Physician Approving Interpretation" },
{ 0x4008, 0x0115, "LT", "Interpretation Diagnosis Description" },
{ 0x4008, 0x0117, "SQ", "InterpretationDiagnosis Code Sequence" },
{ 0x4008, 0x0118, "SQ", "Results Distribution List Sequence" },
{ 0x4008, 0x0119, "PN", "Distribution Name" },
{ 0x4008, 0x011a, "LO", "Distribution Address" },
{ 0x4008, 0x0200, "SH", "Interpretation ID" },
{ 0x4008, 0x0202, "LO", "Interpretation ID Issuer" },
{ 0x4008, 0x0210, "CS", "Interpretation Type ID" },
{ 0x4008, 0x0212, "CS", "Interpretation Status ID" },
{ 0x4008, 0x0300, "ST", "Impressions" },
{ 0x4008, 0x4000, "ST", "Results Comments" },
{ 0x4009, 0x0001, "LT", "Report ID" },
{ 0x4009, 0x0020, "LT", "Report Status" },
{ 0x4009, 0x0030, "DA", "Report Creation Date" },
{ 0x4009, 0x0070, "LT", "Report Approving Physician" },
{ 0x4009, 0x00e0, "LT", "Report Text" },
{ 0x4009, 0x00e1, "LT", "Report Author" },
{ 0x4009, 0x00e3, "LT", "Reporting Radiologist" },
{ 0x5000, 0x0000, "UL", "Curve Group Length" },
{ 0x5000, 0x0005, "US", "Curve Dimensions" },
{ 0x5000, 0x0010, "US", "Number of Points" },
{ 0x5000, 0x0020, "CS", "Type of Data" },
{ 0x5000, 0x0022, "LO", "Curve Description" },
{ 0x5000, 0x0030, "SH", "Axis Units" },
{ 0x5000, 0x0040, "SH", "Axis Labels" },
{ 0x5000, 0x0103, "US", "Data Value Representation" },
{ 0x5000, 0x0104, "US", "Minimum Coordinate Value" },
{ 0x5000, 0x0105, "US", "Maximum Coordinate Value" },
{ 0x5000, 0x0106, "SH", "Curve Range" },
{ 0x5000, 0x0110, "US", "Curve Data Descriptor" },
{ 0x5000, 0x0112, "US", "Coordinate Start Value" },
{ 0x5000, 0x0114, "US", "Coordinate Step Value" },
{ 0x5000, 0x1001, "CS", "Curve Activation Layer" },
{ 0x5000, 0x2000, "US", "Audio Type" },
{ 0x5000, 0x2002, "US", "Audio Sample Format" },
{ 0x5000, 0x2004, "US", "Number of Channels" },
{ 0x5000, 0x2006, "UL", "Number of Samples" },
{ 0x5000, 0x2008, "UL", "Sample Rate" },
{ 0x5000, 0x200a, "UL", "Total Time" },
{ 0x5000, 0x200c, "xs", "Audio Sample Data" },
{ 0x5000, 0x200e, "LT", "Audio Comments" },
{ 0x5000, 0x2500, "LO", "Curve Label" },
{ 0x5000, 0x2600, "SQ", "CurveReferenced Overlay Sequence" },
{ 0x5000, 0x2610, "US", "CurveReferenced Overlay Group" },
{ 0x5000, 0x3000, "OW", "Curve Data" },
{ 0x6000, 0x0000, "UL", "Overlay Group Length" },
{ 0x6000, 0x0001, "US", "Gray Palette Color Lookup Table Descriptor" },
{ 0x6000, 0x0002, "US", "Gray Palette Color Lookup Table Data" },
{ 0x6000, 0x0010, "US", "Overlay Rows" },
{ 0x6000, 0x0011, "US", "Overlay Columns" },
{ 0x6000, 0x0012, "US", "Overlay Planes" },
{ 0x6000, 0x0015, "IS", "Number of Frames in Overlay" },
{ 0x6000, 0x0022, "LO", "Overlay Description" },
{ 0x6000, 0x0040, "CS", "Overlay Type" },
{ 0x6000, 0x0045, "CS", "Overlay Subtype" },
{ 0x6000, 0x0050, "SS", "Overlay Origin" },
{ 0x6000, 0x0051, "US", "Image Frame Origin" },
{ 0x6000, 0x0052, "US", "Plane Origin" },
{ 0x6000, 0x0060, "LO", "Overlay Compression Code" },
{ 0x6000, 0x0061, "SH", "Overlay Compression Originator" },
{ 0x6000, 0x0062, "SH", "Overlay Compression Label" },
{ 0x6000, 0x0063, "SH", "Overlay Compression Description" },
{ 0x6000, 0x0066, "AT", "Overlay Compression Step Pointers" },
{ 0x6000, 0x0068, "US", "Overlay Repeat Interval" },
{ 0x6000, 0x0069, "US", "Overlay Bits Grouped" },
{ 0x6000, 0x0100, "US", "Overlay Bits Allocated" },
{ 0x6000, 0x0102, "US", "Overlay Bit Position" },
{ 0x6000, 0x0110, "LO", "Overlay Format" },
{ 0x6000, 0x0200, "xs", "Overlay Location" },
{ 0x6000, 0x0800, "LO", "Overlay Code Label" },
{ 0x6000, 0x0802, "US", "Overlay Number of Tables" },
{ 0x6000, 0x0803, "AT", "Overlay Code Table Location" },
{ 0x6000, 0x0804, "US", "Overlay Bits For Code Word" },
{ 0x6000, 0x1001, "CS", "Overlay Activation Layer" },
{ 0x6000, 0x1100, "US", "Overlay Descriptor - Gray" },
{ 0x6000, 0x1101, "US", "Overlay Descriptor - Red" },
{ 0x6000, 0x1102, "US", "Overlay Descriptor - Green" },
{ 0x6000, 0x1103, "US", "Overlay Descriptor - Blue" },
{ 0x6000, 0x1200, "US", "Overlays - Gray" },
{ 0x6000, 0x1201, "US", "Overlays - Red" },
{ 0x6000, 0x1202, "US", "Overlays - Green" },
{ 0x6000, 0x1203, "US", "Overlays - Blue" },
{ 0x6000, 0x1301, "IS", "ROI Area" },
{ 0x6000, 0x1302, "DS", "ROI Mean" },
{ 0x6000, 0x1303, "DS", "ROI Standard Deviation" },
{ 0x6000, 0x1500, "LO", "Overlay Label" },
{ 0x6000, 0x3000, "OW", "Overlay Data" },
{ 0x6000, 0x4000, "LT", "Overlay Comments" },
{ 0x6001, 0x0000, "UN", "?" },
{ 0x6001, 0x0010, "LO", "?" },
{ 0x6001, 0x1010, "xs", "?" },
{ 0x6001, 0x1030, "xs", "?" },
{ 0x6021, 0x0000, "xs", "?" },
{ 0x6021, 0x0010, "xs", "?" },
{ 0x7001, 0x0010, "LT", "Dummy" },
{ 0x7003, 0x0010, "LT", "Info" },
{ 0x7005, 0x0010, "LT", "Dummy" },
{ 0x7000, 0x0004, "ST", "TextAnnotation" },
{ 0x7000, 0x0005, "IS", "Box" },
{ 0x7000, 0x0007, "IS", "ArrowEnd" },
{ 0x7fe0, 0x0000, "UL", "Pixel Data Group Length" },
{ 0x7fe0, 0x0010, "xs", "Pixel Data" },
{ 0x7fe0, 0x0020, "OW", "Coefficients SDVN" },
{ 0x7fe0, 0x0030, "OW", "Coefficients SDHN" },
{ 0x7fe0, 0x0040, "OW", "Coefficients SDDN" },
{ 0x7fe1, 0x0010, "xs", "Pixel Data" },
{ 0x7f00, 0x0000, "UL", "Variable Pixel Data Group Length" },
{ 0x7f00, 0x0010, "xs", "Variable Pixel Data" },
{ 0x7f00, 0x0011, "US", "Variable Next Data Group" },
{ 0x7f00, 0x0020, "OW", "Variable Coefficients SDVN" },
{ 0x7f00, 0x0030, "OW", "Variable Coefficients SDHN" },
{ 0x7f00, 0x0040, "OW", "Variable Coefficients SDDN" },
{ 0x7fe1, 0x0000, "OB", "Binary Data" },
{ 0x7fe3, 0x0000, "LT", "Image Graphics Format Code" },
{ 0x7fe3, 0x0010, "OB", "Image Graphics" },
{ 0x7fe3, 0x0020, "OB", "Image Graphics Dummy" },
{ 0x7ff1, 0x0001, "US", "?" },
{ 0x7ff1, 0x0002, "US", "?" },
{ 0x7ff1, 0x0003, "xs", "?" },
{ 0x7ff1, 0x0004, "IS", "?" },
{ 0x7ff1, 0x0005, "US", "?" },
{ 0x7ff1, 0x0007, "US", "?" },
{ 0x7ff1, 0x0008, "US", "?" },
{ 0x7ff1, 0x0009, "US", "?" },
{ 0x7ff1, 0x000a, "LT", "?" },
{ 0x7ff1, 0x000b, "US", "?" },
{ 0x7ff1, 0x000c, "US", "?" },
{ 0x7ff1, 0x000d, "US", "?" },
{ 0x7ff1, 0x0010, "US", "?" },
{ 0xfffc, 0xfffc, "OB", "Data Set Trailing Padding" },
{ 0xfffe, 0xe000, "!!", "Item" },
{ 0xfffe, 0xe00d, "!!", "Item Delimitation Item" },
{ 0xfffe, 0xe0dd, "!!", "Sequence Delimitation Item" },
{ 0xffff, 0xffff, "xs", (char *) NULL }
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D C M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDCM() returns MagickTrue if the image format type, identified by the
% magick string, is DCM.
%
% The format of the ReadDCMImage method is:
%
% MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
{
if (length < 132)
return(MagickFalse);
if (LocaleNCompare((char *) (magick+128),"DICM",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDCMImage() reads a Digital Imaging and Communications in Medicine
% (DICOM) file and returns it. It allocates the memory necessary for the
% new Image structure and returns a pointer to the new image.
%
% The format of the ReadDCMImage method is:
%
% Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _DCMInfo
{
MagickBooleanType
polarity;
Quantum
*scale;
size_t
bits_allocated,
bytes_per_pixel,
depth,
mask,
max_value,
samples_per_pixel,
signed_data,
significant_bits;
MagickBooleanType
rescale;
double
rescale_intercept,
rescale_slope,
window_center,
window_width;
} DCMInfo;
typedef struct _DCMStreamInfo
{
size_t
remaining,
segment_count;
ssize_t
segments[15];
size_t
offset_count;
ssize_t
*offsets;
ssize_t
count;
int
byte;
} DCMStreamInfo;
static int ReadDCMByte(DCMStreamInfo *stream_info,Image *image)
{
if (image->compression != RLECompression)
return(ReadBlobByte(image));
if (stream_info->count == 0)
{
int
byte;
ssize_t
count;
if (stream_info->remaining <= 2)
stream_info->remaining=0;
else
stream_info->remaining-=2;
count=(ssize_t) ReadBlobByte(image);
byte=ReadBlobByte(image);
if (count == 128)
return(0);
else
if (count < 128)
{
/*
Literal bytes.
*/
stream_info->count=count;
stream_info->byte=(-1);
return(byte);
}
else
{
/*
Repeated bytes.
*/
stream_info->count=256-count;
stream_info->byte=byte;
return(byte);
}
}
stream_info->count--;
if (stream_info->byte >= 0)
return(stream_info->byte);
if (stream_info->remaining > 0)
stream_info->remaining--;
return(ReadBlobByte(image));
}
static unsigned short ReadDCMShort(DCMStreamInfo *stream_info,Image *image)
{
int
shift;
unsigned short
value;
if (image->compression != RLECompression)
return(ReadBlobLSBShort(image));
shift=image->depth < 16 ? 4 : 8;
value=ReadDCMByte(stream_info,image) | (unsigned short)
(ReadDCMByte(stream_info,image) << shift);
return(value);
}
static signed short ReadDCMSignedShort(DCMStreamInfo *stream_info,Image *image)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
quantum.unsigned_value=ReadDCMShort(stream_info,image);
return(quantum.signed_value);
}
static MagickBooleanType ReadDCMPixels(Image *image,DCMInfo *info,
DCMStreamInfo *stream_info,MagickBooleanType first_segment,
ExceptionInfo *exception)
{
int
byte,
index;
MagickBooleanType
status;
LongPixelPacket
pixel;
register ssize_t
i,
x;
register IndexPacket
*indexes;
register PixelPacket
*q;
ssize_t
y;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (info->samples_per_pixel == 1)
{
int
pixel_value;
if (info->bytes_per_pixel == 1)
pixel_value=info->polarity != MagickFalse ? ((int) info->max_value-
ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((info->bits_allocated != 12) || (info->significant_bits != 12))
{
if (info->signed_data)
pixel_value=ReadDCMSignedShort(stream_info,image);
else
pixel_value=(int) ReadDCMShort(stream_info,image);
if (info->polarity != MagickFalse)
pixel_value=(int) info->max_value-pixel_value;
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMSignedShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
if (info->signed_data == 1)
pixel_value-=32767;
if (info->rescale)
{
double
scaled_value;
scaled_value=pixel_value*info->rescale_slope+
info->rescale_intercept;
if (info->window_width == 0)
{
index=(int) scaled_value;
}
else
{
double
window_max,
window_min;
window_min=ceil(info->window_center-
(info->window_width-1.0)/2.0-0.5);
window_max=floor(info->window_center+
(info->window_width-1.0)/2.0+0.5);
if (scaled_value <= window_min)
index=0;
else
if (scaled_value > window_max)
index=(int) info->max_value;
else
index=(int) (info->max_value*(((scaled_value-
info->window_center-0.5)/(info->window_width-1))+0.5));
}
}
else
{
index=pixel_value;
}
index&=info->mask;
index=(int) ConstrainColormapIndex(image,(size_t) index);
if (first_segment != MagickFalse)
SetPixelIndex(indexes+x,index);
else
SetPixelIndex(indexes+x,(((size_t) index) |
(((size_t) GetPixelIndex(indexes+x)) << 8)));
pixel.red=1U*image->colormap[index].red;
pixel.green=1U*image->colormap[index].green;
pixel.blue=1U*image->colormap[index].blue;
}
else
{
if (info->bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=info->mask;
pixel.green&=info->mask;
pixel.blue&=info->mask;
if (info->scale != (Quantum *) NULL)
{
if ((MagickSizeType) pixel.red <= GetQuantumRange(info->depth))
pixel.red=info->scale[pixel.red];
if ((MagickSizeType) pixel.green <= GetQuantumRange(info->depth))
pixel.green=info->scale[pixel.green];
if ((MagickSizeType) pixel.blue <= GetQuantumRange(info->depth))
pixel.blue=info->scale[pixel.blue];
}
}
if (first_segment != MagickFalse)
{
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
}
else
{
SetPixelRed(q,(((size_t) pixel.red) |
(((size_t) GetPixelRed(q)) << 8)));
SetPixelGreen(q,(((size_t) pixel.green) |
(((size_t) GetPixelGreen(q)) << 8)));
SetPixelBlue(q,(((size_t) pixel.blue) |
(((size_t) GetPixelBlue(q)) << 8)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
return(status);
}
static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowDCMException(exception,message) \
{ \
if (data != (unsigned char *) NULL) \
data=(unsigned char *) RelinquishMagickMemory(data); \
if (stream_info != (DCMStreamInfo *) NULL) \
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \
ThrowReaderException((exception),(message)); \
}
char
explicit_vr[MaxTextExtent],
implicit_vr[MaxTextExtent],
magick[MaxTextExtent],
photometric[MaxTextExtent];
DCMInfo
info;
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
sequence,
use_explicit;
MagickOffsetType
offset;
register unsigned char
*p;
register ssize_t
i;
size_t
colors,
height,
length,
number_scenes,
quantum,
status,
width;
ssize_t
count,
scene;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
data=(unsigned char *) NULL;
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent);
info.polarity=MagickFalse;
info.scale=(Quantum *) NULL;
info.bits_allocated=8;
info.bytes_per_pixel=1;
info.depth=8;
info.mask=0xffff;
info.max_value=255UL;
info.samples_per_pixel=1;
info.signed_data=(~0UL);
info.significant_bits=0;
info.rescale=MagickFalse;
info.rescale_intercept=0.0;
info.rescale_slope=1.0;
info.window_center=0.0;
info.window_width=0.0;
data=(unsigned char *) NULL;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
number_scenes=1;
sequence=MagickFalse;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"UL",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"FL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (length > GetBlobSize(image))
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MaxTextExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MaxTextExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
count,
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
if (count < 1)
ThrowDCMException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
info.samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
if (data == (unsigned char *) NULL)
break;
for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
if (data == (unsigned char *) NULL)
break;
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
info.bits_allocated=(size_t) datum;
info.bytes_per_pixel=1;
if (datum > 8)
info.bytes_per_pixel=2;
info.depth=info.bits_allocated;
if (info.depth > 32)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.bits_allocated)-1;
image->depth=info.depth;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
info.significant_bits=(size_t) datum;
info.bytes_per_pixel=1;
if (info.significant_bits > 8)
info.bytes_per_pixel=2;
info.depth=info.significant_bits;
if (info.depth > 32)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.significant_bits)-1;
info.mask=(size_t) GetQuantumRange(info.significant_bits);
image->depth=info.depth;
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
info.signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
info.window_center=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
info.window_width=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
info.rescale_intercept=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
info.rescale_slope=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/info.bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (info.bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
info.polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (info.signed_data == 0xffff)
info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MaxTextExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s",
filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property));
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(info.depth)+1);
info.scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*info.scale));
if (info.scale == (Quantum *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(info.depth);
for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++)
info.scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image)+8;
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=info.depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
break;
}
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelPacket *) NULL) &&
(info.samples_per_pixel == 1))
{
int
index;
size_t
one;
one=1;
if (colors == 0)
colors=one << info.depth;
if (AcquireImageColormap(image,colors) == MagickFalse)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(Quantum) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].green=(Quantum) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].blue=(Quantum) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((info.scale != (Quantum *) NULL) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(Quantum) index;
image->colormap[i].green=(Quantum) index;
image->colormap[i].blue=(Quantum) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
if (stream_info->segment_count > 1)
{
info.bytes_per_pixel=1;
info.depth=8;
if (stream_info->offset_count > 0)
(void) SeekBlob(image,stream_info->offsets[0]+
stream_info->segments[0],SEEK_SET);
}
}
if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) info.samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 1:
{
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
default:
break;
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
/*
Convert DCM Medical image to pixel packets.
*/
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
info.window_width=0;
}
option=GetImageOption(image_info,"dcm:window");
if (option != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(option,&geometry_info);
if (flags & RhoValue)
info.window_center=geometry_info.rho;
if (flags & SigmaValue)
info.window_width=geometry_info.sigma;
info.rescale=MagickTrue;
}
option=GetImageOption(image_info,"dcm:rescale");
if (option != (char *) NULL)
info.rescale=IsStringTrue(option);
if ((info.window_center != 0) && (info.window_width == 0))
info.window_width=info.window_center;
status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception);
if ((status != MagickFalse) && (stream_info->segment_count > 1))
{
if (stream_info->offset_count > 0)
(void) SeekBlob(image,stream_info->offsets[0]+
stream_info->segments[1],SEEK_SET);
(void) ReadDCMPixels(image,&info,stream_info,MagickFalse,exception);
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDCMImage() adds attributes for the DCM image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDCMImage method is:
%
% size_t RegisterDCMImage(void)
%
*/
ModuleExport size_t RegisterDCMImage(void)
{
MagickInfo
*entry;
static const char
*DCMNote=
{
"DICOM is used by the medical community for images like X-rays. The\n"
"specification, \"Digital Imaging and Communications in Medicine\n"
"(DICOM)\", is available at http://medical.nema.org/. In particular,\n"
"see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),\n"
"and supplement 61 which adds JPEG-2000 encoding."
};
entry=SetMagickInfo("DCM");
entry->decoder=(DecodeImageHandler *) ReadDCMImage;
entry->magick=(IsImageFormatHandler *) IsDCM;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(
"Digital Imaging and Communications in Medicine image");
entry->note=ConstantString(DCMNote);
entry->module=ConstantString("DCM");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDCMImage() removes format registrations made by the
% DCM module from the list of supported formats.
%
% The format of the UnregisterDCMImage method is:
%
% UnregisterDCMImage(void)
%
*/
ModuleExport void UnregisterDCMImage(void)
{
(void) UnregisterMagickInfo("DCM");
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_2615_0 |
crossvul-cpp_data_good_2622_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP CCCC X X %
% P P C X X %
% PPPP C X %
% P C X X %
% P CCCC X X %
% %
% %
% Read/Write ZSoft IBM PC Paintbrush Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Typedef declarations.
*/
typedef struct _PCXInfo
{
unsigned char
identifier,
version,
encoding,
bits_per_pixel;
unsigned short
left,
top,
right,
bottom,
horizontal_resolution,
vertical_resolution;
unsigned char
reserved,
planes;
unsigned short
bytes_per_line,
palette_info,
horizontal_screensize,
vertical_screensize;
unsigned char
colormap_signature;
} PCXInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePCXImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D C X %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDCX() returns MagickTrue if the image format type, identified by the
% magick string, is DCX.
%
% The format of the IsDCX method is:
%
% MagickBooleanType IsDCX(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDCX(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\261\150\336\72",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P C X %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPCX() returns MagickTrue if the image format type, identified by the
% magick string, is PCX.
%
% The format of the IsPCX method is:
%
% MagickBooleanType IsPCX(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPCX(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\012\002",2) == 0)
return(MagickTrue);
if (memcmp(magick,"\012\005",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P C X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPCXImage() reads a ZSoft IBM PC Paintbrush file and returns it.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the ReadPCXImage method is:
%
% Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPCXException(severity,tag) \
{ \
if (scanline != (unsigned char *) NULL) \
scanline=(unsigned char *) RelinquishMagickMemory(scanline); \
if (pixel_info != (MemoryInfo *) NULL) \
pixel_info=RelinquishVirtualMemory(pixel_info); \
if (page_table != (MagickOffsetType *) NULL) \
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); \
ThrowReaderException(severity,tag); \
}
Image
*image;
int
bits,
id,
mask;
MagickBooleanType
status;
MagickOffsetType
offset,
*page_table;
MemoryInfo
*pixel_info;
PCXInfo
pcx_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p,
*r;
size_t
one,
pcx_packets;
ssize_t
count,
y;
unsigned char
packet,
pcx_colormap[768],
*pixels,
*scanline;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a PCX file.
*/
page_table=(MagickOffsetType *) NULL;
scanline=(unsigned char *) NULL;
pixel_info=(MemoryInfo *) NULL;
if (LocaleCompare(image_info->magick,"DCX") == 0)
{
size_t
magic;
/*
Read the DCX page table.
*/
magic=ReadBlobLSBLong(image);
if (magic != 987654321)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
sizeof(*page_table));
if (page_table == (MagickOffsetType *) NULL)
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
for (id=0; id < 1024; id++)
{
page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image);
if (page_table[id] == 0)
break;
}
}
if (page_table != (MagickOffsetType *) NULL)
{
offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET);
if (offset < 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,1,&pcx_info.identifier);
for (id=1; id < 1024; id++)
{
int
bits_per_pixel;
/*
Verify PCX identifier.
*/
pcx_info.version=(unsigned char) ReadBlobByte(image);
if ((count != 1) || (pcx_info.identifier != 0x0a))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.encoding=(unsigned char) ReadBlobByte(image);
bits_per_pixel=ReadBlobByte(image);
if (bits_per_pixel == -1)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel;
pcx_info.left=ReadBlobLSBShort(image);
pcx_info.top=ReadBlobLSBShort(image);
pcx_info.right=ReadBlobLSBShort(image);
pcx_info.bottom=ReadBlobLSBShort(image);
pcx_info.horizontal_resolution=ReadBlobLSBShort(image);
pcx_info.vertical_resolution=ReadBlobLSBShort(image);
/*
Read PCX raster colormap.
*/
image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right-
pcx_info.left)+1UL;
image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom-
pcx_info.top)+1UL;
if ((image->columns == 0) || (image->rows == 0) ||
((pcx_info.bits_per_pixel != 1) && (pcx_info.bits_per_pixel != 2) &&
(pcx_info.bits_per_pixel != 4) && (pcx_info.bits_per_pixel != 8)))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
image->depth=pcx_info.bits_per_pixel;
image->units=PixelsPerInchResolution;
image->x_resolution=(double) pcx_info.horizontal_resolution;
image->y_resolution=(double) pcx_info.vertical_resolution;
image->colors=16;
count=ReadBlob(image,3*image->colors,pcx_colormap);
if (count != (ssize_t) (3*image->colors))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.reserved=(unsigned char) ReadBlobByte(image);
pcx_info.planes=(unsigned char) ReadBlobByte(image);
if (pcx_info.planes > 6)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
if (pcx_info.planes == 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
one=1;
if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1))
if ((pcx_info.version == 3) || (pcx_info.version == 5) ||
((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
image->colors=(size_t) MagickMin(one << (1UL*
(pcx_info.bits_per_pixel*pcx_info.planes)),256UL);
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1))
image->storage_class=DirectClass;
p=pcx_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
pcx_info.bytes_per_line=ReadBlobLSBShort(image);
pcx_info.palette_info=ReadBlobLSBShort(image);
pcx_info.horizontal_screensize=ReadBlobLSBShort(image);
pcx_info.vertical_screensize=ReadBlobLSBShort(image);
for (i=0; i < 54; i++)
(void) ReadBlobByte(image);
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read image data.
*/
if (HeapOverflowSanityCheck(image->rows, (size_t) pcx_info.bytes_per_line) != MagickFalse)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line;
if (HeapOverflowSanityCheck(pcx_packets, (size_t) pcx_info.planes) != MagickFalse)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_packets=(size_t) pcx_packets*pcx_info.planes;
if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) >
(pcx_packets*8U))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns,
pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline));
pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels));
if ((scanline == (unsigned char *) NULL) ||
(pixel_info == (MemoryInfo *) NULL))
{
if (scanline != (unsigned char *) NULL)
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Uncompress image data.
*/
p=pixels;
if (pcx_info.encoding == 0)
while (pcx_packets != 0)
{
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
*p++=packet;
pcx_packets--;
}
else
while (pcx_packets != 0)
{
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
if ((packet & 0xc0) != 0xc0)
{
*p++=packet;
pcx_packets--;
continue;
}
count=(ssize_t) (packet & 0x3f);
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
for ( ; count != 0; count--)
{
*p++=packet;
pcx_packets--;
if (pcx_packets == 0)
break;
}
}
if (image->storage_class == DirectClass)
image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse;
else
if ((pcx_info.version == 5) ||
((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
{
/*
Initialize image colormap.
*/
if (image->colors > 256)
ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors");
if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)
{
/*
Monochrome colormap.
*/
image->colormap[0].red=(Quantum) 0;
image->colormap[0].green=(Quantum) 0;
image->colormap[0].blue=(Quantum) 0;
image->colormap[1].red=QuantumRange;
image->colormap[1].green=QuantumRange;
image->colormap[1].blue=QuantumRange;
}
else
if (image->colors > 16)
{
/*
256 color images have their color map at the end of the file.
*/
pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image);
count=ReadBlob(image,3*image->colors,pcx_colormap);
p=pcx_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
}
}
/*
Convert PCX raster image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
r=scanline;
if (image->storage_class == DirectClass)
for (i=0; i < pcx_info.planes; i++)
{
r=scanline+i;
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
switch (i)
{
case 0:
{
*r=(*p++);
break;
}
case 1:
{
*r=(*p++);
break;
}
case 2:
{
*r=(*p++);
break;
}
case 3:
default:
{
*r=(*p++);
break;
}
}
r+=pcx_info.planes;
}
}
else
if (pcx_info.planes > 1)
{
for (x=0; x < (ssize_t) image->columns; x++)
*r++=0;
for (i=0; i < pcx_info.planes; i++)
{
r=scanline;
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
bits=(*p++);
for (mask=0x80; mask != 0; mask>>=1)
{
if (bits & mask)
*r|=1 << i;
r++;
}
}
}
}
else
switch (pcx_info.bits_per_pixel)
{
case 1:
{
register ssize_t
bit;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
*r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--)
*r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
p++;
}
break;
}
case 2:
{
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
*r++=(*p >> 6) & 0x3;
*r++=(*p >> 4) & 0x3;
*r++=(*p >> 2) & 0x3;
*r++=(*p) & 0x3;
p++;
}
if ((image->columns % 4) != 0)
{
for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--)
*r++=(unsigned char) ((*p >> (i*2)) & 0x03);
p++;
}
break;
}
case 4:
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
*r++=(*p >> 4) & 0xf;
*r++=(*p) & 0xf;
p++;
}
if ((image->columns % 2) != 0)
*r++=(*p++ >> 4) & 0xf;
break;
}
case 8:
{
(void) CopyMagickMemory(r,p,image->columns);
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=scanline;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,*r++);
else
{
SetPixelRed(q,ScaleCharToQuantum(*r++));
SetPixelGreen(q,ScaleCharToQuantum(*r++));
SetPixelBlue(q,ScaleCharToQuantum(*r++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*r++));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (page_table == (MagickOffsetType *) NULL)
break;
if (page_table[id] == 0)
break;
offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET);
if (offset < 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,1,&pcx_info.identifier);
if ((count != 0) && (pcx_info.identifier == 0x0a))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
if (page_table != (MagickOffsetType *) NULL)
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P C X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPCXImage() adds attributes for the PCX image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPCXImage method is:
%
% size_t RegisterPCXImage(void)
%
*/
ModuleExport size_t RegisterPCXImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("DCX");
entry->decoder=(DecodeImageHandler *) ReadPCXImage;
entry->encoder=(EncodeImageHandler *) WritePCXImage;
entry->seekable_stream=MagickTrue;
entry->magick=(IsImageFormatHandler *) IsDCX;
entry->description=ConstantString("ZSoft IBM PC multi-page Paintbrush");
entry->module=ConstantString("PCX");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PCX");
entry->decoder=(DecodeImageHandler *) ReadPCXImage;
entry->encoder=(EncodeImageHandler *) WritePCXImage;
entry->magick=(IsImageFormatHandler *) IsPCX;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("ZSoft IBM PC Paintbrush");
entry->module=ConstantString("PCX");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P C X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPCXImage() removes format registrations made by the
% PCX module from the list of supported formats.
%
% The format of the UnregisterPCXImage method is:
%
% UnregisterPCXImage(void)
%
*/
ModuleExport void UnregisterPCXImage(void)
{
(void) UnregisterMagickInfo("DCX");
(void) UnregisterMagickInfo("PCX");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P C X I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePCXImage() writes an image in the ZSoft IBM PC Paintbrush file
% format.
%
% The format of the WritePCXImage method is:
%
% MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
*/
static MagickBooleanType PCXWritePixels(PCXInfo *pcx_info,
const unsigned char *pixels,Image *image)
{
register const unsigned char
*q;
register ssize_t
i,
x;
ssize_t
count;
unsigned char
packet,
previous;
q=pixels;
for (i=0; i < (ssize_t) pcx_info->planes; i++)
{
if (pcx_info->encoding == 0)
{
for (x=0; x < (ssize_t) pcx_info->bytes_per_line; x++)
(void) WriteBlobByte(image,(unsigned char) (*q++));
}
else
{
previous=(*q++);
count=1;
for (x=0; x < (ssize_t) (pcx_info->bytes_per_line-1); x++)
{
packet=(*q++);
if ((packet == previous) && (count < 63))
{
count++;
continue;
}
if ((count > 1) || ((previous & 0xc0) == 0xc0))
{
count|=0xc0;
(void) WriteBlobByte(image,(unsigned char) count);
}
(void) WriteBlobByte(image,previous);
previous=packet;
count=1;
}
if ((count > 1) || ((previous & 0xc0) == 0xc0))
{
count|=0xc0;
(void) WriteBlobByte(image,(unsigned char) count);
}
(void) WriteBlobByte(image,previous);
}
}
return (MagickTrue);
}
static MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
offset,
*page_table,
scene;
MemoryInfo
*pixel_info;
PCXInfo
pcx_info;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
length;
ssize_t
y;
unsigned char
*pcx_colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
page_table=(MagickOffsetType *) NULL;
if ((LocaleCompare(image_info->magick,"DCX") == 0) ||
((GetNextImageInList(image) != (Image *) NULL) &&
(image_info->adjoin != MagickFalse)))
{
/*
Write the DCX page table.
*/
(void) WriteBlobLSBLong(image,0x3ADE68B1L);
page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
sizeof(*page_table));
if (page_table == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (scene=0; scene < 1024; scene++)
(void) WriteBlobLSBLong(image,0x00000000L);
}
scene=0;
do
{
if (page_table != (MagickOffsetType *) NULL)
page_table[scene]=TellBlob(image);
/*
Initialize PCX raster file header.
*/
pcx_info.identifier=0x0a;
pcx_info.version=5;
pcx_info.encoding=image_info->compression == NoCompression ? 0 : 1;
pcx_info.bits_per_pixel=8;
if ((image->storage_class == PseudoClass) &&
(SetImageMonochrome(image,&image->exception) != MagickFalse))
pcx_info.bits_per_pixel=1;
pcx_info.left=0;
pcx_info.top=0;
pcx_info.right=(unsigned short) (image->columns-1);
pcx_info.bottom=(unsigned short) (image->rows-1);
switch (image->units)
{
case UndefinedResolution:
case PixelsPerInchResolution:
default:
{
pcx_info.horizontal_resolution=(unsigned short) image->x_resolution;
pcx_info.vertical_resolution=(unsigned short) image->y_resolution;
break;
}
case PixelsPerCentimeterResolution:
{
pcx_info.horizontal_resolution=(unsigned short)
(2.54*image->x_resolution+0.5);
pcx_info.vertical_resolution=(unsigned short)
(2.54*image->y_resolution+0.5);
break;
}
}
pcx_info.reserved=0;
pcx_info.planes=1;
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
pcx_info.planes=3;
if (image->matte != MagickFalse)
pcx_info.planes++;
}
pcx_info.bytes_per_line=(unsigned short) (((size_t) image->columns*
pcx_info.bits_per_pixel+7)/8);
pcx_info.palette_info=1;
pcx_info.colormap_signature=0x0c;
/*
Write PCX header.
*/
(void) WriteBlobByte(image,pcx_info.identifier);
(void) WriteBlobByte(image,pcx_info.version);
(void) WriteBlobByte(image,pcx_info.encoding);
(void) WriteBlobByte(image,pcx_info.bits_per_pixel);
(void) WriteBlobLSBShort(image,pcx_info.left);
(void) WriteBlobLSBShort(image,pcx_info.top);
(void) WriteBlobLSBShort(image,pcx_info.right);
(void) WriteBlobLSBShort(image,pcx_info.bottom);
(void) WriteBlobLSBShort(image,pcx_info.horizontal_resolution);
(void) WriteBlobLSBShort(image,pcx_info.vertical_resolution);
/*
Dump colormap to file.
*/
pcx_colormap=(unsigned char *) AcquireQuantumMemory(256UL,
3*sizeof(*pcx_colormap));
if (pcx_colormap == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(pcx_colormap,0,3*256*sizeof(*pcx_colormap));
q=pcx_colormap;
if ((image->storage_class == PseudoClass) && (image->colors <= 256))
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=ScaleQuantumToChar(image->colormap[i].red);
*q++=ScaleQuantumToChar(image->colormap[i].green);
*q++=ScaleQuantumToChar(image->colormap[i].blue);
}
(void) WriteBlob(image,3*16,(const unsigned char *) pcx_colormap);
(void) WriteBlobByte(image,pcx_info.reserved);
(void) WriteBlobByte(image,pcx_info.planes);
(void) WriteBlobLSBShort(image,pcx_info.bytes_per_line);
(void) WriteBlobLSBShort(image,pcx_info.palette_info);
for (i=0; i < 58; i++)
(void) WriteBlobByte(image,'\0');
length=(size_t) pcx_info.bytes_per_line;
pixel_info=AcquireVirtualMemory(length,pcx_info.planes*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
q=pixels;
if ((image->storage_class == DirectClass) || (image->colors > 256))
{
/*
Convert DirectClass image to PCX raster pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=pixels;
for (i=0; i < pcx_info.planes; i++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
switch ((int) i)
{
case 0:
{
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(p));
p++;
}
break;
}
case 1:
{
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
*q++=ScaleQuantumToChar(GetPixelGreen(p));
p++;
}
break;
}
case 2:
{
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(p));
p++;
}
break;
}
case 3:
default:
{
for (x=(ssize_t) pcx_info.bytes_per_line; x != 0; x--)
{
*q++=ScaleQuantumToChar((Quantum)
(GetPixelAlpha(p)));
p++;
}
break;
}
}
}
if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
if (pcx_info.bits_per_pixel > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
register unsigned char
bit,
byte;
/*
Convert PseudoClass image to a PCX monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
bit=0;
byte=0;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (GetPixelLuma(image,p) >= (QuantumRange/2.0))
byte|=0x01;
bit++;
if (bit == 8)
{
*q++=byte;
bit=0;
byte=0;
}
p++;
}
if (bit != 0)
*q++=byte << (8-bit);
if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
(void) WriteBlobByte(image,pcx_info.colormap_signature);
(void) WriteBlob(image,3*256,pcx_colormap);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap);
if (page_table == (MagickOffsetType *) NULL)
break;
if (scene >= 1023)
break;
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
if (page_table != (MagickOffsetType *) NULL)
{
/*
Write the DCX page table.
*/
page_table[scene+1]=0;
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowWriterException(CorruptImageError,"ImproperImageHeader");
(void) WriteBlobLSBLong(image,0x3ADE68B1L);
for (i=0; i <= (ssize_t) scene; i++)
(void) WriteBlobLSBLong(image,(unsigned int) page_table[i]);
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
}
if (status == MagickFalse)
{
char
*message;
message=GetExceptionMessage(errno);
(void) ThrowMagickException(&image->exception,GetMagickModule(),
FileOpenError,"UnableToWriteFile","`%s': %s",image->filename,message);
message=DestroyString(message);
}
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_2622_0 |
crossvul-cpp_data_good_661_0 | /*
* mac80211_hwsim - software simulator of 802.11 radio(s) for mac80211
* Copyright (c) 2008, Jouni Malinen <j@w1.fi>
* Copyright (c) 2011, Javier Lopez <jlopex@gmail.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.
*/
/*
* TODO:
* - Add TSF sync and fix IBSS beacon transmission by adding
* competition for "air time" at TBTT
* - RX filtering based on filter configuration (data->rx_filter)
*/
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <net/mac80211.h>
#include <net/ieee80211_radiotap.h>
#include <linux/if_arp.h>
#include <linux/rtnetlink.h>
#include <linux/etherdevice.h>
#include <linux/platform_device.h>
#include <linux/debugfs.h>
#include <linux/module.h>
#include <linux/ktime.h>
#include <net/genetlink.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <linux/rhashtable.h>
#include "mac80211_hwsim.h"
#define WARN_QUEUE 100
#define MAX_QUEUE 200
MODULE_AUTHOR("Jouni Malinen");
MODULE_DESCRIPTION("Software simulator of 802.11 radio(s) for mac80211");
MODULE_LICENSE("GPL");
static int radios = 2;
module_param(radios, int, 0444);
MODULE_PARM_DESC(radios, "Number of simulated radios");
static int channels = 1;
module_param(channels, int, 0444);
MODULE_PARM_DESC(channels, "Number of concurrent channels");
static bool paged_rx = false;
module_param(paged_rx, bool, 0644);
MODULE_PARM_DESC(paged_rx, "Use paged SKBs for RX instead of linear ones");
static bool rctbl = false;
module_param(rctbl, bool, 0444);
MODULE_PARM_DESC(rctbl, "Handle rate control table");
static bool support_p2p_device = true;
module_param(support_p2p_device, bool, 0444);
MODULE_PARM_DESC(support_p2p_device, "Support P2P-Device interface type");
/**
* enum hwsim_regtest - the type of regulatory tests we offer
*
* These are the different values you can use for the regtest
* module parameter. This is useful to help test world roaming
* and the driver regulatory_hint() call and combinations of these.
* If you want to do specific alpha2 regulatory domain tests simply
* use the userspace regulatory request as that will be respected as
* well without the need of this module parameter. This is designed
* only for testing the driver regulatory request, world roaming
* and all possible combinations.
*
* @HWSIM_REGTEST_DISABLED: No regulatory tests are performed,
* this is the default value.
* @HWSIM_REGTEST_DRIVER_REG_FOLLOW: Used for testing the driver regulatory
* hint, only one driver regulatory hint will be sent as such the
* secondary radios are expected to follow.
* @HWSIM_REGTEST_DRIVER_REG_ALL: Used for testing the driver regulatory
* request with all radios reporting the same regulatory domain.
* @HWSIM_REGTEST_DIFF_COUNTRY: Used for testing the drivers calling
* different regulatory domains requests. Expected behaviour is for
* an intersection to occur but each device will still use their
* respective regulatory requested domains. Subsequent radios will
* use the resulting intersection.
* @HWSIM_REGTEST_WORLD_ROAM: Used for testing the world roaming. We accomplish
* this by using a custom beacon-capable regulatory domain for the first
* radio. All other device world roam.
* @HWSIM_REGTEST_CUSTOM_WORLD: Used for testing the custom world regulatory
* domain requests. All radios will adhere to this custom world regulatory
* domain.
* @HWSIM_REGTEST_CUSTOM_WORLD_2: Used for testing 2 custom world regulatory
* domain requests. The first radio will adhere to the first custom world
* regulatory domain, the second one to the second custom world regulatory
* domain. All other devices will world roam.
* @HWSIM_REGTEST_STRICT_FOLLOW_: Used for testing strict regulatory domain
* settings, only the first radio will send a regulatory domain request
* and use strict settings. The rest of the radios are expected to follow.
* @HWSIM_REGTEST_STRICT_ALL: Used for testing strict regulatory domain
* settings. All radios will adhere to this.
* @HWSIM_REGTEST_STRICT_AND_DRIVER_REG: Used for testing strict regulatory
* domain settings, combined with secondary driver regulatory domain
* settings. The first radio will get a strict regulatory domain setting
* using the first driver regulatory request and the second radio will use
* non-strict settings using the second driver regulatory request. All
* other devices should follow the intersection created between the
* first two.
* @HWSIM_REGTEST_ALL: Used for testing every possible mix. You will need
* at least 6 radios for a complete test. We will test in this order:
* 1 - driver custom world regulatory domain
* 2 - second custom world regulatory domain
* 3 - first driver regulatory domain request
* 4 - second driver regulatory domain request
* 5 - strict regulatory domain settings using the third driver regulatory
* domain request
* 6 and on - should follow the intersection of the 3rd, 4rth and 5th radio
* regulatory requests.
*/
enum hwsim_regtest {
HWSIM_REGTEST_DISABLED = 0,
HWSIM_REGTEST_DRIVER_REG_FOLLOW = 1,
HWSIM_REGTEST_DRIVER_REG_ALL = 2,
HWSIM_REGTEST_DIFF_COUNTRY = 3,
HWSIM_REGTEST_WORLD_ROAM = 4,
HWSIM_REGTEST_CUSTOM_WORLD = 5,
HWSIM_REGTEST_CUSTOM_WORLD_2 = 6,
HWSIM_REGTEST_STRICT_FOLLOW = 7,
HWSIM_REGTEST_STRICT_ALL = 8,
HWSIM_REGTEST_STRICT_AND_DRIVER_REG = 9,
HWSIM_REGTEST_ALL = 10,
};
/* Set to one of the HWSIM_REGTEST_* values above */
static int regtest = HWSIM_REGTEST_DISABLED;
module_param(regtest, int, 0444);
MODULE_PARM_DESC(regtest, "The type of regulatory test we want to run");
static const char *hwsim_alpha2s[] = {
"FI",
"AL",
"US",
"DE",
"JP",
"AL",
};
static const struct ieee80211_regdomain hwsim_world_regdom_custom_01 = {
.n_reg_rules = 4,
.alpha2 = "99",
.reg_rules = {
REG_RULE(2412-10, 2462+10, 40, 0, 20, 0),
REG_RULE(2484-10, 2484+10, 40, 0, 20, 0),
REG_RULE(5150-10, 5240+10, 40, 0, 30, 0),
REG_RULE(5745-10, 5825+10, 40, 0, 30, 0),
}
};
static const struct ieee80211_regdomain hwsim_world_regdom_custom_02 = {
.n_reg_rules = 2,
.alpha2 = "99",
.reg_rules = {
REG_RULE(2412-10, 2462+10, 40, 0, 20, 0),
REG_RULE(5725-10, 5850+10, 40, 0, 30,
NL80211_RRF_NO_IR),
}
};
static const struct ieee80211_regdomain *hwsim_world_regdom_custom[] = {
&hwsim_world_regdom_custom_01,
&hwsim_world_regdom_custom_02,
};
struct hwsim_vif_priv {
u32 magic;
u8 bssid[ETH_ALEN];
bool assoc;
bool bcn_en;
u16 aid;
};
#define HWSIM_VIF_MAGIC 0x69537748
static inline void hwsim_check_magic(struct ieee80211_vif *vif)
{
struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
WARN(vp->magic != HWSIM_VIF_MAGIC,
"Invalid VIF (%p) magic %#x, %pM, %d/%d\n",
vif, vp->magic, vif->addr, vif->type, vif->p2p);
}
static inline void hwsim_set_magic(struct ieee80211_vif *vif)
{
struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
vp->magic = HWSIM_VIF_MAGIC;
}
static inline void hwsim_clear_magic(struct ieee80211_vif *vif)
{
struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
vp->magic = 0;
}
struct hwsim_sta_priv {
u32 magic;
};
#define HWSIM_STA_MAGIC 0x6d537749
static inline void hwsim_check_sta_magic(struct ieee80211_sta *sta)
{
struct hwsim_sta_priv *sp = (void *)sta->drv_priv;
WARN_ON(sp->magic != HWSIM_STA_MAGIC);
}
static inline void hwsim_set_sta_magic(struct ieee80211_sta *sta)
{
struct hwsim_sta_priv *sp = (void *)sta->drv_priv;
sp->magic = HWSIM_STA_MAGIC;
}
static inline void hwsim_clear_sta_magic(struct ieee80211_sta *sta)
{
struct hwsim_sta_priv *sp = (void *)sta->drv_priv;
sp->magic = 0;
}
struct hwsim_chanctx_priv {
u32 magic;
};
#define HWSIM_CHANCTX_MAGIC 0x6d53774a
static inline void hwsim_check_chanctx_magic(struct ieee80211_chanctx_conf *c)
{
struct hwsim_chanctx_priv *cp = (void *)c->drv_priv;
WARN_ON(cp->magic != HWSIM_CHANCTX_MAGIC);
}
static inline void hwsim_set_chanctx_magic(struct ieee80211_chanctx_conf *c)
{
struct hwsim_chanctx_priv *cp = (void *)c->drv_priv;
cp->magic = HWSIM_CHANCTX_MAGIC;
}
static inline void hwsim_clear_chanctx_magic(struct ieee80211_chanctx_conf *c)
{
struct hwsim_chanctx_priv *cp = (void *)c->drv_priv;
cp->magic = 0;
}
static unsigned int hwsim_net_id;
static int hwsim_netgroup;
struct hwsim_net {
int netgroup;
u32 wmediumd;
};
static inline int hwsim_net_get_netgroup(struct net *net)
{
struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
return hwsim_net->netgroup;
}
static inline void hwsim_net_set_netgroup(struct net *net)
{
struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
hwsim_net->netgroup = hwsim_netgroup++;
}
static inline u32 hwsim_net_get_wmediumd(struct net *net)
{
struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
return hwsim_net->wmediumd;
}
static inline void hwsim_net_set_wmediumd(struct net *net, u32 portid)
{
struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
hwsim_net->wmediumd = portid;
}
static struct class *hwsim_class;
static struct net_device *hwsim_mon; /* global monitor netdev */
#define CHAN2G(_freq) { \
.band = NL80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_freq), \
.max_power = 20, \
}
#define CHAN5G(_freq) { \
.band = NL80211_BAND_5GHZ, \
.center_freq = (_freq), \
.hw_value = (_freq), \
.max_power = 20, \
}
static const struct ieee80211_channel hwsim_channels_2ghz[] = {
CHAN2G(2412), /* Channel 1 */
CHAN2G(2417), /* Channel 2 */
CHAN2G(2422), /* Channel 3 */
CHAN2G(2427), /* Channel 4 */
CHAN2G(2432), /* Channel 5 */
CHAN2G(2437), /* Channel 6 */
CHAN2G(2442), /* Channel 7 */
CHAN2G(2447), /* Channel 8 */
CHAN2G(2452), /* Channel 9 */
CHAN2G(2457), /* Channel 10 */
CHAN2G(2462), /* Channel 11 */
CHAN2G(2467), /* Channel 12 */
CHAN2G(2472), /* Channel 13 */
CHAN2G(2484), /* Channel 14 */
};
static const struct ieee80211_channel hwsim_channels_5ghz[] = {
CHAN5G(5180), /* Channel 36 */
CHAN5G(5200), /* Channel 40 */
CHAN5G(5220), /* Channel 44 */
CHAN5G(5240), /* Channel 48 */
CHAN5G(5260), /* Channel 52 */
CHAN5G(5280), /* Channel 56 */
CHAN5G(5300), /* Channel 60 */
CHAN5G(5320), /* Channel 64 */
CHAN5G(5500), /* Channel 100 */
CHAN5G(5520), /* Channel 104 */
CHAN5G(5540), /* Channel 108 */
CHAN5G(5560), /* Channel 112 */
CHAN5G(5580), /* Channel 116 */
CHAN5G(5600), /* Channel 120 */
CHAN5G(5620), /* Channel 124 */
CHAN5G(5640), /* Channel 128 */
CHAN5G(5660), /* Channel 132 */
CHAN5G(5680), /* Channel 136 */
CHAN5G(5700), /* Channel 140 */
CHAN5G(5745), /* Channel 149 */
CHAN5G(5765), /* Channel 153 */
CHAN5G(5785), /* Channel 157 */
CHAN5G(5805), /* Channel 161 */
CHAN5G(5825), /* Channel 165 */
CHAN5G(5845), /* Channel 169 */
};
static const struct ieee80211_rate hwsim_rates[] = {
{ .bitrate = 10 },
{ .bitrate = 20, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 55, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 110, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 60 },
{ .bitrate = 90 },
{ .bitrate = 120 },
{ .bitrate = 180 },
{ .bitrate = 240 },
{ .bitrate = 360 },
{ .bitrate = 480 },
{ .bitrate = 540 }
};
#define OUI_QCA 0x001374
#define QCA_NL80211_SUBCMD_TEST 1
enum qca_nl80211_vendor_subcmds {
QCA_WLAN_VENDOR_ATTR_TEST = 8,
QCA_WLAN_VENDOR_ATTR_MAX = QCA_WLAN_VENDOR_ATTR_TEST
};
static const struct nla_policy
hwsim_vendor_test_policy[QCA_WLAN_VENDOR_ATTR_MAX + 1] = {
[QCA_WLAN_VENDOR_ATTR_MAX] = { .type = NLA_U32 },
};
static int mac80211_hwsim_vendor_cmd_test(struct wiphy *wiphy,
struct wireless_dev *wdev,
const void *data, int data_len)
{
struct sk_buff *skb;
struct nlattr *tb[QCA_WLAN_VENDOR_ATTR_MAX + 1];
int err;
u32 val;
err = nla_parse(tb, QCA_WLAN_VENDOR_ATTR_MAX, data, data_len,
hwsim_vendor_test_policy, NULL);
if (err)
return err;
if (!tb[QCA_WLAN_VENDOR_ATTR_TEST])
return -EINVAL;
val = nla_get_u32(tb[QCA_WLAN_VENDOR_ATTR_TEST]);
wiphy_dbg(wiphy, "%s: test=%u\n", __func__, val);
/* Send a vendor event as a test. Note that this would not normally be
* done within a command handler, but rather, based on some other
* trigger. For simplicity, this command is used to trigger the event
* here.
*
* event_idx = 0 (index in mac80211_hwsim_vendor_commands)
*/
skb = cfg80211_vendor_event_alloc(wiphy, wdev, 100, 0, GFP_KERNEL);
if (skb) {
/* skb_put() or nla_put() will fill up data within
* NL80211_ATTR_VENDOR_DATA.
*/
/* Add vendor data */
nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_TEST, val + 1);
/* Send the event - this will call nla_nest_end() */
cfg80211_vendor_event(skb, GFP_KERNEL);
}
/* Send a response to the command */
skb = cfg80211_vendor_cmd_alloc_reply_skb(wiphy, 10);
if (!skb)
return -ENOMEM;
/* skb_put() or nla_put() will fill up data within
* NL80211_ATTR_VENDOR_DATA
*/
nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_TEST, val + 2);
return cfg80211_vendor_cmd_reply(skb);
}
static struct wiphy_vendor_command mac80211_hwsim_vendor_commands[] = {
{
.info = { .vendor_id = OUI_QCA,
.subcmd = QCA_NL80211_SUBCMD_TEST },
.flags = WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mac80211_hwsim_vendor_cmd_test,
}
};
/* Advertise support vendor specific events */
static const struct nl80211_vendor_cmd_info mac80211_hwsim_vendor_events[] = {
{ .vendor_id = OUI_QCA, .subcmd = 1 },
};
static const struct ieee80211_iface_limit hwsim_if_limits[] = {
{ .max = 1, .types = BIT(NL80211_IFTYPE_ADHOC) },
{ .max = 2048, .types = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_P2P_CLIENT) |
#ifdef CONFIG_MAC80211_MESH
BIT(NL80211_IFTYPE_MESH_POINT) |
#endif
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_GO) },
/* must be last, see hwsim_if_comb */
{ .max = 1, .types = BIT(NL80211_IFTYPE_P2P_DEVICE) }
};
static const struct ieee80211_iface_combination hwsim_if_comb[] = {
{
.limits = hwsim_if_limits,
/* remove the last entry which is P2P_DEVICE */
.n_limits = ARRAY_SIZE(hwsim_if_limits) - 1,
.max_interfaces = 2048,
.num_different_channels = 1,
.radar_detect_widths = BIT(NL80211_CHAN_WIDTH_20_NOHT) |
BIT(NL80211_CHAN_WIDTH_20) |
BIT(NL80211_CHAN_WIDTH_40) |
BIT(NL80211_CHAN_WIDTH_80) |
BIT(NL80211_CHAN_WIDTH_160),
},
};
static const struct ieee80211_iface_combination hwsim_if_comb_p2p_dev[] = {
{
.limits = hwsim_if_limits,
.n_limits = ARRAY_SIZE(hwsim_if_limits),
.max_interfaces = 2048,
.num_different_channels = 1,
.radar_detect_widths = BIT(NL80211_CHAN_WIDTH_20_NOHT) |
BIT(NL80211_CHAN_WIDTH_20) |
BIT(NL80211_CHAN_WIDTH_40) |
BIT(NL80211_CHAN_WIDTH_80) |
BIT(NL80211_CHAN_WIDTH_160),
},
};
static spinlock_t hwsim_radio_lock;
static LIST_HEAD(hwsim_radios);
static struct rhashtable hwsim_radios_rht;
static int hwsim_radio_idx;
static struct platform_driver mac80211_hwsim_driver = {
.driver = {
.name = "mac80211_hwsim",
},
};
struct mac80211_hwsim_data {
struct list_head list;
struct rhash_head rht;
struct ieee80211_hw *hw;
struct device *dev;
struct ieee80211_supported_band bands[NUM_NL80211_BANDS];
struct ieee80211_channel channels_2ghz[ARRAY_SIZE(hwsim_channels_2ghz)];
struct ieee80211_channel channels_5ghz[ARRAY_SIZE(hwsim_channels_5ghz)];
struct ieee80211_rate rates[ARRAY_SIZE(hwsim_rates)];
struct ieee80211_iface_combination if_combination;
struct mac_address addresses[2];
int channels, idx;
bool use_chanctx;
bool destroy_on_close;
struct work_struct destroy_work;
u32 portid;
char alpha2[2];
const struct ieee80211_regdomain *regd;
struct ieee80211_channel *tmp_chan;
struct ieee80211_channel *roc_chan;
u32 roc_duration;
struct delayed_work roc_start;
struct delayed_work roc_done;
struct delayed_work hw_scan;
struct cfg80211_scan_request *hw_scan_request;
struct ieee80211_vif *hw_scan_vif;
int scan_chan_idx;
u8 scan_addr[ETH_ALEN];
struct {
struct ieee80211_channel *channel;
unsigned long next_start, start, end;
} survey_data[ARRAY_SIZE(hwsim_channels_2ghz) +
ARRAY_SIZE(hwsim_channels_5ghz)];
struct ieee80211_channel *channel;
u64 beacon_int /* beacon interval in us */;
unsigned int rx_filter;
bool started, idle, scanning;
struct mutex mutex;
struct tasklet_hrtimer beacon_timer;
enum ps_mode {
PS_DISABLED, PS_ENABLED, PS_AUTO_POLL, PS_MANUAL_POLL
} ps;
bool ps_poll_pending;
struct dentry *debugfs;
uintptr_t pending_cookie;
struct sk_buff_head pending; /* packets pending */
/*
* Only radios in the same group can communicate together (the
* channel has to match too). Each bit represents a group. A
* radio can be in more than one group.
*/
u64 group;
/* group shared by radios created in the same netns */
int netgroup;
/* wmediumd portid responsible for netgroup of this radio */
u32 wmediumd;
/* difference between this hw's clock and the real clock, in usecs */
s64 tsf_offset;
s64 bcn_delta;
/* absolute beacon transmission time. Used to cover up "tx" delay. */
u64 abs_bcn_ts;
/* Stats */
u64 tx_pkts;
u64 rx_pkts;
u64 tx_bytes;
u64 rx_bytes;
u64 tx_dropped;
u64 tx_failed;
};
static const struct rhashtable_params hwsim_rht_params = {
.nelem_hint = 2,
.automatic_shrinking = true,
.key_len = ETH_ALEN,
.key_offset = offsetof(struct mac80211_hwsim_data, addresses[1]),
.head_offset = offsetof(struct mac80211_hwsim_data, rht),
};
struct hwsim_radiotap_hdr {
struct ieee80211_radiotap_header hdr;
__le64 rt_tsft;
u8 rt_flags;
u8 rt_rate;
__le16 rt_channel;
__le16 rt_chbitmask;
} __packed;
struct hwsim_radiotap_ack_hdr {
struct ieee80211_radiotap_header hdr;
u8 rt_flags;
u8 pad;
__le16 rt_channel;
__le16 rt_chbitmask;
} __packed;
/* MAC80211_HWSIM netlink family */
static struct genl_family hwsim_genl_family;
enum hwsim_multicast_groups {
HWSIM_MCGRP_CONFIG,
};
static const struct genl_multicast_group hwsim_mcgrps[] = {
[HWSIM_MCGRP_CONFIG] = { .name = "config", },
};
/* MAC80211_HWSIM netlink policy */
static const struct nla_policy hwsim_genl_policy[HWSIM_ATTR_MAX + 1] = {
[HWSIM_ATTR_ADDR_RECEIVER] = { .type = NLA_UNSPEC, .len = ETH_ALEN },
[HWSIM_ATTR_ADDR_TRANSMITTER] = { .type = NLA_UNSPEC, .len = ETH_ALEN },
[HWSIM_ATTR_FRAME] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[HWSIM_ATTR_FLAGS] = { .type = NLA_U32 },
[HWSIM_ATTR_RX_RATE] = { .type = NLA_U32 },
[HWSIM_ATTR_SIGNAL] = { .type = NLA_U32 },
[HWSIM_ATTR_TX_INFO] = { .type = NLA_UNSPEC,
.len = IEEE80211_TX_MAX_RATES *
sizeof(struct hwsim_tx_rate)},
[HWSIM_ATTR_COOKIE] = { .type = NLA_U64 },
[HWSIM_ATTR_CHANNELS] = { .type = NLA_U32 },
[HWSIM_ATTR_RADIO_ID] = { .type = NLA_U32 },
[HWSIM_ATTR_REG_HINT_ALPHA2] = { .type = NLA_STRING, .len = 2 },
[HWSIM_ATTR_REG_CUSTOM_REG] = { .type = NLA_U32 },
[HWSIM_ATTR_REG_STRICT_REG] = { .type = NLA_FLAG },
[HWSIM_ATTR_SUPPORT_P2P_DEVICE] = { .type = NLA_FLAG },
[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE] = { .type = NLA_FLAG },
[HWSIM_ATTR_RADIO_NAME] = { .type = NLA_STRING },
[HWSIM_ATTR_NO_VIF] = { .type = NLA_FLAG },
[HWSIM_ATTR_FREQ] = { .type = NLA_U32 },
};
static void mac80211_hwsim_tx_frame(struct ieee80211_hw *hw,
struct sk_buff *skb,
struct ieee80211_channel *chan);
/* sysfs attributes */
static void hwsim_send_ps_poll(void *dat, u8 *mac, struct ieee80211_vif *vif)
{
struct mac80211_hwsim_data *data = dat;
struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
struct sk_buff *skb;
struct ieee80211_pspoll *pspoll;
if (!vp->assoc)
return;
wiphy_dbg(data->hw->wiphy,
"%s: send PS-Poll to %pM for aid %d\n",
__func__, vp->bssid, vp->aid);
skb = dev_alloc_skb(sizeof(*pspoll));
if (!skb)
return;
pspoll = skb_put(skb, sizeof(*pspoll));
pspoll->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
IEEE80211_STYPE_PSPOLL |
IEEE80211_FCTL_PM);
pspoll->aid = cpu_to_le16(0xc000 | vp->aid);
memcpy(pspoll->bssid, vp->bssid, ETH_ALEN);
memcpy(pspoll->ta, mac, ETH_ALEN);
rcu_read_lock();
mac80211_hwsim_tx_frame(data->hw, skb,
rcu_dereference(vif->chanctx_conf)->def.chan);
rcu_read_unlock();
}
static void hwsim_send_nullfunc(struct mac80211_hwsim_data *data, u8 *mac,
struct ieee80211_vif *vif, int ps)
{
struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
struct sk_buff *skb;
struct ieee80211_hdr *hdr;
if (!vp->assoc)
return;
wiphy_dbg(data->hw->wiphy,
"%s: send data::nullfunc to %pM ps=%d\n",
__func__, vp->bssid, ps);
skb = dev_alloc_skb(sizeof(*hdr));
if (!skb)
return;
hdr = skb_put(skb, sizeof(*hdr) - ETH_ALEN);
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC |
IEEE80211_FCTL_TODS |
(ps ? IEEE80211_FCTL_PM : 0));
hdr->duration_id = cpu_to_le16(0);
memcpy(hdr->addr1, vp->bssid, ETH_ALEN);
memcpy(hdr->addr2, mac, ETH_ALEN);
memcpy(hdr->addr3, vp->bssid, ETH_ALEN);
rcu_read_lock();
mac80211_hwsim_tx_frame(data->hw, skb,
rcu_dereference(vif->chanctx_conf)->def.chan);
rcu_read_unlock();
}
static void hwsim_send_nullfunc_ps(void *dat, u8 *mac,
struct ieee80211_vif *vif)
{
struct mac80211_hwsim_data *data = dat;
hwsim_send_nullfunc(data, mac, vif, 1);
}
static void hwsim_send_nullfunc_no_ps(void *dat, u8 *mac,
struct ieee80211_vif *vif)
{
struct mac80211_hwsim_data *data = dat;
hwsim_send_nullfunc(data, mac, vif, 0);
}
static int hwsim_fops_ps_read(void *dat, u64 *val)
{
struct mac80211_hwsim_data *data = dat;
*val = data->ps;
return 0;
}
static int hwsim_fops_ps_write(void *dat, u64 val)
{
struct mac80211_hwsim_data *data = dat;
enum ps_mode old_ps;
if (val != PS_DISABLED && val != PS_ENABLED && val != PS_AUTO_POLL &&
val != PS_MANUAL_POLL)
return -EINVAL;
if (val == PS_MANUAL_POLL) {
if (data->ps != PS_ENABLED)
return -EINVAL;
local_bh_disable();
ieee80211_iterate_active_interfaces_atomic(
data->hw, IEEE80211_IFACE_ITER_NORMAL,
hwsim_send_ps_poll, data);
local_bh_enable();
return 0;
}
old_ps = data->ps;
data->ps = val;
local_bh_disable();
if (old_ps == PS_DISABLED && val != PS_DISABLED) {
ieee80211_iterate_active_interfaces_atomic(
data->hw, IEEE80211_IFACE_ITER_NORMAL,
hwsim_send_nullfunc_ps, data);
} else if (old_ps != PS_DISABLED && val == PS_DISABLED) {
ieee80211_iterate_active_interfaces_atomic(
data->hw, IEEE80211_IFACE_ITER_NORMAL,
hwsim_send_nullfunc_no_ps, data);
}
local_bh_enable();
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(hwsim_fops_ps, hwsim_fops_ps_read, hwsim_fops_ps_write,
"%llu\n");
static int hwsim_write_simulate_radar(void *dat, u64 val)
{
struct mac80211_hwsim_data *data = dat;
ieee80211_radar_detected(data->hw);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(hwsim_simulate_radar, NULL,
hwsim_write_simulate_radar, "%llu\n");
static int hwsim_fops_group_read(void *dat, u64 *val)
{
struct mac80211_hwsim_data *data = dat;
*val = data->group;
return 0;
}
static int hwsim_fops_group_write(void *dat, u64 val)
{
struct mac80211_hwsim_data *data = dat;
data->group = val;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(hwsim_fops_group,
hwsim_fops_group_read, hwsim_fops_group_write,
"%llx\n");
static netdev_tx_t hwsim_mon_xmit(struct sk_buff *skb,
struct net_device *dev)
{
/* TODO: allow packet injection */
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static inline u64 mac80211_hwsim_get_tsf_raw(void)
{
return ktime_to_us(ktime_get_real());
}
static __le64 __mac80211_hwsim_get_tsf(struct mac80211_hwsim_data *data)
{
u64 now = mac80211_hwsim_get_tsf_raw();
return cpu_to_le64(now + data->tsf_offset);
}
static u64 mac80211_hwsim_get_tsf(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct mac80211_hwsim_data *data = hw->priv;
return le64_to_cpu(__mac80211_hwsim_get_tsf(data));
}
static void mac80211_hwsim_set_tsf(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u64 tsf)
{
struct mac80211_hwsim_data *data = hw->priv;
u64 now = mac80211_hwsim_get_tsf(hw, vif);
u32 bcn_int = data->beacon_int;
u64 delta = abs(tsf - now);
/* adjust after beaconing with new timestamp at old TBTT */
if (tsf > now) {
data->tsf_offset += delta;
data->bcn_delta = do_div(delta, bcn_int);
} else {
data->tsf_offset -= delta;
data->bcn_delta = -(s64)do_div(delta, bcn_int);
}
}
static void mac80211_hwsim_monitor_rx(struct ieee80211_hw *hw,
struct sk_buff *tx_skb,
struct ieee80211_channel *chan)
{
struct mac80211_hwsim_data *data = hw->priv;
struct sk_buff *skb;
struct hwsim_radiotap_hdr *hdr;
u16 flags;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx_skb);
struct ieee80211_rate *txrate = ieee80211_get_tx_rate(hw, info);
if (WARN_ON(!txrate))
return;
if (!netif_running(hwsim_mon))
return;
skb = skb_copy_expand(tx_skb, sizeof(*hdr), 0, GFP_ATOMIC);
if (skb == NULL)
return;
hdr = skb_push(skb, sizeof(*hdr));
hdr->hdr.it_version = PKTHDR_RADIOTAP_VERSION;
hdr->hdr.it_pad = 0;
hdr->hdr.it_len = cpu_to_le16(sizeof(*hdr));
hdr->hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) |
(1 << IEEE80211_RADIOTAP_RATE) |
(1 << IEEE80211_RADIOTAP_TSFT) |
(1 << IEEE80211_RADIOTAP_CHANNEL));
hdr->rt_tsft = __mac80211_hwsim_get_tsf(data);
hdr->rt_flags = 0;
hdr->rt_rate = txrate->bitrate / 5;
hdr->rt_channel = cpu_to_le16(chan->center_freq);
flags = IEEE80211_CHAN_2GHZ;
if (txrate->flags & IEEE80211_RATE_ERP_G)
flags |= IEEE80211_CHAN_OFDM;
else
flags |= IEEE80211_CHAN_CCK;
hdr->rt_chbitmask = cpu_to_le16(flags);
skb->dev = hwsim_mon;
skb_reset_mac_header(skb);
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->pkt_type = PACKET_OTHERHOST;
skb->protocol = htons(ETH_P_802_2);
memset(skb->cb, 0, sizeof(skb->cb));
netif_rx(skb);
}
static void mac80211_hwsim_monitor_ack(struct ieee80211_channel *chan,
const u8 *addr)
{
struct sk_buff *skb;
struct hwsim_radiotap_ack_hdr *hdr;
u16 flags;
struct ieee80211_hdr *hdr11;
if (!netif_running(hwsim_mon))
return;
skb = dev_alloc_skb(100);
if (skb == NULL)
return;
hdr = skb_put(skb, sizeof(*hdr));
hdr->hdr.it_version = PKTHDR_RADIOTAP_VERSION;
hdr->hdr.it_pad = 0;
hdr->hdr.it_len = cpu_to_le16(sizeof(*hdr));
hdr->hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) |
(1 << IEEE80211_RADIOTAP_CHANNEL));
hdr->rt_flags = 0;
hdr->pad = 0;
hdr->rt_channel = cpu_to_le16(chan->center_freq);
flags = IEEE80211_CHAN_2GHZ;
hdr->rt_chbitmask = cpu_to_le16(flags);
hdr11 = skb_put(skb, 10);
hdr11->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
IEEE80211_STYPE_ACK);
hdr11->duration_id = cpu_to_le16(0);
memcpy(hdr11->addr1, addr, ETH_ALEN);
skb->dev = hwsim_mon;
skb_reset_mac_header(skb);
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->pkt_type = PACKET_OTHERHOST;
skb->protocol = htons(ETH_P_802_2);
memset(skb->cb, 0, sizeof(skb->cb));
netif_rx(skb);
}
struct mac80211_hwsim_addr_match_data {
u8 addr[ETH_ALEN];
bool ret;
};
static void mac80211_hwsim_addr_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct mac80211_hwsim_addr_match_data *md = data;
if (memcmp(mac, md->addr, ETH_ALEN) == 0)
md->ret = true;
}
static bool mac80211_hwsim_addr_match(struct mac80211_hwsim_data *data,
const u8 *addr)
{
struct mac80211_hwsim_addr_match_data md = {
.ret = false,
};
if (data->scanning && memcmp(addr, data->scan_addr, ETH_ALEN) == 0)
return true;
memcpy(md.addr, addr, ETH_ALEN);
ieee80211_iterate_active_interfaces_atomic(data->hw,
IEEE80211_IFACE_ITER_NORMAL,
mac80211_hwsim_addr_iter,
&md);
return md.ret;
}
static bool hwsim_ps_rx_ok(struct mac80211_hwsim_data *data,
struct sk_buff *skb)
{
switch (data->ps) {
case PS_DISABLED:
return true;
case PS_ENABLED:
return false;
case PS_AUTO_POLL:
/* TODO: accept (some) Beacons by default and other frames only
* if pending PS-Poll has been sent */
return true;
case PS_MANUAL_POLL:
/* Allow unicast frames to own address if there is a pending
* PS-Poll */
if (data->ps_poll_pending &&
mac80211_hwsim_addr_match(data, skb->data + 4)) {
data->ps_poll_pending = false;
return true;
}
return false;
}
return true;
}
static int hwsim_unicast_netgroup(struct mac80211_hwsim_data *data,
struct sk_buff *skb, int portid)
{
struct net *net;
bool found = false;
int res = -ENOENT;
rcu_read_lock();
for_each_net_rcu(net) {
if (data->netgroup == hwsim_net_get_netgroup(net)) {
res = genlmsg_unicast(net, skb, portid);
found = true;
break;
}
}
rcu_read_unlock();
if (!found)
nlmsg_free(skb);
return res;
}
static inline u16 trans_tx_rate_flags_ieee2hwsim(struct ieee80211_tx_rate *rate)
{
u16 result = 0;
if (rate->flags & IEEE80211_TX_RC_USE_RTS_CTS)
result |= MAC80211_HWSIM_TX_RC_USE_RTS_CTS;
if (rate->flags & IEEE80211_TX_RC_USE_CTS_PROTECT)
result |= MAC80211_HWSIM_TX_RC_USE_CTS_PROTECT;
if (rate->flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
result |= MAC80211_HWSIM_TX_RC_USE_SHORT_PREAMBLE;
if (rate->flags & IEEE80211_TX_RC_MCS)
result |= MAC80211_HWSIM_TX_RC_MCS;
if (rate->flags & IEEE80211_TX_RC_GREEN_FIELD)
result |= MAC80211_HWSIM_TX_RC_GREEN_FIELD;
if (rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
result |= MAC80211_HWSIM_TX_RC_40_MHZ_WIDTH;
if (rate->flags & IEEE80211_TX_RC_DUP_DATA)
result |= MAC80211_HWSIM_TX_RC_DUP_DATA;
if (rate->flags & IEEE80211_TX_RC_SHORT_GI)
result |= MAC80211_HWSIM_TX_RC_SHORT_GI;
if (rate->flags & IEEE80211_TX_RC_VHT_MCS)
result |= MAC80211_HWSIM_TX_RC_VHT_MCS;
if (rate->flags & IEEE80211_TX_RC_80_MHZ_WIDTH)
result |= MAC80211_HWSIM_TX_RC_80_MHZ_WIDTH;
if (rate->flags & IEEE80211_TX_RC_160_MHZ_WIDTH)
result |= MAC80211_HWSIM_TX_RC_160_MHZ_WIDTH;
return result;
}
static void mac80211_hwsim_tx_frame_nl(struct ieee80211_hw *hw,
struct sk_buff *my_skb,
int dst_portid)
{
struct sk_buff *skb;
struct mac80211_hwsim_data *data = hw->priv;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) my_skb->data;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(my_skb);
void *msg_head;
unsigned int hwsim_flags = 0;
int i;
struct hwsim_tx_rate tx_attempts[IEEE80211_TX_MAX_RATES];
struct hwsim_tx_rate_flag tx_attempts_flags[IEEE80211_TX_MAX_RATES];
uintptr_t cookie;
if (data->ps != PS_DISABLED)
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
/* If the queue contains MAX_QUEUE skb's drop some */
if (skb_queue_len(&data->pending) >= MAX_QUEUE) {
/* Droping until WARN_QUEUE level */
while (skb_queue_len(&data->pending) >= WARN_QUEUE) {
ieee80211_free_txskb(hw, skb_dequeue(&data->pending));
data->tx_dropped++;
}
}
skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (skb == NULL)
goto nla_put_failure;
msg_head = genlmsg_put(skb, 0, 0, &hwsim_genl_family, 0,
HWSIM_CMD_FRAME);
if (msg_head == NULL) {
pr_debug("mac80211_hwsim: problem with msg_head\n");
goto nla_put_failure;
}
if (nla_put(skb, HWSIM_ATTR_ADDR_TRANSMITTER,
ETH_ALEN, data->addresses[1].addr))
goto nla_put_failure;
/* We get the skb->data */
if (nla_put(skb, HWSIM_ATTR_FRAME, my_skb->len, my_skb->data))
goto nla_put_failure;
/* We get the flags for this transmission, and we translate them to
wmediumd flags */
if (info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS)
hwsim_flags |= HWSIM_TX_CTL_REQ_TX_STATUS;
if (info->flags & IEEE80211_TX_CTL_NO_ACK)
hwsim_flags |= HWSIM_TX_CTL_NO_ACK;
if (nla_put_u32(skb, HWSIM_ATTR_FLAGS, hwsim_flags))
goto nla_put_failure;
if (nla_put_u32(skb, HWSIM_ATTR_FREQ, data->channel->center_freq))
goto nla_put_failure;
/* We get the tx control (rate and retries) info*/
for (i = 0; i < IEEE80211_TX_MAX_RATES; i++) {
tx_attempts[i].idx = info->status.rates[i].idx;
tx_attempts_flags[i].idx = info->status.rates[i].idx;
tx_attempts[i].count = info->status.rates[i].count;
tx_attempts_flags[i].flags =
trans_tx_rate_flags_ieee2hwsim(
&info->status.rates[i]);
}
if (nla_put(skb, HWSIM_ATTR_TX_INFO,
sizeof(struct hwsim_tx_rate)*IEEE80211_TX_MAX_RATES,
tx_attempts))
goto nla_put_failure;
if (nla_put(skb, HWSIM_ATTR_TX_INFO_FLAGS,
sizeof(struct hwsim_tx_rate_flag) * IEEE80211_TX_MAX_RATES,
tx_attempts_flags))
goto nla_put_failure;
/* We create a cookie to identify this skb */
data->pending_cookie++;
cookie = data->pending_cookie;
info->rate_driver_data[0] = (void *)cookie;
if (nla_put_u64_64bit(skb, HWSIM_ATTR_COOKIE, cookie, HWSIM_ATTR_PAD))
goto nla_put_failure;
genlmsg_end(skb, msg_head);
if (hwsim_unicast_netgroup(data, skb, dst_portid))
goto err_free_txskb;
/* Enqueue the packet */
skb_queue_tail(&data->pending, my_skb);
data->tx_pkts++;
data->tx_bytes += my_skb->len;
return;
nla_put_failure:
nlmsg_free(skb);
err_free_txskb:
pr_debug("mac80211_hwsim: error occurred in %s\n", __func__);
ieee80211_free_txskb(hw, my_skb);
data->tx_failed++;
}
static bool hwsim_chans_compat(struct ieee80211_channel *c1,
struct ieee80211_channel *c2)
{
if (!c1 || !c2)
return false;
return c1->center_freq == c2->center_freq;
}
struct tx_iter_data {
struct ieee80211_channel *channel;
bool receive;
};
static void mac80211_hwsim_tx_iter(void *_data, u8 *addr,
struct ieee80211_vif *vif)
{
struct tx_iter_data *data = _data;
if (!vif->chanctx_conf)
return;
if (!hwsim_chans_compat(data->channel,
rcu_dereference(vif->chanctx_conf)->def.chan))
return;
data->receive = true;
}
static void mac80211_hwsim_add_vendor_rtap(struct sk_buff *skb)
{
/*
* To enable this code, #define the HWSIM_RADIOTAP_OUI,
* e.g. like this:
* #define HWSIM_RADIOTAP_OUI "\x02\x00\x00"
* (but you should use a valid OUI, not that)
*
* If anyone wants to 'donate' a radiotap OUI/subns code
* please send a patch removing this #ifdef and changing
* the values accordingly.
*/
#ifdef HWSIM_RADIOTAP_OUI
struct ieee80211_vendor_radiotap *rtap;
/*
* Note that this code requires the headroom in the SKB
* that was allocated earlier.
*/
rtap = skb_push(skb, sizeof(*rtap) + 8 + 4);
rtap->oui[0] = HWSIM_RADIOTAP_OUI[0];
rtap->oui[1] = HWSIM_RADIOTAP_OUI[1];
rtap->oui[2] = HWSIM_RADIOTAP_OUI[2];
rtap->subns = 127;
/*
* Radiotap vendor namespaces can (and should) also be
* split into fields by using the standard radiotap
* presence bitmap mechanism. Use just BIT(0) here for
* the presence bitmap.
*/
rtap->present = BIT(0);
/* We have 8 bytes of (dummy) data */
rtap->len = 8;
/* For testing, also require it to be aligned */
rtap->align = 8;
/* And also test that padding works, 4 bytes */
rtap->pad = 4;
/* push the data */
memcpy(rtap->data, "ABCDEFGH", 8);
/* make sure to clear padding, mac80211 doesn't */
memset(rtap->data + 8, 0, 4);
IEEE80211_SKB_RXCB(skb)->flag |= RX_FLAG_RADIOTAP_VENDOR_DATA;
#endif
}
static bool mac80211_hwsim_tx_frame_no_nl(struct ieee80211_hw *hw,
struct sk_buff *skb,
struct ieee80211_channel *chan)
{
struct mac80211_hwsim_data *data = hw->priv, *data2;
bool ack = false;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_rx_status rx_status;
u64 now;
memset(&rx_status, 0, sizeof(rx_status));
rx_status.flag |= RX_FLAG_MACTIME_START;
rx_status.freq = chan->center_freq;
rx_status.band = chan->band;
if (info->control.rates[0].flags & IEEE80211_TX_RC_VHT_MCS) {
rx_status.rate_idx =
ieee80211_rate_get_vht_mcs(&info->control.rates[0]);
rx_status.nss =
ieee80211_rate_get_vht_nss(&info->control.rates[0]);
rx_status.encoding = RX_ENC_VHT;
} else {
rx_status.rate_idx = info->control.rates[0].idx;
if (info->control.rates[0].flags & IEEE80211_TX_RC_MCS)
rx_status.encoding = RX_ENC_HT;
}
if (info->control.rates[0].flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
rx_status.bw = RATE_INFO_BW_40;
else if (info->control.rates[0].flags & IEEE80211_TX_RC_80_MHZ_WIDTH)
rx_status.bw = RATE_INFO_BW_80;
else if (info->control.rates[0].flags & IEEE80211_TX_RC_160_MHZ_WIDTH)
rx_status.bw = RATE_INFO_BW_160;
else
rx_status.bw = RATE_INFO_BW_20;
if (info->control.rates[0].flags & IEEE80211_TX_RC_SHORT_GI)
rx_status.enc_flags |= RX_ENC_FLAG_SHORT_GI;
/* TODO: simulate real signal strength (and optional packet loss) */
rx_status.signal = -50;
if (info->control.vif)
rx_status.signal += info->control.vif->bss_conf.txpower;
if (data->ps != PS_DISABLED)
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
/* release the skb's source info */
skb_orphan(skb);
skb_dst_drop(skb);
skb->mark = 0;
secpath_reset(skb);
nf_reset(skb);
/*
* Get absolute mactime here so all HWs RX at the "same time", and
* absolute TX time for beacon mactime so the timestamp matches.
* Giving beacons a different mactime than non-beacons looks messy, but
* it helps the Toffset be exact and a ~10us mactime discrepancy
* probably doesn't really matter.
*/
if (ieee80211_is_beacon(hdr->frame_control) ||
ieee80211_is_probe_resp(hdr->frame_control))
now = data->abs_bcn_ts;
else
now = mac80211_hwsim_get_tsf_raw();
/* Copy skb to all enabled radios that are on the current frequency */
spin_lock(&hwsim_radio_lock);
list_for_each_entry(data2, &hwsim_radios, list) {
struct sk_buff *nskb;
struct tx_iter_data tx_iter_data = {
.receive = false,
.channel = chan,
};
if (data == data2)
continue;
if (!data2->started || (data2->idle && !data2->tmp_chan) ||
!hwsim_ps_rx_ok(data2, skb))
continue;
if (!(data->group & data2->group))
continue;
if (data->netgroup != data2->netgroup)
continue;
if (!hwsim_chans_compat(chan, data2->tmp_chan) &&
!hwsim_chans_compat(chan, data2->channel)) {
ieee80211_iterate_active_interfaces_atomic(
data2->hw, IEEE80211_IFACE_ITER_NORMAL,
mac80211_hwsim_tx_iter, &tx_iter_data);
if (!tx_iter_data.receive)
continue;
}
/*
* reserve some space for our vendor and the normal
* radiotap header, since we're copying anyway
*/
if (skb->len < PAGE_SIZE && paged_rx) {
struct page *page = alloc_page(GFP_ATOMIC);
if (!page)
continue;
nskb = dev_alloc_skb(128);
if (!nskb) {
__free_page(page);
continue;
}
memcpy(page_address(page), skb->data, skb->len);
skb_add_rx_frag(nskb, 0, page, 0, skb->len, skb->len);
} else {
nskb = skb_copy(skb, GFP_ATOMIC);
if (!nskb)
continue;
}
if (mac80211_hwsim_addr_match(data2, hdr->addr1))
ack = true;
rx_status.mactime = now + data2->tsf_offset;
memcpy(IEEE80211_SKB_RXCB(nskb), &rx_status, sizeof(rx_status));
mac80211_hwsim_add_vendor_rtap(nskb);
data2->rx_pkts++;
data2->rx_bytes += nskb->len;
ieee80211_rx_irqsafe(data2->hw, nskb);
}
spin_unlock(&hwsim_radio_lock);
return ack;
}
static void mac80211_hwsim_tx(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control,
struct sk_buff *skb)
{
struct mac80211_hwsim_data *data = hw->priv;
struct ieee80211_tx_info *txi = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (void *)skb->data;
struct ieee80211_chanctx_conf *chanctx_conf;
struct ieee80211_channel *channel;
bool ack;
u32 _portid;
if (WARN_ON(skb->len < 10)) {
/* Should not happen; just a sanity check for addr1 use */
ieee80211_free_txskb(hw, skb);
return;
}
if (!data->use_chanctx) {
channel = data->channel;
} else if (txi->hw_queue == 4) {
channel = data->tmp_chan;
} else {
chanctx_conf = rcu_dereference(txi->control.vif->chanctx_conf);
if (chanctx_conf)
channel = chanctx_conf->def.chan;
else
channel = NULL;
}
if (WARN(!channel, "TX w/o channel - queue = %d\n", txi->hw_queue)) {
ieee80211_free_txskb(hw, skb);
return;
}
if (data->idle && !data->tmp_chan) {
wiphy_dbg(hw->wiphy, "Trying to TX when idle - reject\n");
ieee80211_free_txskb(hw, skb);
return;
}
if (txi->control.vif)
hwsim_check_magic(txi->control.vif);
if (control->sta)
hwsim_check_sta_magic(control->sta);
if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE))
ieee80211_get_tx_rates(txi->control.vif, control->sta, skb,
txi->control.rates,
ARRAY_SIZE(txi->control.rates));
if (skb->len >= 24 + 8 &&
ieee80211_is_probe_resp(hdr->frame_control)) {
/* fake header transmission time */
struct ieee80211_mgmt *mgmt;
struct ieee80211_rate *txrate;
u64 ts;
mgmt = (struct ieee80211_mgmt *)skb->data;
txrate = ieee80211_get_tx_rate(hw, txi);
ts = mac80211_hwsim_get_tsf_raw();
mgmt->u.probe_resp.timestamp =
cpu_to_le64(ts + data->tsf_offset +
24 * 8 * 10 / txrate->bitrate);
}
mac80211_hwsim_monitor_rx(hw, skb, channel);
/* wmediumd mode check */
_portid = READ_ONCE(data->wmediumd);
if (_portid)
return mac80211_hwsim_tx_frame_nl(hw, skb, _portid);
/* NO wmediumd detected, perfect medium simulation */
data->tx_pkts++;
data->tx_bytes += skb->len;
ack = mac80211_hwsim_tx_frame_no_nl(hw, skb, channel);
if (ack && skb->len >= 16)
mac80211_hwsim_monitor_ack(channel, hdr->addr2);
ieee80211_tx_info_clear_status(txi);
/* frame was transmitted at most favorable rate at first attempt */
txi->control.rates[0].count = 1;
txi->control.rates[1].idx = -1;
if (!(txi->flags & IEEE80211_TX_CTL_NO_ACK) && ack)
txi->flags |= IEEE80211_TX_STAT_ACK;
ieee80211_tx_status_irqsafe(hw, skb);
}
static int mac80211_hwsim_start(struct ieee80211_hw *hw)
{
struct mac80211_hwsim_data *data = hw->priv;
wiphy_dbg(hw->wiphy, "%s\n", __func__);
data->started = true;
return 0;
}
static void mac80211_hwsim_stop(struct ieee80211_hw *hw)
{
struct mac80211_hwsim_data *data = hw->priv;
data->started = false;
tasklet_hrtimer_cancel(&data->beacon_timer);
wiphy_dbg(hw->wiphy, "%s\n", __func__);
}
static int mac80211_hwsim_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
wiphy_dbg(hw->wiphy, "%s (type=%d mac_addr=%pM)\n",
__func__, ieee80211_vif_type_p2p(vif),
vif->addr);
hwsim_set_magic(vif);
vif->cab_queue = 0;
vif->hw_queue[IEEE80211_AC_VO] = 0;
vif->hw_queue[IEEE80211_AC_VI] = 1;
vif->hw_queue[IEEE80211_AC_BE] = 2;
vif->hw_queue[IEEE80211_AC_BK] = 3;
return 0;
}
static int mac80211_hwsim_change_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum nl80211_iftype newtype,
bool newp2p)
{
newtype = ieee80211_iftype_p2p(newtype, newp2p);
wiphy_dbg(hw->wiphy,
"%s (old type=%d, new type=%d, mac_addr=%pM)\n",
__func__, ieee80211_vif_type_p2p(vif),
newtype, vif->addr);
hwsim_check_magic(vif);
/*
* interface may change from non-AP to AP in
* which case this needs to be set up again
*/
vif->cab_queue = 0;
return 0;
}
static void mac80211_hwsim_remove_interface(
struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
wiphy_dbg(hw->wiphy, "%s (type=%d mac_addr=%pM)\n",
__func__, ieee80211_vif_type_p2p(vif),
vif->addr);
hwsim_check_magic(vif);
hwsim_clear_magic(vif);
}
static void mac80211_hwsim_tx_frame(struct ieee80211_hw *hw,
struct sk_buff *skb,
struct ieee80211_channel *chan)
{
struct mac80211_hwsim_data *data = hw->priv;
u32 _pid = READ_ONCE(data->wmediumd);
if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE)) {
struct ieee80211_tx_info *txi = IEEE80211_SKB_CB(skb);
ieee80211_get_tx_rates(txi->control.vif, NULL, skb,
txi->control.rates,
ARRAY_SIZE(txi->control.rates));
}
mac80211_hwsim_monitor_rx(hw, skb, chan);
if (_pid)
return mac80211_hwsim_tx_frame_nl(hw, skb, _pid);
mac80211_hwsim_tx_frame_no_nl(hw, skb, chan);
dev_kfree_skb(skb);
}
static void mac80211_hwsim_beacon_tx(void *arg, u8 *mac,
struct ieee80211_vif *vif)
{
struct mac80211_hwsim_data *data = arg;
struct ieee80211_hw *hw = data->hw;
struct ieee80211_tx_info *info;
struct ieee80211_rate *txrate;
struct ieee80211_mgmt *mgmt;
struct sk_buff *skb;
hwsim_check_magic(vif);
if (vif->type != NL80211_IFTYPE_AP &&
vif->type != NL80211_IFTYPE_MESH_POINT &&
vif->type != NL80211_IFTYPE_ADHOC)
return;
skb = ieee80211_beacon_get(hw, vif);
if (skb == NULL)
return;
info = IEEE80211_SKB_CB(skb);
if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE))
ieee80211_get_tx_rates(vif, NULL, skb,
info->control.rates,
ARRAY_SIZE(info->control.rates));
txrate = ieee80211_get_tx_rate(hw, info);
mgmt = (struct ieee80211_mgmt *) skb->data;
/* fake header transmission time */
data->abs_bcn_ts = mac80211_hwsim_get_tsf_raw();
mgmt->u.beacon.timestamp = cpu_to_le64(data->abs_bcn_ts +
data->tsf_offset +
24 * 8 * 10 / txrate->bitrate);
mac80211_hwsim_tx_frame(hw, skb,
rcu_dereference(vif->chanctx_conf)->def.chan);
if (vif->csa_active && ieee80211_csa_is_complete(vif))
ieee80211_csa_finish(vif);
}
static enum hrtimer_restart
mac80211_hwsim_beacon(struct hrtimer *timer)
{
struct mac80211_hwsim_data *data =
container_of(timer, struct mac80211_hwsim_data,
beacon_timer.timer);
struct ieee80211_hw *hw = data->hw;
u64 bcn_int = data->beacon_int;
ktime_t next_bcn;
if (!data->started)
goto out;
ieee80211_iterate_active_interfaces_atomic(
hw, IEEE80211_IFACE_ITER_NORMAL,
mac80211_hwsim_beacon_tx, data);
/* beacon at new TBTT + beacon interval */
if (data->bcn_delta) {
bcn_int -= data->bcn_delta;
data->bcn_delta = 0;
}
next_bcn = ktime_add(hrtimer_get_expires(timer),
ns_to_ktime(bcn_int * 1000));
tasklet_hrtimer_start(&data->beacon_timer, next_bcn, HRTIMER_MODE_ABS);
out:
return HRTIMER_NORESTART;
}
static const char * const hwsim_chanwidths[] = {
[NL80211_CHAN_WIDTH_20_NOHT] = "noht",
[NL80211_CHAN_WIDTH_20] = "ht20",
[NL80211_CHAN_WIDTH_40] = "ht40",
[NL80211_CHAN_WIDTH_80] = "vht80",
[NL80211_CHAN_WIDTH_80P80] = "vht80p80",
[NL80211_CHAN_WIDTH_160] = "vht160",
};
static int mac80211_hwsim_config(struct ieee80211_hw *hw, u32 changed)
{
struct mac80211_hwsim_data *data = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
static const char *smps_modes[IEEE80211_SMPS_NUM_MODES] = {
[IEEE80211_SMPS_AUTOMATIC] = "auto",
[IEEE80211_SMPS_OFF] = "off",
[IEEE80211_SMPS_STATIC] = "static",
[IEEE80211_SMPS_DYNAMIC] = "dynamic",
};
int idx;
if (conf->chandef.chan)
wiphy_dbg(hw->wiphy,
"%s (freq=%d(%d - %d)/%s idle=%d ps=%d smps=%s)\n",
__func__,
conf->chandef.chan->center_freq,
conf->chandef.center_freq1,
conf->chandef.center_freq2,
hwsim_chanwidths[conf->chandef.width],
!!(conf->flags & IEEE80211_CONF_IDLE),
!!(conf->flags & IEEE80211_CONF_PS),
smps_modes[conf->smps_mode]);
else
wiphy_dbg(hw->wiphy,
"%s (freq=0 idle=%d ps=%d smps=%s)\n",
__func__,
!!(conf->flags & IEEE80211_CONF_IDLE),
!!(conf->flags & IEEE80211_CONF_PS),
smps_modes[conf->smps_mode]);
data->idle = !!(conf->flags & IEEE80211_CONF_IDLE);
WARN_ON(conf->chandef.chan && data->use_chanctx);
mutex_lock(&data->mutex);
if (data->scanning && conf->chandef.chan) {
for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) {
if (data->survey_data[idx].channel == data->channel) {
data->survey_data[idx].start =
data->survey_data[idx].next_start;
data->survey_data[idx].end = jiffies;
break;
}
}
data->channel = conf->chandef.chan;
for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) {
if (data->survey_data[idx].channel &&
data->survey_data[idx].channel != data->channel)
continue;
data->survey_data[idx].channel = data->channel;
data->survey_data[idx].next_start = jiffies;
break;
}
} else {
data->channel = conf->chandef.chan;
}
mutex_unlock(&data->mutex);
if (!data->started || !data->beacon_int)
tasklet_hrtimer_cancel(&data->beacon_timer);
else if (!hrtimer_is_queued(&data->beacon_timer.timer)) {
u64 tsf = mac80211_hwsim_get_tsf(hw, NULL);
u32 bcn_int = data->beacon_int;
u64 until_tbtt = bcn_int - do_div(tsf, bcn_int);
tasklet_hrtimer_start(&data->beacon_timer,
ns_to_ktime(until_tbtt * 1000),
HRTIMER_MODE_REL);
}
return 0;
}
static void mac80211_hwsim_configure_filter(struct ieee80211_hw *hw,
unsigned int changed_flags,
unsigned int *total_flags,u64 multicast)
{
struct mac80211_hwsim_data *data = hw->priv;
wiphy_dbg(hw->wiphy, "%s\n", __func__);
data->rx_filter = 0;
if (*total_flags & FIF_ALLMULTI)
data->rx_filter |= FIF_ALLMULTI;
*total_flags = data->rx_filter;
}
static void mac80211_hwsim_bcn_en_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
unsigned int *count = data;
struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
if (vp->bcn_en)
(*count)++;
}
static void mac80211_hwsim_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *info,
u32 changed)
{
struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
struct mac80211_hwsim_data *data = hw->priv;
hwsim_check_magic(vif);
wiphy_dbg(hw->wiphy, "%s(changed=0x%x vif->addr=%pM)\n",
__func__, changed, vif->addr);
if (changed & BSS_CHANGED_BSSID) {
wiphy_dbg(hw->wiphy, "%s: BSSID changed: %pM\n",
__func__, info->bssid);
memcpy(vp->bssid, info->bssid, ETH_ALEN);
}
if (changed & BSS_CHANGED_ASSOC) {
wiphy_dbg(hw->wiphy, " ASSOC: assoc=%d aid=%d\n",
info->assoc, info->aid);
vp->assoc = info->assoc;
vp->aid = info->aid;
}
if (changed & BSS_CHANGED_BEACON_ENABLED) {
wiphy_dbg(hw->wiphy, " BCN EN: %d (BI=%u)\n",
info->enable_beacon, info->beacon_int);
vp->bcn_en = info->enable_beacon;
if (data->started &&
!hrtimer_is_queued(&data->beacon_timer.timer) &&
info->enable_beacon) {
u64 tsf, until_tbtt;
u32 bcn_int;
data->beacon_int = info->beacon_int * 1024;
tsf = mac80211_hwsim_get_tsf(hw, vif);
bcn_int = data->beacon_int;
until_tbtt = bcn_int - do_div(tsf, bcn_int);
tasklet_hrtimer_start(&data->beacon_timer,
ns_to_ktime(until_tbtt * 1000),
HRTIMER_MODE_REL);
} else if (!info->enable_beacon) {
unsigned int count = 0;
ieee80211_iterate_active_interfaces_atomic(
data->hw, IEEE80211_IFACE_ITER_NORMAL,
mac80211_hwsim_bcn_en_iter, &count);
wiphy_dbg(hw->wiphy, " beaconing vifs remaining: %u",
count);
if (count == 0) {
tasklet_hrtimer_cancel(&data->beacon_timer);
data->beacon_int = 0;
}
}
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
wiphy_dbg(hw->wiphy, " ERP_CTS_PROT: %d\n",
info->use_cts_prot);
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
wiphy_dbg(hw->wiphy, " ERP_PREAMBLE: %d\n",
info->use_short_preamble);
}
if (changed & BSS_CHANGED_ERP_SLOT) {
wiphy_dbg(hw->wiphy, " ERP_SLOT: %d\n", info->use_short_slot);
}
if (changed & BSS_CHANGED_HT) {
wiphy_dbg(hw->wiphy, " HT: op_mode=0x%x\n",
info->ht_operation_mode);
}
if (changed & BSS_CHANGED_BASIC_RATES) {
wiphy_dbg(hw->wiphy, " BASIC_RATES: 0x%llx\n",
(unsigned long long) info->basic_rates);
}
if (changed & BSS_CHANGED_TXPOWER)
wiphy_dbg(hw->wiphy, " TX Power: %d dBm\n", info->txpower);
}
static int mac80211_hwsim_sta_add(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
hwsim_check_magic(vif);
hwsim_set_sta_magic(sta);
return 0;
}
static int mac80211_hwsim_sta_remove(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
hwsim_check_magic(vif);
hwsim_clear_sta_magic(sta);
return 0;
}
static void mac80211_hwsim_sta_notify(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum sta_notify_cmd cmd,
struct ieee80211_sta *sta)
{
hwsim_check_magic(vif);
switch (cmd) {
case STA_NOTIFY_SLEEP:
case STA_NOTIFY_AWAKE:
/* TODO: make good use of these flags */
break;
default:
WARN(1, "Invalid sta notify: %d\n", cmd);
break;
}
}
static int mac80211_hwsim_set_tim(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
bool set)
{
hwsim_check_sta_magic(sta);
return 0;
}
static int mac80211_hwsim_conf_tx(
struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *params)
{
wiphy_dbg(hw->wiphy,
"%s (queue=%d txop=%d cw_min=%d cw_max=%d aifs=%d)\n",
__func__, queue,
params->txop, params->cw_min,
params->cw_max, params->aifs);
return 0;
}
static int mac80211_hwsim_get_survey(struct ieee80211_hw *hw, int idx,
struct survey_info *survey)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
if (idx < 0 || idx >= ARRAY_SIZE(hwsim->survey_data))
return -ENOENT;
mutex_lock(&hwsim->mutex);
survey->channel = hwsim->survey_data[idx].channel;
if (!survey->channel) {
mutex_unlock(&hwsim->mutex);
return -ENOENT;
}
/*
* Magically conjured dummy values --- this is only ok for simulated hardware.
*
* A real driver which cannot determine real values noise MUST NOT
* report any, especially not a magically conjured ones :-)
*/
survey->filled = SURVEY_INFO_NOISE_DBM |
SURVEY_INFO_TIME |
SURVEY_INFO_TIME_BUSY;
survey->noise = -92;
survey->time =
jiffies_to_msecs(hwsim->survey_data[idx].end -
hwsim->survey_data[idx].start);
/* report 12.5% of channel time is used */
survey->time_busy = survey->time/8;
mutex_unlock(&hwsim->mutex);
return 0;
}
#ifdef CONFIG_NL80211_TESTMODE
/*
* This section contains example code for using netlink
* attributes with the testmode command in nl80211.
*/
/* These enums need to be kept in sync with userspace */
enum hwsim_testmode_attr {
__HWSIM_TM_ATTR_INVALID = 0,
HWSIM_TM_ATTR_CMD = 1,
HWSIM_TM_ATTR_PS = 2,
/* keep last */
__HWSIM_TM_ATTR_AFTER_LAST,
HWSIM_TM_ATTR_MAX = __HWSIM_TM_ATTR_AFTER_LAST - 1
};
enum hwsim_testmode_cmd {
HWSIM_TM_CMD_SET_PS = 0,
HWSIM_TM_CMD_GET_PS = 1,
HWSIM_TM_CMD_STOP_QUEUES = 2,
HWSIM_TM_CMD_WAKE_QUEUES = 3,
};
static const struct nla_policy hwsim_testmode_policy[HWSIM_TM_ATTR_MAX + 1] = {
[HWSIM_TM_ATTR_CMD] = { .type = NLA_U32 },
[HWSIM_TM_ATTR_PS] = { .type = NLA_U32 },
};
static int mac80211_hwsim_testmode_cmd(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
void *data, int len)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
struct nlattr *tb[HWSIM_TM_ATTR_MAX + 1];
struct sk_buff *skb;
int err, ps;
err = nla_parse(tb, HWSIM_TM_ATTR_MAX, data, len,
hwsim_testmode_policy, NULL);
if (err)
return err;
if (!tb[HWSIM_TM_ATTR_CMD])
return -EINVAL;
switch (nla_get_u32(tb[HWSIM_TM_ATTR_CMD])) {
case HWSIM_TM_CMD_SET_PS:
if (!tb[HWSIM_TM_ATTR_PS])
return -EINVAL;
ps = nla_get_u32(tb[HWSIM_TM_ATTR_PS]);
return hwsim_fops_ps_write(hwsim, ps);
case HWSIM_TM_CMD_GET_PS:
skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy,
nla_total_size(sizeof(u32)));
if (!skb)
return -ENOMEM;
if (nla_put_u32(skb, HWSIM_TM_ATTR_PS, hwsim->ps))
goto nla_put_failure;
return cfg80211_testmode_reply(skb);
case HWSIM_TM_CMD_STOP_QUEUES:
ieee80211_stop_queues(hw);
return 0;
case HWSIM_TM_CMD_WAKE_QUEUES:
ieee80211_wake_queues(hw);
return 0;
default:
return -EOPNOTSUPP;
}
nla_put_failure:
kfree_skb(skb);
return -ENOBUFS;
}
#endif
static int mac80211_hwsim_ampdu_action(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_ampdu_params *params)
{
struct ieee80211_sta *sta = params->sta;
enum ieee80211_ampdu_mlme_action action = params->action;
u16 tid = params->tid;
switch (action) {
case IEEE80211_AMPDU_TX_START:
ieee80211_start_tx_ba_cb_irqsafe(vif, sta->addr, tid);
break;
case IEEE80211_AMPDU_TX_STOP_CONT:
case IEEE80211_AMPDU_TX_STOP_FLUSH:
case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT:
ieee80211_stop_tx_ba_cb_irqsafe(vif, sta->addr, tid);
break;
case IEEE80211_AMPDU_TX_OPERATIONAL:
break;
case IEEE80211_AMPDU_RX_START:
case IEEE80211_AMPDU_RX_STOP:
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static void mac80211_hwsim_flush(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
u32 queues, bool drop)
{
/* Not implemented, queues only on kernel side */
}
static void hw_scan_work(struct work_struct *work)
{
struct mac80211_hwsim_data *hwsim =
container_of(work, struct mac80211_hwsim_data, hw_scan.work);
struct cfg80211_scan_request *req = hwsim->hw_scan_request;
int dwell, i;
mutex_lock(&hwsim->mutex);
if (hwsim->scan_chan_idx >= req->n_channels) {
struct cfg80211_scan_info info = {
.aborted = false,
};
wiphy_dbg(hwsim->hw->wiphy, "hw scan complete\n");
ieee80211_scan_completed(hwsim->hw, &info);
hwsim->hw_scan_request = NULL;
hwsim->hw_scan_vif = NULL;
hwsim->tmp_chan = NULL;
mutex_unlock(&hwsim->mutex);
return;
}
wiphy_dbg(hwsim->hw->wiphy, "hw scan %d MHz\n",
req->channels[hwsim->scan_chan_idx]->center_freq);
hwsim->tmp_chan = req->channels[hwsim->scan_chan_idx];
if (hwsim->tmp_chan->flags & (IEEE80211_CHAN_NO_IR |
IEEE80211_CHAN_RADAR) ||
!req->n_ssids) {
dwell = 120;
} else {
dwell = 30;
/* send probes */
for (i = 0; i < req->n_ssids; i++) {
struct sk_buff *probe;
struct ieee80211_mgmt *mgmt;
probe = ieee80211_probereq_get(hwsim->hw,
hwsim->scan_addr,
req->ssids[i].ssid,
req->ssids[i].ssid_len,
req->ie_len);
if (!probe)
continue;
mgmt = (struct ieee80211_mgmt *) probe->data;
memcpy(mgmt->da, req->bssid, ETH_ALEN);
memcpy(mgmt->bssid, req->bssid, ETH_ALEN);
if (req->ie_len)
skb_put_data(probe, req->ie, req->ie_len);
local_bh_disable();
mac80211_hwsim_tx_frame(hwsim->hw, probe,
hwsim->tmp_chan);
local_bh_enable();
}
}
ieee80211_queue_delayed_work(hwsim->hw, &hwsim->hw_scan,
msecs_to_jiffies(dwell));
hwsim->survey_data[hwsim->scan_chan_idx].channel = hwsim->tmp_chan;
hwsim->survey_data[hwsim->scan_chan_idx].start = jiffies;
hwsim->survey_data[hwsim->scan_chan_idx].end =
jiffies + msecs_to_jiffies(dwell);
hwsim->scan_chan_idx++;
mutex_unlock(&hwsim->mutex);
}
static int mac80211_hwsim_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_scan_request *hw_req)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
struct cfg80211_scan_request *req = &hw_req->req;
mutex_lock(&hwsim->mutex);
if (WARN_ON(hwsim->tmp_chan || hwsim->hw_scan_request)) {
mutex_unlock(&hwsim->mutex);
return -EBUSY;
}
hwsim->hw_scan_request = req;
hwsim->hw_scan_vif = vif;
hwsim->scan_chan_idx = 0;
if (req->flags & NL80211_SCAN_FLAG_RANDOM_ADDR)
get_random_mask_addr(hwsim->scan_addr,
hw_req->req.mac_addr,
hw_req->req.mac_addr_mask);
else
memcpy(hwsim->scan_addr, vif->addr, ETH_ALEN);
memset(hwsim->survey_data, 0, sizeof(hwsim->survey_data));
mutex_unlock(&hwsim->mutex);
wiphy_dbg(hw->wiphy, "hwsim hw_scan request\n");
ieee80211_queue_delayed_work(hwsim->hw, &hwsim->hw_scan, 0);
return 0;
}
static void mac80211_hwsim_cancel_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
struct cfg80211_scan_info info = {
.aborted = true,
};
wiphy_dbg(hw->wiphy, "hwsim cancel_hw_scan\n");
cancel_delayed_work_sync(&hwsim->hw_scan);
mutex_lock(&hwsim->mutex);
ieee80211_scan_completed(hwsim->hw, &info);
hwsim->tmp_chan = NULL;
hwsim->hw_scan_request = NULL;
hwsim->hw_scan_vif = NULL;
mutex_unlock(&hwsim->mutex);
}
static void mac80211_hwsim_sw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const u8 *mac_addr)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
mutex_lock(&hwsim->mutex);
if (hwsim->scanning) {
pr_debug("two hwsim sw_scans detected!\n");
goto out;
}
pr_debug("hwsim sw_scan request, prepping stuff\n");
memcpy(hwsim->scan_addr, mac_addr, ETH_ALEN);
hwsim->scanning = true;
memset(hwsim->survey_data, 0, sizeof(hwsim->survey_data));
out:
mutex_unlock(&hwsim->mutex);
}
static void mac80211_hwsim_sw_scan_complete(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
mutex_lock(&hwsim->mutex);
pr_debug("hwsim sw_scan_complete\n");
hwsim->scanning = false;
eth_zero_addr(hwsim->scan_addr);
mutex_unlock(&hwsim->mutex);
}
static void hw_roc_start(struct work_struct *work)
{
struct mac80211_hwsim_data *hwsim =
container_of(work, struct mac80211_hwsim_data, roc_start.work);
mutex_lock(&hwsim->mutex);
wiphy_dbg(hwsim->hw->wiphy, "hwsim ROC begins\n");
hwsim->tmp_chan = hwsim->roc_chan;
ieee80211_ready_on_channel(hwsim->hw);
ieee80211_queue_delayed_work(hwsim->hw, &hwsim->roc_done,
msecs_to_jiffies(hwsim->roc_duration));
mutex_unlock(&hwsim->mutex);
}
static void hw_roc_done(struct work_struct *work)
{
struct mac80211_hwsim_data *hwsim =
container_of(work, struct mac80211_hwsim_data, roc_done.work);
mutex_lock(&hwsim->mutex);
ieee80211_remain_on_channel_expired(hwsim->hw);
hwsim->tmp_chan = NULL;
mutex_unlock(&hwsim->mutex);
wiphy_dbg(hwsim->hw->wiphy, "hwsim ROC expired\n");
}
static int mac80211_hwsim_roc(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_channel *chan,
int duration,
enum ieee80211_roc_type type)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
mutex_lock(&hwsim->mutex);
if (WARN_ON(hwsim->tmp_chan || hwsim->hw_scan_request)) {
mutex_unlock(&hwsim->mutex);
return -EBUSY;
}
hwsim->roc_chan = chan;
hwsim->roc_duration = duration;
mutex_unlock(&hwsim->mutex);
wiphy_dbg(hw->wiphy, "hwsim ROC (%d MHz, %d ms)\n",
chan->center_freq, duration);
ieee80211_queue_delayed_work(hw, &hwsim->roc_start, HZ/50);
return 0;
}
static int mac80211_hwsim_croc(struct ieee80211_hw *hw)
{
struct mac80211_hwsim_data *hwsim = hw->priv;
cancel_delayed_work_sync(&hwsim->roc_start);
cancel_delayed_work_sync(&hwsim->roc_done);
mutex_lock(&hwsim->mutex);
hwsim->tmp_chan = NULL;
mutex_unlock(&hwsim->mutex);
wiphy_dbg(hw->wiphy, "hwsim ROC canceled\n");
return 0;
}
static int mac80211_hwsim_add_chanctx(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *ctx)
{
hwsim_set_chanctx_magic(ctx);
wiphy_dbg(hw->wiphy,
"add channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n",
ctx->def.chan->center_freq, ctx->def.width,
ctx->def.center_freq1, ctx->def.center_freq2);
return 0;
}
static void mac80211_hwsim_remove_chanctx(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *ctx)
{
wiphy_dbg(hw->wiphy,
"remove channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n",
ctx->def.chan->center_freq, ctx->def.width,
ctx->def.center_freq1, ctx->def.center_freq2);
hwsim_check_chanctx_magic(ctx);
hwsim_clear_chanctx_magic(ctx);
}
static void mac80211_hwsim_change_chanctx(struct ieee80211_hw *hw,
struct ieee80211_chanctx_conf *ctx,
u32 changed)
{
hwsim_check_chanctx_magic(ctx);
wiphy_dbg(hw->wiphy,
"change channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n",
ctx->def.chan->center_freq, ctx->def.width,
ctx->def.center_freq1, ctx->def.center_freq2);
}
static int mac80211_hwsim_assign_vif_chanctx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_chanctx_conf *ctx)
{
hwsim_check_magic(vif);
hwsim_check_chanctx_magic(ctx);
return 0;
}
static void mac80211_hwsim_unassign_vif_chanctx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_chanctx_conf *ctx)
{
hwsim_check_magic(vif);
hwsim_check_chanctx_magic(ctx);
}
static const char mac80211_hwsim_gstrings_stats[][ETH_GSTRING_LEN] = {
"tx_pkts_nic",
"tx_bytes_nic",
"rx_pkts_nic",
"rx_bytes_nic",
"d_tx_dropped",
"d_tx_failed",
"d_ps_mode",
"d_group",
};
#define MAC80211_HWSIM_SSTATS_LEN ARRAY_SIZE(mac80211_hwsim_gstrings_stats)
static void mac80211_hwsim_get_et_strings(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
u32 sset, u8 *data)
{
if (sset == ETH_SS_STATS)
memcpy(data, *mac80211_hwsim_gstrings_stats,
sizeof(mac80211_hwsim_gstrings_stats));
}
static int mac80211_hwsim_get_et_sset_count(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, int sset)
{
if (sset == ETH_SS_STATS)
return MAC80211_HWSIM_SSTATS_LEN;
return 0;
}
static void mac80211_hwsim_get_et_stats(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ethtool_stats *stats, u64 *data)
{
struct mac80211_hwsim_data *ar = hw->priv;
int i = 0;
data[i++] = ar->tx_pkts;
data[i++] = ar->tx_bytes;
data[i++] = ar->rx_pkts;
data[i++] = ar->rx_bytes;
data[i++] = ar->tx_dropped;
data[i++] = ar->tx_failed;
data[i++] = ar->ps;
data[i++] = ar->group;
WARN_ON(i != MAC80211_HWSIM_SSTATS_LEN);
}
#define HWSIM_COMMON_OPS \
.tx = mac80211_hwsim_tx, \
.start = mac80211_hwsim_start, \
.stop = mac80211_hwsim_stop, \
.add_interface = mac80211_hwsim_add_interface, \
.change_interface = mac80211_hwsim_change_interface, \
.remove_interface = mac80211_hwsim_remove_interface, \
.config = mac80211_hwsim_config, \
.configure_filter = mac80211_hwsim_configure_filter, \
.bss_info_changed = mac80211_hwsim_bss_info_changed, \
.sta_add = mac80211_hwsim_sta_add, \
.sta_remove = mac80211_hwsim_sta_remove, \
.sta_notify = mac80211_hwsim_sta_notify, \
.set_tim = mac80211_hwsim_set_tim, \
.conf_tx = mac80211_hwsim_conf_tx, \
.get_survey = mac80211_hwsim_get_survey, \
CFG80211_TESTMODE_CMD(mac80211_hwsim_testmode_cmd) \
.ampdu_action = mac80211_hwsim_ampdu_action, \
.flush = mac80211_hwsim_flush, \
.get_tsf = mac80211_hwsim_get_tsf, \
.set_tsf = mac80211_hwsim_set_tsf, \
.get_et_sset_count = mac80211_hwsim_get_et_sset_count, \
.get_et_stats = mac80211_hwsim_get_et_stats, \
.get_et_strings = mac80211_hwsim_get_et_strings,
static const struct ieee80211_ops mac80211_hwsim_ops = {
HWSIM_COMMON_OPS
.sw_scan_start = mac80211_hwsim_sw_scan,
.sw_scan_complete = mac80211_hwsim_sw_scan_complete,
};
static const struct ieee80211_ops mac80211_hwsim_mchan_ops = {
HWSIM_COMMON_OPS
.hw_scan = mac80211_hwsim_hw_scan,
.cancel_hw_scan = mac80211_hwsim_cancel_hw_scan,
.sw_scan_start = NULL,
.sw_scan_complete = NULL,
.remain_on_channel = mac80211_hwsim_roc,
.cancel_remain_on_channel = mac80211_hwsim_croc,
.add_chanctx = mac80211_hwsim_add_chanctx,
.remove_chanctx = mac80211_hwsim_remove_chanctx,
.change_chanctx = mac80211_hwsim_change_chanctx,
.assign_vif_chanctx = mac80211_hwsim_assign_vif_chanctx,
.unassign_vif_chanctx = mac80211_hwsim_unassign_vif_chanctx,
};
struct hwsim_new_radio_params {
unsigned int channels;
const char *reg_alpha2;
const struct ieee80211_regdomain *regd;
bool reg_strict;
bool p2p_device;
bool use_chanctx;
bool destroy_on_close;
const char *hwname;
bool no_vif;
};
static void hwsim_mcast_config_msg(struct sk_buff *mcast_skb,
struct genl_info *info)
{
if (info)
genl_notify(&hwsim_genl_family, mcast_skb, info,
HWSIM_MCGRP_CONFIG, GFP_KERNEL);
else
genlmsg_multicast(&hwsim_genl_family, mcast_skb, 0,
HWSIM_MCGRP_CONFIG, GFP_KERNEL);
}
static int append_radio_msg(struct sk_buff *skb, int id,
struct hwsim_new_radio_params *param)
{
int ret;
ret = nla_put_u32(skb, HWSIM_ATTR_RADIO_ID, id);
if (ret < 0)
return ret;
if (param->channels) {
ret = nla_put_u32(skb, HWSIM_ATTR_CHANNELS, param->channels);
if (ret < 0)
return ret;
}
if (param->reg_alpha2) {
ret = nla_put(skb, HWSIM_ATTR_REG_HINT_ALPHA2, 2,
param->reg_alpha2);
if (ret < 0)
return ret;
}
if (param->regd) {
int i;
for (i = 0; i < ARRAY_SIZE(hwsim_world_regdom_custom); i++) {
if (hwsim_world_regdom_custom[i] != param->regd)
continue;
ret = nla_put_u32(skb, HWSIM_ATTR_REG_CUSTOM_REG, i);
if (ret < 0)
return ret;
break;
}
}
if (param->reg_strict) {
ret = nla_put_flag(skb, HWSIM_ATTR_REG_STRICT_REG);
if (ret < 0)
return ret;
}
if (param->p2p_device) {
ret = nla_put_flag(skb, HWSIM_ATTR_SUPPORT_P2P_DEVICE);
if (ret < 0)
return ret;
}
if (param->use_chanctx) {
ret = nla_put_flag(skb, HWSIM_ATTR_USE_CHANCTX);
if (ret < 0)
return ret;
}
if (param->hwname) {
ret = nla_put(skb, HWSIM_ATTR_RADIO_NAME,
strlen(param->hwname), param->hwname);
if (ret < 0)
return ret;
}
return 0;
}
static void hwsim_mcast_new_radio(int id, struct genl_info *info,
struct hwsim_new_radio_params *param)
{
struct sk_buff *mcast_skb;
void *data;
mcast_skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!mcast_skb)
return;
data = genlmsg_put(mcast_skb, 0, 0, &hwsim_genl_family, 0,
HWSIM_CMD_NEW_RADIO);
if (!data)
goto out_err;
if (append_radio_msg(mcast_skb, id, param) < 0)
goto out_err;
genlmsg_end(mcast_skb, data);
hwsim_mcast_config_msg(mcast_skb, info);
return;
out_err:
genlmsg_cancel(mcast_skb, data);
nlmsg_free(mcast_skb);
}
static int mac80211_hwsim_new_radio(struct genl_info *info,
struct hwsim_new_radio_params *param)
{
int err;
u8 addr[ETH_ALEN];
struct mac80211_hwsim_data *data;
struct ieee80211_hw *hw;
enum nl80211_band band;
const struct ieee80211_ops *ops = &mac80211_hwsim_ops;
struct net *net;
int idx;
if (WARN_ON(param->channels > 1 && !param->use_chanctx))
return -EINVAL;
spin_lock_bh(&hwsim_radio_lock);
idx = hwsim_radio_idx++;
spin_unlock_bh(&hwsim_radio_lock);
if (param->use_chanctx)
ops = &mac80211_hwsim_mchan_ops;
hw = ieee80211_alloc_hw_nm(sizeof(*data), ops, param->hwname);
if (!hw) {
pr_debug("mac80211_hwsim: ieee80211_alloc_hw failed\n");
err = -ENOMEM;
goto failed;
}
/* ieee80211_alloc_hw_nm may have used a default name */
param->hwname = wiphy_name(hw->wiphy);
if (info)
net = genl_info_net(info);
else
net = &init_net;
wiphy_net_set(hw->wiphy, net);
data = hw->priv;
data->hw = hw;
data->dev = device_create(hwsim_class, NULL, 0, hw, "hwsim%d", idx);
if (IS_ERR(data->dev)) {
printk(KERN_DEBUG
"mac80211_hwsim: device_create failed (%ld)\n",
PTR_ERR(data->dev));
err = -ENOMEM;
goto failed_drvdata;
}
data->dev->driver = &mac80211_hwsim_driver.driver;
err = device_bind_driver(data->dev);
if (err != 0) {
pr_debug("mac80211_hwsim: device_bind_driver failed (%d)\n",
err);
goto failed_bind;
}
skb_queue_head_init(&data->pending);
SET_IEEE80211_DEV(hw, data->dev);
eth_zero_addr(addr);
addr[0] = 0x02;
addr[3] = idx >> 8;
addr[4] = idx;
memcpy(data->addresses[0].addr, addr, ETH_ALEN);
memcpy(data->addresses[1].addr, addr, ETH_ALEN);
data->addresses[1].addr[0] |= 0x40;
hw->wiphy->n_addresses = 2;
hw->wiphy->addresses = data->addresses;
data->channels = param->channels;
data->use_chanctx = param->use_chanctx;
data->idx = idx;
data->destroy_on_close = param->destroy_on_close;
if (info)
data->portid = info->snd_portid;
if (data->use_chanctx) {
hw->wiphy->max_scan_ssids = 255;
hw->wiphy->max_scan_ie_len = IEEE80211_MAX_DATA_LEN;
hw->wiphy->max_remain_on_channel_duration = 1000;
hw->wiphy->iface_combinations = &data->if_combination;
if (param->p2p_device)
data->if_combination = hwsim_if_comb_p2p_dev[0];
else
data->if_combination = hwsim_if_comb[0];
hw->wiphy->n_iface_combinations = 1;
/* For channels > 1 DFS is not allowed */
data->if_combination.radar_detect_widths = 0;
data->if_combination.num_different_channels = data->channels;
} else if (param->p2p_device) {
hw->wiphy->iface_combinations = hwsim_if_comb_p2p_dev;
hw->wiphy->n_iface_combinations =
ARRAY_SIZE(hwsim_if_comb_p2p_dev);
} else {
hw->wiphy->iface_combinations = hwsim_if_comb;
hw->wiphy->n_iface_combinations = ARRAY_SIZE(hwsim_if_comb);
}
INIT_DELAYED_WORK(&data->roc_start, hw_roc_start);
INIT_DELAYED_WORK(&data->roc_done, hw_roc_done);
INIT_DELAYED_WORK(&data->hw_scan, hw_scan_work);
hw->queues = 5;
hw->offchannel_tx_hw_queue = 4;
hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_MESH_POINT);
if (param->p2p_device)
hw->wiphy->interface_modes |= BIT(NL80211_IFTYPE_P2P_DEVICE);
ieee80211_hw_set(hw, SUPPORT_FAST_XMIT);
ieee80211_hw_set(hw, CHANCTX_STA_CSA);
ieee80211_hw_set(hw, SUPPORTS_HT_CCK_RATES);
ieee80211_hw_set(hw, QUEUE_CONTROL);
ieee80211_hw_set(hw, WANT_MONITOR_VIF);
ieee80211_hw_set(hw, AMPDU_AGGREGATION);
ieee80211_hw_set(hw, MFP_CAPABLE);
ieee80211_hw_set(hw, SIGNAL_DBM);
ieee80211_hw_set(hw, TDLS_WIDER_BW);
if (rctbl)
ieee80211_hw_set(hw, SUPPORTS_RC_TABLE);
hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS |
WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL |
WIPHY_FLAG_AP_UAPSD |
WIPHY_FLAG_HAS_CHANNEL_SWITCH;
hw->wiphy->features |= NL80211_FEATURE_ACTIVE_MONITOR |
NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE |
NL80211_FEATURE_STATIC_SMPS |
NL80211_FEATURE_DYNAMIC_SMPS |
NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR;
wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_VHT_IBSS);
/* ask mac80211 to reserve space for magic */
hw->vif_data_size = sizeof(struct hwsim_vif_priv);
hw->sta_data_size = sizeof(struct hwsim_sta_priv);
hw->chanctx_data_size = sizeof(struct hwsim_chanctx_priv);
memcpy(data->channels_2ghz, hwsim_channels_2ghz,
sizeof(hwsim_channels_2ghz));
memcpy(data->channels_5ghz, hwsim_channels_5ghz,
sizeof(hwsim_channels_5ghz));
memcpy(data->rates, hwsim_rates, sizeof(hwsim_rates));
for (band = NL80211_BAND_2GHZ; band < NUM_NL80211_BANDS; band++) {
struct ieee80211_supported_band *sband = &data->bands[band];
switch (band) {
case NL80211_BAND_2GHZ:
sband->channels = data->channels_2ghz;
sband->n_channels = ARRAY_SIZE(hwsim_channels_2ghz);
sband->bitrates = data->rates;
sband->n_bitrates = ARRAY_SIZE(hwsim_rates);
break;
case NL80211_BAND_5GHZ:
sband->channels = data->channels_5ghz;
sband->n_channels = ARRAY_SIZE(hwsim_channels_5ghz);
sband->bitrates = data->rates + 4;
sband->n_bitrates = ARRAY_SIZE(hwsim_rates) - 4;
sband->vht_cap.vht_supported = true;
sband->vht_cap.cap =
IEEE80211_VHT_CAP_MAX_MPDU_LENGTH_11454 |
IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160_80PLUS80MHZ |
IEEE80211_VHT_CAP_RXLDPC |
IEEE80211_VHT_CAP_SHORT_GI_80 |
IEEE80211_VHT_CAP_SHORT_GI_160 |
IEEE80211_VHT_CAP_TXSTBC |
IEEE80211_VHT_CAP_RXSTBC_1 |
IEEE80211_VHT_CAP_RXSTBC_2 |
IEEE80211_VHT_CAP_RXSTBC_3 |
IEEE80211_VHT_CAP_RXSTBC_4 |
IEEE80211_VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_MASK;
sband->vht_cap.vht_mcs.rx_mcs_map =
cpu_to_le16(IEEE80211_VHT_MCS_SUPPORT_0_9 << 0 |
IEEE80211_VHT_MCS_SUPPORT_0_9 << 2 |
IEEE80211_VHT_MCS_SUPPORT_0_9 << 4 |
IEEE80211_VHT_MCS_SUPPORT_0_9 << 6 |
IEEE80211_VHT_MCS_SUPPORT_0_9 << 8 |
IEEE80211_VHT_MCS_SUPPORT_0_9 << 10 |
IEEE80211_VHT_MCS_SUPPORT_0_9 << 12 |
IEEE80211_VHT_MCS_SUPPORT_0_9 << 14);
sband->vht_cap.vht_mcs.tx_mcs_map =
sband->vht_cap.vht_mcs.rx_mcs_map;
break;
default:
continue;
}
sband->ht_cap.ht_supported = true;
sband->ht_cap.cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 |
IEEE80211_HT_CAP_GRN_FLD |
IEEE80211_HT_CAP_SGI_20 |
IEEE80211_HT_CAP_SGI_40 |
IEEE80211_HT_CAP_DSSSCCK40;
sband->ht_cap.ampdu_factor = 0x3;
sband->ht_cap.ampdu_density = 0x6;
memset(&sband->ht_cap.mcs, 0,
sizeof(sband->ht_cap.mcs));
sband->ht_cap.mcs.rx_mask[0] = 0xff;
sband->ht_cap.mcs.rx_mask[1] = 0xff;
sband->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
hw->wiphy->bands[band] = sband;
}
/* By default all radios belong to the first group */
data->group = 1;
mutex_init(&data->mutex);
data->netgroup = hwsim_net_get_netgroup(net);
/* Enable frame retransmissions for lossy channels */
hw->max_rates = 4;
hw->max_rate_tries = 11;
hw->wiphy->vendor_commands = mac80211_hwsim_vendor_commands;
hw->wiphy->n_vendor_commands =
ARRAY_SIZE(mac80211_hwsim_vendor_commands);
hw->wiphy->vendor_events = mac80211_hwsim_vendor_events;
hw->wiphy->n_vendor_events = ARRAY_SIZE(mac80211_hwsim_vendor_events);
if (param->reg_strict)
hw->wiphy->regulatory_flags |= REGULATORY_STRICT_REG;
if (param->regd) {
data->regd = param->regd;
hw->wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG;
wiphy_apply_custom_regulatory(hw->wiphy, param->regd);
/* give the regulatory workqueue a chance to run */
schedule_timeout_interruptible(1);
}
if (param->no_vif)
ieee80211_hw_set(hw, NO_AUTO_VIF);
wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_CQM_RSSI_LIST);
err = ieee80211_register_hw(hw);
if (err < 0) {
pr_debug("mac80211_hwsim: ieee80211_register_hw failed (%d)\n",
err);
goto failed_hw;
}
wiphy_dbg(hw->wiphy, "hwaddr %pM registered\n", hw->wiphy->perm_addr);
if (param->reg_alpha2) {
data->alpha2[0] = param->reg_alpha2[0];
data->alpha2[1] = param->reg_alpha2[1];
regulatory_hint(hw->wiphy, param->reg_alpha2);
}
data->debugfs = debugfs_create_dir("hwsim", hw->wiphy->debugfsdir);
debugfs_create_file("ps", 0666, data->debugfs, data, &hwsim_fops_ps);
debugfs_create_file("group", 0666, data->debugfs, data,
&hwsim_fops_group);
if (!data->use_chanctx)
debugfs_create_file("dfs_simulate_radar", 0222,
data->debugfs,
data, &hwsim_simulate_radar);
tasklet_hrtimer_init(&data->beacon_timer,
mac80211_hwsim_beacon,
CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
spin_lock_bh(&hwsim_radio_lock);
err = rhashtable_insert_fast(&hwsim_radios_rht, &data->rht,
hwsim_rht_params);
if (err < 0) {
pr_debug("mac80211_hwsim: radio index %d already present\n",
idx);
spin_unlock_bh(&hwsim_radio_lock);
goto failed_final_insert;
}
list_add_tail(&data->list, &hwsim_radios);
spin_unlock_bh(&hwsim_radio_lock);
if (idx > 0)
hwsim_mcast_new_radio(idx, info, param);
return idx;
failed_final_insert:
debugfs_remove_recursive(data->debugfs);
ieee80211_unregister_hw(data->hw);
failed_hw:
device_release_driver(data->dev);
failed_bind:
device_unregister(data->dev);
failed_drvdata:
ieee80211_free_hw(hw);
failed:
return err;
}
static void hwsim_mcast_del_radio(int id, const char *hwname,
struct genl_info *info)
{
struct sk_buff *skb;
void *data;
int ret;
skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!skb)
return;
data = genlmsg_put(skb, 0, 0, &hwsim_genl_family, 0,
HWSIM_CMD_DEL_RADIO);
if (!data)
goto error;
ret = nla_put_u32(skb, HWSIM_ATTR_RADIO_ID, id);
if (ret < 0)
goto error;
ret = nla_put(skb, HWSIM_ATTR_RADIO_NAME, strlen(hwname),
hwname);
if (ret < 0)
goto error;
genlmsg_end(skb, data);
hwsim_mcast_config_msg(skb, info);
return;
error:
nlmsg_free(skb);
}
static void mac80211_hwsim_del_radio(struct mac80211_hwsim_data *data,
const char *hwname,
struct genl_info *info)
{
hwsim_mcast_del_radio(data->idx, hwname, info);
debugfs_remove_recursive(data->debugfs);
ieee80211_unregister_hw(data->hw);
device_release_driver(data->dev);
device_unregister(data->dev);
ieee80211_free_hw(data->hw);
}
static int mac80211_hwsim_get_radio(struct sk_buff *skb,
struct mac80211_hwsim_data *data,
u32 portid, u32 seq,
struct netlink_callback *cb, int flags)
{
void *hdr;
struct hwsim_new_radio_params param = { };
int res = -EMSGSIZE;
hdr = genlmsg_put(skb, portid, seq, &hwsim_genl_family, flags,
HWSIM_CMD_GET_RADIO);
if (!hdr)
return -EMSGSIZE;
if (cb)
genl_dump_check_consistent(cb, hdr);
if (data->alpha2[0] && data->alpha2[1])
param.reg_alpha2 = data->alpha2;
param.reg_strict = !!(data->hw->wiphy->regulatory_flags &
REGULATORY_STRICT_REG);
param.p2p_device = !!(data->hw->wiphy->interface_modes &
BIT(NL80211_IFTYPE_P2P_DEVICE));
param.use_chanctx = data->use_chanctx;
param.regd = data->regd;
param.channels = data->channels;
param.hwname = wiphy_name(data->hw->wiphy);
res = append_radio_msg(skb, data->idx, ¶m);
if (res < 0)
goto out_err;
genlmsg_end(skb, hdr);
return 0;
out_err:
genlmsg_cancel(skb, hdr);
return res;
}
static void mac80211_hwsim_free(void)
{
struct mac80211_hwsim_data *data;
spin_lock_bh(&hwsim_radio_lock);
while ((data = list_first_entry_or_null(&hwsim_radios,
struct mac80211_hwsim_data,
list))) {
list_del(&data->list);
spin_unlock_bh(&hwsim_radio_lock);
mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy),
NULL);
spin_lock_bh(&hwsim_radio_lock);
}
spin_unlock_bh(&hwsim_radio_lock);
class_destroy(hwsim_class);
}
static const struct net_device_ops hwsim_netdev_ops = {
.ndo_start_xmit = hwsim_mon_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static void hwsim_mon_setup(struct net_device *dev)
{
dev->netdev_ops = &hwsim_netdev_ops;
dev->needs_free_netdev = true;
ether_setup(dev);
dev->priv_flags |= IFF_NO_QUEUE;
dev->type = ARPHRD_IEEE80211_RADIOTAP;
eth_zero_addr(dev->dev_addr);
dev->dev_addr[0] = 0x12;
}
static struct mac80211_hwsim_data *get_hwsim_data_ref_from_addr(const u8 *addr)
{
return rhashtable_lookup_fast(&hwsim_radios_rht,
addr,
hwsim_rht_params);
}
static void hwsim_register_wmediumd(struct net *net, u32 portid)
{
struct mac80211_hwsim_data *data;
hwsim_net_set_wmediumd(net, portid);
spin_lock_bh(&hwsim_radio_lock);
list_for_each_entry(data, &hwsim_radios, list) {
if (data->netgroup == hwsim_net_get_netgroup(net))
data->wmediumd = portid;
}
spin_unlock_bh(&hwsim_radio_lock);
}
static int hwsim_tx_info_frame_received_nl(struct sk_buff *skb_2,
struct genl_info *info)
{
struct ieee80211_hdr *hdr;
struct mac80211_hwsim_data *data2;
struct ieee80211_tx_info *txi;
struct hwsim_tx_rate *tx_attempts;
u64 ret_skb_cookie;
struct sk_buff *skb, *tmp;
const u8 *src;
unsigned int hwsim_flags;
int i;
bool found = false;
if (!info->attrs[HWSIM_ATTR_ADDR_TRANSMITTER] ||
!info->attrs[HWSIM_ATTR_FLAGS] ||
!info->attrs[HWSIM_ATTR_COOKIE] ||
!info->attrs[HWSIM_ATTR_SIGNAL] ||
!info->attrs[HWSIM_ATTR_TX_INFO])
goto out;
src = (void *)nla_data(info->attrs[HWSIM_ATTR_ADDR_TRANSMITTER]);
hwsim_flags = nla_get_u32(info->attrs[HWSIM_ATTR_FLAGS]);
ret_skb_cookie = nla_get_u64(info->attrs[HWSIM_ATTR_COOKIE]);
data2 = get_hwsim_data_ref_from_addr(src);
if (!data2)
goto out;
if (hwsim_net_get_netgroup(genl_info_net(info)) != data2->netgroup)
goto out;
if (info->snd_portid != data2->wmediumd)
goto out;
/* look for the skb matching the cookie passed back from user */
skb_queue_walk_safe(&data2->pending, skb, tmp) {
u64 skb_cookie;
txi = IEEE80211_SKB_CB(skb);
skb_cookie = (u64)(uintptr_t)txi->rate_driver_data[0];
if (skb_cookie == ret_skb_cookie) {
skb_unlink(skb, &data2->pending);
found = true;
break;
}
}
/* not found */
if (!found)
goto out;
/* Tx info received because the frame was broadcasted on user space,
so we get all the necessary info: tx attempts and skb control buff */
tx_attempts = (struct hwsim_tx_rate *)nla_data(
info->attrs[HWSIM_ATTR_TX_INFO]);
/* now send back TX status */
txi = IEEE80211_SKB_CB(skb);
ieee80211_tx_info_clear_status(txi);
for (i = 0; i < IEEE80211_TX_MAX_RATES; i++) {
txi->status.rates[i].idx = tx_attempts[i].idx;
txi->status.rates[i].count = tx_attempts[i].count;
}
txi->status.ack_signal = nla_get_u32(info->attrs[HWSIM_ATTR_SIGNAL]);
if (!(hwsim_flags & HWSIM_TX_CTL_NO_ACK) &&
(hwsim_flags & HWSIM_TX_STAT_ACK)) {
if (skb->len >= 16) {
hdr = (struct ieee80211_hdr *) skb->data;
mac80211_hwsim_monitor_ack(data2->channel,
hdr->addr2);
}
txi->flags |= IEEE80211_TX_STAT_ACK;
}
ieee80211_tx_status_irqsafe(data2->hw, skb);
return 0;
out:
return -EINVAL;
}
static int hwsim_cloned_frame_received_nl(struct sk_buff *skb_2,
struct genl_info *info)
{
struct mac80211_hwsim_data *data2;
struct ieee80211_rx_status rx_status;
const u8 *dst;
int frame_data_len;
void *frame_data;
struct sk_buff *skb = NULL;
if (!info->attrs[HWSIM_ATTR_ADDR_RECEIVER] ||
!info->attrs[HWSIM_ATTR_FRAME] ||
!info->attrs[HWSIM_ATTR_RX_RATE] ||
!info->attrs[HWSIM_ATTR_SIGNAL])
goto out;
dst = (void *)nla_data(info->attrs[HWSIM_ATTR_ADDR_RECEIVER]);
frame_data_len = nla_len(info->attrs[HWSIM_ATTR_FRAME]);
frame_data = (void *)nla_data(info->attrs[HWSIM_ATTR_FRAME]);
/* Allocate new skb here */
skb = alloc_skb(frame_data_len, GFP_KERNEL);
if (skb == NULL)
goto err;
if (frame_data_len > IEEE80211_MAX_DATA_LEN)
goto err;
/* Copy the data */
skb_put_data(skb, frame_data, frame_data_len);
data2 = get_hwsim_data_ref_from_addr(dst);
if (!data2)
goto out;
if (hwsim_net_get_netgroup(genl_info_net(info)) != data2->netgroup)
goto out;
if (info->snd_portid != data2->wmediumd)
goto out;
/* check if radio is configured properly */
if (data2->idle || !data2->started)
goto out;
/* A frame is received from user space */
memset(&rx_status, 0, sizeof(rx_status));
if (info->attrs[HWSIM_ATTR_FREQ]) {
/* throw away off-channel packets, but allow both the temporary
* ("hw" scan/remain-on-channel) and regular channel, since the
* internal datapath also allows this
*/
mutex_lock(&data2->mutex);
rx_status.freq = nla_get_u32(info->attrs[HWSIM_ATTR_FREQ]);
if (rx_status.freq != data2->channel->center_freq &&
(!data2->tmp_chan ||
rx_status.freq != data2->tmp_chan->center_freq)) {
mutex_unlock(&data2->mutex);
goto out;
}
mutex_unlock(&data2->mutex);
} else {
rx_status.freq = data2->channel->center_freq;
}
rx_status.band = data2->channel->band;
rx_status.rate_idx = nla_get_u32(info->attrs[HWSIM_ATTR_RX_RATE]);
rx_status.signal = nla_get_u32(info->attrs[HWSIM_ATTR_SIGNAL]);
memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
data2->rx_pkts++;
data2->rx_bytes += skb->len;
ieee80211_rx_irqsafe(data2->hw, skb);
return 0;
err:
pr_debug("mac80211_hwsim: error occurred in %s\n", __func__);
out:
dev_kfree_skb(skb);
return -EINVAL;
}
static int hwsim_register_received_nl(struct sk_buff *skb_2,
struct genl_info *info)
{
struct net *net = genl_info_net(info);
struct mac80211_hwsim_data *data;
int chans = 1;
spin_lock_bh(&hwsim_radio_lock);
list_for_each_entry(data, &hwsim_radios, list)
chans = max(chans, data->channels);
spin_unlock_bh(&hwsim_radio_lock);
/* In the future we should revise the userspace API and allow it
* to set a flag that it does support multi-channel, then we can
* let this pass conditionally on the flag.
* For current userspace, prohibit it since it won't work right.
*/
if (chans > 1)
return -EOPNOTSUPP;
if (hwsim_net_get_wmediumd(net))
return -EBUSY;
hwsim_register_wmediumd(net, info->snd_portid);
pr_debug("mac80211_hwsim: received a REGISTER, "
"switching to wmediumd mode with pid %d\n", info->snd_portid);
return 0;
}
static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info)
{
struct hwsim_new_radio_params param = { 0 };
const char *hwname = NULL;
int ret;
param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG];
param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE];
param.channels = channels;
param.destroy_on_close =
info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE];
if (info->attrs[HWSIM_ATTR_CHANNELS])
param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]);
if (info->attrs[HWSIM_ATTR_NO_VIF])
param.no_vif = true;
if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
hwname = kasprintf(GFP_KERNEL, "%.*s",
nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
(char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]));
if (!hwname)
return -ENOMEM;
param.hwname = hwname;
}
if (info->attrs[HWSIM_ATTR_USE_CHANCTX])
param.use_chanctx = true;
else
param.use_chanctx = (param.channels > 1);
if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2])
param.reg_alpha2 =
nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]);
if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) {
u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]);
if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom)) {
kfree(hwname);
return -EINVAL;
}
param.regd = hwsim_world_regdom_custom[idx];
}
ret = mac80211_hwsim_new_radio(info, ¶m);
kfree(hwname);
return ret;
}
static int hwsim_del_radio_nl(struct sk_buff *msg, struct genl_info *info)
{
struct mac80211_hwsim_data *data;
s64 idx = -1;
const char *hwname = NULL;
if (info->attrs[HWSIM_ATTR_RADIO_ID]) {
idx = nla_get_u32(info->attrs[HWSIM_ATTR_RADIO_ID]);
} else if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
hwname = kasprintf(GFP_KERNEL, "%.*s",
nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
(char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]));
if (!hwname)
return -ENOMEM;
} else
return -EINVAL;
spin_lock_bh(&hwsim_radio_lock);
list_for_each_entry(data, &hwsim_radios, list) {
if (idx >= 0) {
if (data->idx != idx)
continue;
} else {
if (!hwname ||
strcmp(hwname, wiphy_name(data->hw->wiphy)))
continue;
}
if (!net_eq(wiphy_net(data->hw->wiphy), genl_info_net(info)))
continue;
list_del(&data->list);
rhashtable_remove_fast(&hwsim_radios_rht, &data->rht,
hwsim_rht_params);
spin_unlock_bh(&hwsim_radio_lock);
mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy),
info);
kfree(hwname);
return 0;
}
spin_unlock_bh(&hwsim_radio_lock);
kfree(hwname);
return -ENODEV;
}
static int hwsim_get_radio_nl(struct sk_buff *msg, struct genl_info *info)
{
struct mac80211_hwsim_data *data;
struct sk_buff *skb;
int idx, res = -ENODEV;
if (!info->attrs[HWSIM_ATTR_RADIO_ID])
return -EINVAL;
idx = nla_get_u32(info->attrs[HWSIM_ATTR_RADIO_ID]);
spin_lock_bh(&hwsim_radio_lock);
list_for_each_entry(data, &hwsim_radios, list) {
if (data->idx != idx)
continue;
if (!net_eq(wiphy_net(data->hw->wiphy), genl_info_net(info)))
continue;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb) {
res = -ENOMEM;
goto out_err;
}
res = mac80211_hwsim_get_radio(skb, data, info->snd_portid,
info->snd_seq, NULL, 0);
if (res < 0) {
nlmsg_free(skb);
goto out_err;
}
genlmsg_reply(skb, info);
break;
}
out_err:
spin_unlock_bh(&hwsim_radio_lock);
return res;
}
static int hwsim_dump_radio_nl(struct sk_buff *skb,
struct netlink_callback *cb)
{
int idx = cb->args[0];
struct mac80211_hwsim_data *data = NULL;
int res;
spin_lock_bh(&hwsim_radio_lock);
if (idx == hwsim_radio_idx)
goto done;
list_for_each_entry(data, &hwsim_radios, list) {
if (data->idx < idx)
continue;
if (!net_eq(wiphy_net(data->hw->wiphy), sock_net(skb->sk)))
continue;
res = mac80211_hwsim_get_radio(skb, data,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, cb,
NLM_F_MULTI);
if (res < 0)
break;
idx = data->idx + 1;
}
cb->args[0] = idx;
done:
spin_unlock_bh(&hwsim_radio_lock);
return skb->len;
}
/* Generic Netlink operations array */
static const struct genl_ops hwsim_ops[] = {
{
.cmd = HWSIM_CMD_REGISTER,
.policy = hwsim_genl_policy,
.doit = hwsim_register_received_nl,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = HWSIM_CMD_FRAME,
.policy = hwsim_genl_policy,
.doit = hwsim_cloned_frame_received_nl,
},
{
.cmd = HWSIM_CMD_TX_INFO_FRAME,
.policy = hwsim_genl_policy,
.doit = hwsim_tx_info_frame_received_nl,
},
{
.cmd = HWSIM_CMD_NEW_RADIO,
.policy = hwsim_genl_policy,
.doit = hwsim_new_radio_nl,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = HWSIM_CMD_DEL_RADIO,
.policy = hwsim_genl_policy,
.doit = hwsim_del_radio_nl,
.flags = GENL_UNS_ADMIN_PERM,
},
{
.cmd = HWSIM_CMD_GET_RADIO,
.policy = hwsim_genl_policy,
.doit = hwsim_get_radio_nl,
.dumpit = hwsim_dump_radio_nl,
},
};
static struct genl_family hwsim_genl_family __ro_after_init = {
.name = "MAC80211_HWSIM",
.version = 1,
.maxattr = HWSIM_ATTR_MAX,
.netnsok = true,
.module = THIS_MODULE,
.ops = hwsim_ops,
.n_ops = ARRAY_SIZE(hwsim_ops),
.mcgrps = hwsim_mcgrps,
.n_mcgrps = ARRAY_SIZE(hwsim_mcgrps),
};
static void destroy_radio(struct work_struct *work)
{
struct mac80211_hwsim_data *data =
container_of(work, struct mac80211_hwsim_data, destroy_work);
mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy), NULL);
}
static void remove_user_radios(u32 portid)
{
struct mac80211_hwsim_data *entry, *tmp;
spin_lock_bh(&hwsim_radio_lock);
list_for_each_entry_safe(entry, tmp, &hwsim_radios, list) {
if (entry->destroy_on_close && entry->portid == portid) {
list_del(&entry->list);
rhashtable_remove_fast(&hwsim_radios_rht, &entry->rht,
hwsim_rht_params);
INIT_WORK(&entry->destroy_work, destroy_radio);
schedule_work(&entry->destroy_work);
}
}
spin_unlock_bh(&hwsim_radio_lock);
}
static int mac80211_hwsim_netlink_notify(struct notifier_block *nb,
unsigned long state,
void *_notify)
{
struct netlink_notify *notify = _notify;
if (state != NETLINK_URELEASE)
return NOTIFY_DONE;
remove_user_radios(notify->portid);
if (notify->portid == hwsim_net_get_wmediumd(notify->net)) {
printk(KERN_INFO "mac80211_hwsim: wmediumd released netlink"
" socket, switching to perfect channel medium\n");
hwsim_register_wmediumd(notify->net, 0);
}
return NOTIFY_DONE;
}
static struct notifier_block hwsim_netlink_notifier = {
.notifier_call = mac80211_hwsim_netlink_notify,
};
static int __init hwsim_init_netlink(void)
{
int rc;
printk(KERN_INFO "mac80211_hwsim: initializing netlink\n");
rc = genl_register_family(&hwsim_genl_family);
if (rc)
goto failure;
rc = netlink_register_notifier(&hwsim_netlink_notifier);
if (rc) {
genl_unregister_family(&hwsim_genl_family);
goto failure;
}
return 0;
failure:
pr_debug("mac80211_hwsim: error occurred in %s\n", __func__);
return -EINVAL;
}
static __net_init int hwsim_init_net(struct net *net)
{
hwsim_net_set_netgroup(net);
return 0;
}
static void __net_exit hwsim_exit_net(struct net *net)
{
struct mac80211_hwsim_data *data, *tmp;
spin_lock_bh(&hwsim_radio_lock);
list_for_each_entry_safe(data, tmp, &hwsim_radios, list) {
if (!net_eq(wiphy_net(data->hw->wiphy), net))
continue;
/* Radios created in init_net are returned to init_net. */
if (data->netgroup == hwsim_net_get_netgroup(&init_net))
continue;
list_del(&data->list);
rhashtable_remove_fast(&hwsim_radios_rht, &data->rht,
hwsim_rht_params);
INIT_WORK(&data->destroy_work, destroy_radio);
schedule_work(&data->destroy_work);
}
spin_unlock_bh(&hwsim_radio_lock);
}
static struct pernet_operations hwsim_net_ops = {
.init = hwsim_init_net,
.exit = hwsim_exit_net,
.id = &hwsim_net_id,
.size = sizeof(struct hwsim_net),
};
static void hwsim_exit_netlink(void)
{
/* unregister the notifier */
netlink_unregister_notifier(&hwsim_netlink_notifier);
/* unregister the family */
genl_unregister_family(&hwsim_genl_family);
}
static int __init init_mac80211_hwsim(void)
{
int i, err;
if (radios < 0 || radios > 100)
return -EINVAL;
if (channels < 1)
return -EINVAL;
spin_lock_init(&hwsim_radio_lock);
rhashtable_init(&hwsim_radios_rht, &hwsim_rht_params);
err = register_pernet_device(&hwsim_net_ops);
if (err)
return err;
err = platform_driver_register(&mac80211_hwsim_driver);
if (err)
goto out_unregister_pernet;
hwsim_class = class_create(THIS_MODULE, "mac80211_hwsim");
if (IS_ERR(hwsim_class)) {
err = PTR_ERR(hwsim_class);
goto out_unregister_driver;
}
err = hwsim_init_netlink();
if (err < 0)
goto out_unregister_driver;
for (i = 0; i < radios; i++) {
struct hwsim_new_radio_params param = { 0 };
param.channels = channels;
switch (regtest) {
case HWSIM_REGTEST_DIFF_COUNTRY:
if (i < ARRAY_SIZE(hwsim_alpha2s))
param.reg_alpha2 = hwsim_alpha2s[i];
break;
case HWSIM_REGTEST_DRIVER_REG_FOLLOW:
if (!i)
param.reg_alpha2 = hwsim_alpha2s[0];
break;
case HWSIM_REGTEST_STRICT_ALL:
param.reg_strict = true;
case HWSIM_REGTEST_DRIVER_REG_ALL:
param.reg_alpha2 = hwsim_alpha2s[0];
break;
case HWSIM_REGTEST_WORLD_ROAM:
if (i == 0)
param.regd = &hwsim_world_regdom_custom_01;
break;
case HWSIM_REGTEST_CUSTOM_WORLD:
param.regd = &hwsim_world_regdom_custom_01;
break;
case HWSIM_REGTEST_CUSTOM_WORLD_2:
if (i == 0)
param.regd = &hwsim_world_regdom_custom_01;
else if (i == 1)
param.regd = &hwsim_world_regdom_custom_02;
break;
case HWSIM_REGTEST_STRICT_FOLLOW:
if (i == 0) {
param.reg_strict = true;
param.reg_alpha2 = hwsim_alpha2s[0];
}
break;
case HWSIM_REGTEST_STRICT_AND_DRIVER_REG:
if (i == 0) {
param.reg_strict = true;
param.reg_alpha2 = hwsim_alpha2s[0];
} else if (i == 1) {
param.reg_alpha2 = hwsim_alpha2s[1];
}
break;
case HWSIM_REGTEST_ALL:
switch (i) {
case 0:
param.regd = &hwsim_world_regdom_custom_01;
break;
case 1:
param.regd = &hwsim_world_regdom_custom_02;
break;
case 2:
param.reg_alpha2 = hwsim_alpha2s[0];
break;
case 3:
param.reg_alpha2 = hwsim_alpha2s[1];
break;
case 4:
param.reg_strict = true;
param.reg_alpha2 = hwsim_alpha2s[2];
break;
}
break;
default:
break;
}
param.p2p_device = support_p2p_device;
param.use_chanctx = channels > 1;
err = mac80211_hwsim_new_radio(NULL, ¶m);
if (err < 0)
goto out_free_radios;
}
hwsim_mon = alloc_netdev(0, "hwsim%d", NET_NAME_UNKNOWN,
hwsim_mon_setup);
if (hwsim_mon == NULL) {
err = -ENOMEM;
goto out_free_radios;
}
rtnl_lock();
err = dev_alloc_name(hwsim_mon, hwsim_mon->name);
if (err < 0) {
rtnl_unlock();
goto out_free_radios;
}
err = register_netdevice(hwsim_mon);
if (err < 0) {
rtnl_unlock();
goto out_free_mon;
}
rtnl_unlock();
return 0;
out_free_mon:
free_netdev(hwsim_mon);
out_free_radios:
mac80211_hwsim_free();
out_unregister_driver:
platform_driver_unregister(&mac80211_hwsim_driver);
out_unregister_pernet:
unregister_pernet_device(&hwsim_net_ops);
return err;
}
module_init(init_mac80211_hwsim);
static void __exit exit_mac80211_hwsim(void)
{
pr_debug("mac80211_hwsim: unregister radios\n");
hwsim_exit_netlink();
mac80211_hwsim_free();
rhashtable_destroy(&hwsim_radios_rht);
unregister_netdev(hwsim_mon);
platform_driver_unregister(&mac80211_hwsim_driver);
unregister_pernet_device(&hwsim_net_ops);
}
module_exit(exit_mac80211_hwsim);
| ./CrossVul/dataset_final_sorted/CWE-772/c/good_661_0 |
crossvul-cpp_data_bad_2620_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% IIIII N N L IIIII N N EEEEE %
% I NN N L I NN N E %
% I N N N L I N N N EEE %
% I N NN L I N NN E %
% IIIII N N LLLLL IIIII N N EEEEE %
% %
% %
% Read/Write Inline Images %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/client.h"
#include "magick/display.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/utility.h"
#include "magick/xwindow.h"
#include "magick/xwindow-private.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteINLINEImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d I N L I N E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadINLINEImage() reads base64-encoded inlines images.
%
% The format of the ReadINLINEImage method is:
%
% Image *ReadINLINEImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadINLINEImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register size_t
i;
size_t
quantum;
ssize_t
count;
unsigned char
*inline_image;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (LocaleNCompare(image_info->filename,"data:",5) == 0)
{
char
*filename;
Image
*data_image;
filename=AcquireString("data:");
(void) ConcatenateMagickString(filename,image_info->filename,
MaxTextExtent);
data_image=ReadInlineImage(image_info,filename,exception);
filename=DestroyString(filename);
return(data_image);
}
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
quantum=MagickMin((size_t) GetBlobSize(image),MagickMaxBufferExtent);
if (quantum == 0)
quantum=MagickMaxBufferExtent;
inline_image=(unsigned char *) AcquireQuantumMemory(quantum,
sizeof(*inline_image));
count=0;
for (i=0; inline_image != (unsigned char *) NULL; i+=count)
{
count=(ssize_t) ReadBlob(image,quantum,inline_image+i);
if (count <= 0)
{
count=0;
if (errno != EINTR)
break;
}
if (~((size_t) i) < (quantum+1))
{
inline_image=(unsigned char *) RelinquishMagickMemory(inline_image);
break;
}
inline_image=(unsigned char *) ResizeQuantumMemory(inline_image,i+count+
quantum+1,sizeof(*inline_image));
}
if (inline_image == (unsigned char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return((Image *) NULL);
}
inline_image[i+count]='\0';
image=DestroyImageList(image);
image=ReadInlineImage(image_info,(char *) inline_image,exception);
inline_image=(unsigned char *) RelinquishMagickMemory(inline_image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r I N L I N E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterINLINEImage() adds attributes for the INLINE image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterINLINEImage method is:
%
% size_t RegisterINLINEImage(void)
%
*/
ModuleExport size_t RegisterINLINEImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("DATA");
entry->decoder=(DecodeImageHandler *) ReadINLINEImage;
entry->encoder=(EncodeImageHandler *) WriteINLINEImage;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Base64-encoded inline images");
entry->module=ConstantString("INLINE");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("INLINE");
entry->decoder=(DecodeImageHandler *) ReadINLINEImage;
entry->encoder=(EncodeImageHandler *) WriteINLINEImage;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Base64-encoded inline images");
entry->module=ConstantString("INLINE");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r I N L I N E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterINLINEImage() removes format registrations made by the
% INLINE module from the list of supported formats.
%
% The format of the UnregisterINLINEImage method is:
%
% UnregisterINLINEImage(void)
%
*/
ModuleExport void UnregisterINLINEImage(void)
{
(void) UnregisterMagickInfo("INLINE");
(void) UnregisterMagickInfo("DATA");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e I N L I N E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteINLINEImage() writes an image to a file in INLINE format (Base64).
%
% The format of the WriteINLINEImage method is:
%
% MagickBooleanType WriteINLINEImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteINLINEImage(const ImageInfo *image_info,
Image *image)
{
char
*base64,
message[MaxTextExtent];
const MagickInfo
*magick_info;
ExceptionInfo
*exception;
Image
*write_image;
ImageInfo
*write_info;
MagickBooleanType
status;
size_t
blob_length,
encode_length;
unsigned char
*blob;
/*
Convert image to base64-encoding.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=(&image->exception);
write_info=CloneImageInfo(image_info);
(void) SetImageInfo(write_info,1,exception);
if (LocaleCompare(write_info->magick,"INLINE") == 0)
(void) CopyMagickString(write_info->magick,image->magick,MaxTextExtent);
magick_info=GetMagickInfo(write_info->magick,exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickMimeType(magick_info) == (const char *) NULL))
ThrowWriterException(CorruptImageError,"ImageTypeNotSupported");
(void) CopyMagickString(image->filename,write_info->filename,MaxTextExtent);
blob_length=2048;
write_image=CloneImage(image,0,0,MagickTrue,exception);
if (write_image == (Image *) NULL)
{
write_info=DestroyImageInfo(write_info);
return(MagickTrue);
}
blob=(unsigned char *) ImageToBlob(write_info,write_image,&blob_length,
exception);
write_image=DestroyImage(write_image);
write_info=DestroyImageInfo(write_info);
if (blob == (unsigned char *) NULL)
return(MagickFalse);
encode_length=0;
base64=Base64Encode(blob,blob_length,&encode_length);
blob=(unsigned char *) RelinquishMagickMemory(blob);
if (base64 == (char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write base64-encoded image.
*/
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
{
base64=DestroyString(base64);
return(status);
}
(void) FormatLocaleString(message,MaxTextExtent,"data:%s;base64,",
GetMagickMimeType(magick_info));
(void) WriteBlobString(image,message);
(void) WriteBlobString(image,base64);
base64=DestroyString(base64);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/bad_2620_0 |
crossvul-cpp_data_bad_4476_0 | /* $OpenBSD: table.c,v 1.48 2019/01/10 07:40:52 eric Exp $ */
/*
* Copyright (c) 2013 Eric Faurot <eric@openbsd.org>
* Copyright (c) 2008 Gilles Chehade <gilles@poolp.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/tree.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <errno.h>
#include <event.h>
#include <imsg.h>
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <limits.h>
#include <string.h>
#include <unistd.h>
#include "smtpd.h"
#include "log.h"
struct table_backend *table_backend_lookup(const char *);
extern struct table_backend table_backend_static;
extern struct table_backend table_backend_db;
extern struct table_backend table_backend_getpwnam;
extern struct table_backend table_backend_proc;
static const char * table_service_name(enum table_service);
static int table_parse_lookup(enum table_service, const char *, const char *,
union lookup *);
static int parse_sockaddr(struct sockaddr *, int, const char *);
static unsigned int last_table_id = 0;
static struct table_backend *backends[] = {
&table_backend_static,
&table_backend_db,
&table_backend_getpwnam,
&table_backend_proc,
NULL
};
struct table_backend *
table_backend_lookup(const char *backend)
{
int i;
if (!strcmp(backend, "file"))
backend = "static";
for (i = 0; backends[i]; i++)
if (!strcmp(backends[i]->name, backend))
return (backends[i]);
return NULL;
}
static const char *
table_service_name(enum table_service s)
{
switch (s) {
case K_NONE: return "NONE";
case K_ALIAS: return "ALIAS";
case K_DOMAIN: return "DOMAIN";
case K_CREDENTIALS: return "CREDENTIALS";
case K_NETADDR: return "NETADDR";
case K_USERINFO: return "USERINFO";
case K_SOURCE: return "SOURCE";
case K_MAILADDR: return "MAILADDR";
case K_ADDRNAME: return "ADDRNAME";
case K_MAILADDRMAP: return "MAILADDRMAP";
case K_RELAYHOST: return "RELAYHOST";
case K_STRING: return "STRING";
case K_REGEX: return "REGEX";
}
return "???";
}
struct table *
table_find(struct smtpd *conf, const char *name)
{
return dict_get(conf->sc_tables_dict, name);
}
int
table_match(struct table *table, enum table_service kind, const char *key)
{
return table_lookup(table, kind, key, NULL);
}
int
table_lookup(struct table *table, enum table_service kind, const char *key,
union lookup *lk)
{
char lkey[1024], *buf = NULL;
int r;
r = -1;
if (table->t_backend->lookup == NULL)
errno = ENOTSUP;
else if (!lowercase(lkey, key, sizeof lkey)) {
log_warnx("warn: lookup key too long: %s", key);
errno = EINVAL;
}
else
r = table->t_backend->lookup(table, kind, lkey, lk ? &buf : NULL);
if (r == 1) {
log_trace(TRACE_LOOKUP, "lookup: %s \"%s\" as %s in table %s:%s -> %s%s%s",
lk ? "lookup" : "match",
key,
table_service_name(kind),
table->t_backend->name,
table->t_name,
lk ? "\"" : "",
lk ? buf : "true",
lk ? "\"" : "");
if (buf)
r = table_parse_lookup(kind, lkey, buf, lk);
}
else
log_trace(TRACE_LOOKUP, "lookup: %s \"%s\" as %s in table %s:%s -> %s%s",
lk ? "lookup" : "match",
key,
table_service_name(kind),
table->t_backend->name,
table->t_name,
(r == -1) ? "error: " : (lk ? "none" : "false"),
(r == -1) ? strerror(errno) : "");
free(buf);
return (r);
}
int
table_fetch(struct table *table, enum table_service kind, union lookup *lk)
{
char *buf = NULL;
int r;
r = -1;
if (table->t_backend->fetch == NULL)
errno = ENOTSUP;
else
r = table->t_backend->fetch(table, kind, &buf);
if (r == 1) {
log_trace(TRACE_LOOKUP, "lookup: fetch %s from table %s:%s -> \"%s\"",
table_service_name(kind),
table->t_backend->name,
table->t_name,
buf);
r = table_parse_lookup(kind, NULL, buf, lk);
}
else
log_trace(TRACE_LOOKUP, "lookup: fetch %s from table %s:%s -> %s%s",
table_service_name(kind),
table->t_backend->name,
table->t_name,
(r == -1) ? "error: " : "none",
(r == -1) ? strerror(errno) : "");
free(buf);
return (r);
}
struct table *
table_create(struct smtpd *conf, const char *backend, const char *name,
const char *config)
{
struct table *t;
struct table_backend *tb;
char path[LINE_MAX];
size_t n;
struct stat sb;
if (name && table_find(conf, name))
fatalx("table_create: table \"%s\" already defined", name);
if ((tb = table_backend_lookup(backend)) == NULL) {
if ((size_t)snprintf(path, sizeof(path), PATH_LIBEXEC"/table-%s",
backend) >= sizeof(path)) {
fatalx("table_create: path too long \""
PATH_LIBEXEC"/table-%s\"", backend);
}
if (stat(path, &sb) == 0) {
tb = table_backend_lookup("proc");
(void)strlcpy(path, backend, sizeof(path));
if (config) {
(void)strlcat(path, ":", sizeof(path));
if (strlcat(path, config, sizeof(path))
>= sizeof(path))
fatalx("table_create: config file path too long");
}
config = path;
}
}
if (tb == NULL)
fatalx("table_create: backend \"%s\" does not exist", backend);
t = xcalloc(1, sizeof(*t));
t->t_backend = tb;
if (config) {
if (strlcpy(t->t_config, config, sizeof t->t_config)
>= sizeof t->t_config)
fatalx("table_create: table config \"%s\" too large",
t->t_config);
}
if (strcmp(tb->name, "static") != 0)
t->t_type = T_DYNAMIC;
if (name == NULL)
(void)snprintf(t->t_name, sizeof(t->t_name), "<dynamic:%u>",
last_table_id++);
else {
n = strlcpy(t->t_name, name, sizeof(t->t_name));
if (n >= sizeof(t->t_name))
fatalx("table_create: table name too long");
}
dict_set(conf->sc_tables_dict, t->t_name, t);
return (t);
}
void
table_destroy(struct smtpd *conf, struct table *t)
{
dict_xpop(conf->sc_tables_dict, t->t_name);
free(t);
}
int
table_config(struct table *t)
{
if (t->t_backend->config == NULL)
return (1);
return (t->t_backend->config(t));
}
void
table_add(struct table *t, const char *key, const char *val)
{
if (t->t_backend->add == NULL)
fatalx("table_add: cannot add to table");
if (t->t_backend->add(t, key, val) == 0)
log_warnx("warn: failed to add \"%s\" in table \"%s\"", key, t->t_name);
}
void
table_dump(struct table *t)
{
const char *type;
char buf[LINE_MAX];
switch(t->t_type) {
case T_NONE:
type = "NONE";
break;
case T_DYNAMIC:
type = "DYNAMIC";
break;
case T_LIST:
type = "LIST";
break;
case T_HASH:
type = "HASH";
break;
default:
type = "???";
break;
}
if (t->t_config[0])
snprintf(buf, sizeof(buf), " config=\"%s\"", t->t_config);
else
buf[0] = '\0';
log_debug("TABLE \"%s\" backend=%s type=%s%s", t->t_name,
t->t_backend->name, type, buf);
if (t->t_backend->dump)
t->t_backend->dump(t);
}
int
table_check_type(struct table *t, uint32_t mask)
{
return t->t_type & mask;
}
int
table_check_service(struct table *t, uint32_t mask)
{
return t->t_backend->services & mask;
}
int
table_check_use(struct table *t, uint32_t tmask, uint32_t smask)
{
return table_check_type(t, tmask) && table_check_service(t, smask);
}
int
table_open(struct table *t)
{
if (t->t_backend->open == NULL)
return (1);
return (t->t_backend->open(t));
}
void
table_close(struct table *t)
{
if (t->t_backend->close)
t->t_backend->close(t);
}
int
table_update(struct table *t)
{
if (t->t_backend->update == NULL)
return (1);
return (t->t_backend->update(t));
}
/*
* quick reminder:
* in *_match() s1 comes from session, s2 comes from table
*/
int
table_domain_match(const char *s1, const char *s2)
{
return hostname_match(s1, s2);
}
int
table_mailaddr_match(const char *s1, const char *s2)
{
struct mailaddr m1;
struct mailaddr m2;
if (!text_to_mailaddr(&m1, s1))
return 0;
if (!text_to_mailaddr(&m2, s2))
return 0;
return mailaddr_match(&m1, &m2);
}
static int table_match_mask(struct sockaddr_storage *, struct netaddr *);
static int table_inet4_match(struct sockaddr_in *, struct netaddr *);
static int table_inet6_match(struct sockaddr_in6 *, struct netaddr *);
int
table_netaddr_match(const char *s1, const char *s2)
{
struct netaddr n1;
struct netaddr n2;
if (strcasecmp(s1, s2) == 0)
return 1;
if (!text_to_netaddr(&n1, s1))
return 0;
if (!text_to_netaddr(&n2, s2))
return 0;
if (n1.ss.ss_family != n2.ss.ss_family)
return 0;
if (n1.ss.ss_len != n2.ss.ss_len)
return 0;
return table_match_mask(&n1.ss, &n2);
}
static int
table_match_mask(struct sockaddr_storage *ss, struct netaddr *ssmask)
{
if (ss->ss_family == AF_INET)
return table_inet4_match((struct sockaddr_in *)ss, ssmask);
if (ss->ss_family == AF_INET6)
return table_inet6_match((struct sockaddr_in6 *)ss, ssmask);
return (0);
}
static int
table_inet4_match(struct sockaddr_in *ss, struct netaddr *ssmask)
{
in_addr_t mask;
int i;
/* a.b.c.d/8 -> htonl(0xff000000) */
mask = 0;
for (i = 0; i < ssmask->bits; ++i)
mask = (mask >> 1) | 0x80000000;
mask = htonl(mask);
/* (addr & mask) == (net & mask) */
if ((ss->sin_addr.s_addr & mask) ==
(((struct sockaddr_in *)ssmask)->sin_addr.s_addr & mask))
return 1;
return 0;
}
static int
table_inet6_match(struct sockaddr_in6 *ss, struct netaddr *ssmask)
{
struct in6_addr *in;
struct in6_addr *inmask;
struct in6_addr mask;
int i;
memset(&mask, 0, sizeof(mask));
for (i = 0; i < ssmask->bits / 8; i++)
mask.s6_addr[i] = 0xff;
i = ssmask->bits % 8;
if (i)
mask.s6_addr[ssmask->bits / 8] = 0xff00 >> i;
in = &ss->sin6_addr;
inmask = &((struct sockaddr_in6 *)&ssmask->ss)->sin6_addr;
for (i = 0; i < 16; i++) {
if ((in->s6_addr[i] & mask.s6_addr[i]) !=
(inmask->s6_addr[i] & mask.s6_addr[i]))
return (0);
}
return (1);
}
int
table_regex_match(const char *string, const char *pattern)
{
regex_t preg;
int cflags = REG_EXTENDED|REG_NOSUB;
if (strncmp(pattern, "(?i)", 4) == 0) {
cflags |= REG_ICASE;
pattern += 4;
}
if (regcomp(&preg, pattern, cflags) != 0)
return (0);
if (regexec(&preg, string, 0, NULL, 0) != 0)
return (0);
return (1);
}
void
table_dump_all(struct smtpd *conf)
{
struct table *t;
void *iter;
iter = NULL;
while (dict_iter(conf->sc_tables_dict, &iter, NULL, (void **)&t))
table_dump(t);
}
void
table_open_all(struct smtpd *conf)
{
struct table *t;
void *iter;
iter = NULL;
while (dict_iter(conf->sc_tables_dict, &iter, NULL, (void **)&t))
if (!table_open(t))
fatalx("failed to open table %s", t->t_name);
}
void
table_close_all(struct smtpd *conf)
{
struct table *t;
void *iter;
iter = NULL;
while (dict_iter(conf->sc_tables_dict, &iter, NULL, (void **)&t))
table_close(t);
}
static int
table_parse_lookup(enum table_service service, const char *key,
const char *line, union lookup *lk)
{
char buffer[LINE_MAX], *p;
size_t len;
len = strlen(line);
switch (service) {
case K_ALIAS:
lk->expand = calloc(1, sizeof(*lk->expand));
if (lk->expand == NULL)
return (-1);
if (!expand_line(lk->expand, line, 1)) {
expand_free(lk->expand);
return (-1);
}
return (1);
case K_DOMAIN:
if (strlcpy(lk->domain.name, line, sizeof(lk->domain.name))
>= sizeof(lk->domain.name))
return (-1);
return (1);
case K_CREDENTIALS:
/* credentials are stored as user:password */
if (len < 3)
return (-1);
/* too big to fit in a smtp session line */
if (len >= LINE_MAX)
return (-1);
p = strchr(line, ':');
if (p == NULL) {
if (strlcpy(lk->creds.username, key, sizeof (lk->creds.username))
>= sizeof (lk->creds.username))
return (-1);
if (strlcpy(lk->creds.password, line, sizeof(lk->creds.password))
>= sizeof(lk->creds.password))
return (-1);
return (1);
}
if (p == line || p == line + len - 1)
return (-1);
memmove(lk->creds.username, line, p - line);
lk->creds.username[p - line] = '\0';
if (strlcpy(lk->creds.password, p+1, sizeof(lk->creds.password))
>= sizeof(lk->creds.password))
return (-1);
return (1);
case K_NETADDR:
if (!text_to_netaddr(&lk->netaddr, line))
return (-1);
return (1);
case K_USERINFO:
if (!bsnprintf(buffer, sizeof(buffer), "%s:%s", key, line))
return (-1);
if (!text_to_userinfo(&lk->userinfo, buffer))
return (-1);
return (1);
case K_SOURCE:
if (parse_sockaddr((struct sockaddr *)&lk->source.addr,
PF_UNSPEC, line) == -1)
return (-1);
return (1);
case K_MAILADDR:
if (!text_to_mailaddr(&lk->mailaddr, line))
return (-1);
return (1);
case K_MAILADDRMAP:
lk->maddrmap = calloc(1, sizeof(*lk->maddrmap));
if (lk->maddrmap == NULL)
return (-1);
maddrmap_init(lk->maddrmap);
if (!mailaddr_line(lk->maddrmap, line)) {
maddrmap_free(lk->maddrmap);
return (-1);
}
return (1);
case K_ADDRNAME:
if (parse_sockaddr((struct sockaddr *)&lk->addrname.addr,
PF_UNSPEC, key) == -1)
return (-1);
if (strlcpy(lk->addrname.name, line, sizeof(lk->addrname.name))
>= sizeof(lk->addrname.name))
return (-1);
return (1);
case K_RELAYHOST:
if (strlcpy(lk->relayhost, line, sizeof(lk->relayhost))
>= sizeof(lk->relayhost))
return (-1);
return (1);
default:
return (-1);
}
}
static int
parse_sockaddr(struct sockaddr *sa, int family, const char *str)
{
struct in_addr ina;
struct in6_addr in6a;
struct sockaddr_in *sin;
struct sockaddr_in6 *sin6;
char *cp, *str2;
const char *errstr;
switch (family) {
case PF_UNSPEC:
if (parse_sockaddr(sa, PF_INET, str) == 0)
return (0);
return parse_sockaddr(sa, PF_INET6, str);
case PF_INET:
if (inet_pton(PF_INET, str, &ina) != 1)
return (-1);
sin = (struct sockaddr_in *)sa;
memset(sin, 0, sizeof *sin);
sin->sin_len = sizeof(struct sockaddr_in);
sin->sin_family = PF_INET;
sin->sin_addr.s_addr = ina.s_addr;
return (0);
case PF_INET6:
if (strncasecmp("ipv6:", str, 5) == 0)
str += 5;
cp = strchr(str, SCOPE_DELIMITER);
if (cp) {
str2 = strdup(str);
if (str2 == NULL)
return (-1);
str2[cp - str] = '\0';
if (inet_pton(PF_INET6, str2, &in6a) != 1) {
free(str2);
return (-1);
}
cp++;
free(str2);
} else if (inet_pton(PF_INET6, str, &in6a) != 1)
return (-1);
sin6 = (struct sockaddr_in6 *)sa;
memset(sin6, 0, sizeof *sin6);
sin6->sin6_len = sizeof(struct sockaddr_in6);
sin6->sin6_family = PF_INET6;
sin6->sin6_addr = in6a;
if (cp == NULL)
return (0);
if (IN6_IS_ADDR_LINKLOCAL(&in6a) ||
IN6_IS_ADDR_MC_LINKLOCAL(&in6a) ||
IN6_IS_ADDR_MC_INTFACELOCAL(&in6a))
if ((sin6->sin6_scope_id = if_nametoindex(cp)))
return (0);
sin6->sin6_scope_id = strtonum(cp, 0, UINT32_MAX, &errstr);
if (errstr)
return (-1);
return (0);
default:
break;
}
return (-1);
}
| ./CrossVul/dataset_final_sorted/CWE-772/c/bad_4476_0 |
crossvul-cpp_data_good_4069_0 | /**
* @file
* Low-level socket handling
*
* @authors
* Copyright (C) 1998,2000 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1999-2006,2008 Brendan Cully <brendan@kublai.com>
* Copyright (C) 1999-2000 Tommi Komulainen <Tommi.Komulainen@iki.fi>
*
* @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 conn_socket Low-level socket handling
*
* Low-level socket handling
*/
#include "config.h"
#include <errno.h>
#include <string.h>
#include <time.h>
#include "private.h"
#include "mutt/lib.h"
#include "socket.h"
#include "conn_globals.h"
#include "connaccount.h"
#include "connection.h"
#include "protos.h"
#include "ssl.h"
/**
* socket_preconnect - Execute a command before opening a socket
* @retval 0 Success
* @retval >0 An errno, e.g. EPERM
*/
static int socket_preconnect(void)
{
if (!C_Preconnect)
return 0;
mutt_debug(LL_DEBUG2, "Executing preconnect: %s\n", C_Preconnect);
const int rc = mutt_system(C_Preconnect);
mutt_debug(LL_DEBUG2, "Preconnect result: %d\n", rc);
if (rc != 0)
{
const int save_errno = errno;
mutt_perror(_("Preconnect command failed"));
return save_errno;
}
return 0;
}
/**
* mutt_socket_open - Simple wrapper
* @param conn Connection to a server
* @retval 0 Success
* @retval -1 Error
*/
int mutt_socket_open(struct Connection *conn)
{
int rc;
if (socket_preconnect())
return -1;
rc = conn->open(conn);
mutt_debug(LL_DEBUG2, "Connected to %s:%d on fd=%d\n", conn->account.host,
conn->account.port, conn->fd);
return rc;
}
/**
* mutt_socket_close - Close a socket
* @param conn Connection to a server
* @retval 0 Success
* @retval -1 Error
*/
int mutt_socket_close(struct Connection *conn)
{
if (!conn)
return 0;
int rc = -1;
if (conn->fd < 0)
mutt_debug(LL_DEBUG1, "Attempt to close closed connection\n");
else
rc = conn->close(conn);
conn->fd = -1;
conn->ssf = 0;
conn->bufpos = 0;
conn->available = 0;
return rc;
}
/**
* mutt_socket_read - read from a Connection
* @param conn Connection a server
* @param buf Buffer to store read data
* @param len length of the buffer
* @retval >0 Success, number of bytes read
* @retval -1 Error, see errno
*/
int mutt_socket_read(struct Connection *conn, char *buf, size_t len)
{
return conn->read(conn, buf, len);
}
/**
* mutt_socket_write - write to a Connection
* @param conn Connection to a server
* @param buf Buffer with data to write
* @param len Length of data to write
* @retval >0 Number of bytes written
* @retval -1 Error
*/
int mutt_socket_write(struct Connection *conn, const char *buf, size_t len)
{
return conn->write(conn, buf, len);
}
/**
* mutt_socket_write_d - Write data to a socket
* @param conn Connection to a server
* @param buf Buffer with data to write
* @param len Length of data to write
* @param dbg Debug level for logging
* @retval >0 Number of bytes written
* @retval -1 Error
*/
int mutt_socket_write_d(struct Connection *conn, const char *buf, int len, int dbg)
{
int sent = 0;
mutt_debug(dbg, "%d> %s", conn->fd, buf);
if (conn->fd < 0)
{
mutt_debug(LL_DEBUG1, "attempt to write to closed connection\n");
return -1;
}
while (sent < len)
{
const int rc = conn->write(conn, buf + sent, len - sent);
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "error writing (%s), closing socket\n", strerror(errno));
mutt_socket_close(conn);
return -1;
}
if (rc < len - sent)
mutt_debug(LL_DEBUG3, "short write (%d of %d bytes)\n", rc, len - sent);
sent += rc;
}
return sent;
}
/**
* mutt_socket_poll - Checks whether reads would block
* @param conn Connection to a server
* @param wait_secs How long to wait for a response
* @retval >0 There is data to read
* @retval 0 Read would block
* @retval -1 Connection doesn't support polling
*/
int mutt_socket_poll(struct Connection *conn, time_t wait_secs)
{
if (conn->bufpos < conn->available)
return conn->available - conn->bufpos;
if (conn->poll)
return conn->poll(conn, wait_secs);
return -1;
}
/**
* mutt_socket_readchar - simple read buffering to speed things up
* @param[in] conn Connection to a server
* @param[out] c Character that was read
* @retval 1 Success
* @retval -1 Error
*/
int mutt_socket_readchar(struct Connection *conn, char *c)
{
if (conn->bufpos >= conn->available)
{
if (conn->fd >= 0)
conn->available = conn->read(conn, conn->inbuf, sizeof(conn->inbuf));
else
{
mutt_debug(LL_DEBUG1, "attempt to read from closed connection\n");
return -1;
}
conn->bufpos = 0;
if (conn->available == 0)
{
mutt_error(_("Connection to %s closed"), conn->account.host);
}
if (conn->available <= 0)
{
mutt_socket_close(conn);
return -1;
}
}
*c = conn->inbuf[conn->bufpos];
conn->bufpos++;
return 1;
}
/**
* mutt_socket_readln_d - Read a line from a socket
* @param buf Buffer to store the line
* @param buflen Length of data to write
* @param conn Connection to a server
* @param dbg Debug level for logging
* @retval >0 Success, number of bytes read
* @retval -1 Error
*/
int mutt_socket_readln_d(char *buf, size_t buflen, struct Connection *conn, int dbg)
{
char ch;
int i;
for (i = 0; i < buflen - 1; i++)
{
if (mutt_socket_readchar(conn, &ch) != 1)
{
buf[i] = '\0';
return -1;
}
if (ch == '\n')
break;
buf[i] = ch;
}
/* strip \r from \r\n termination */
if (i && (buf[i - 1] == '\r'))
i--;
buf[i] = '\0';
mutt_debug(dbg, "%d< %s\n", conn->fd, buf);
/* number of bytes read, not strlen */
return i + 1;
}
/**
* mutt_socket_new - allocate and initialise a new connection
* @param type Type of the new Connection
* @retval ptr New Connection
*/
struct Connection *mutt_socket_new(enum ConnectionType type)
{
struct Connection *conn = mutt_mem_calloc(1, sizeof(struct Connection));
conn->fd = -1;
if (type == MUTT_CONNECTION_TUNNEL)
{
mutt_tunnel_socket_setup(conn);
}
else if (type == MUTT_CONNECTION_SSL)
{
int rc = mutt_ssl_socket_setup(conn);
if (rc < 0)
FREE(&conn);
}
else
{
conn->read = raw_socket_read;
conn->write = raw_socket_write;
conn->open = raw_socket_open;
conn->close = raw_socket_close;
conn->poll = raw_socket_poll;
}
return conn;
}
/**
* mutt_socket_empty - Clear out any queued data
*
* The internal buffer is emptied and any data that has already arrived at this
* machine (in kernel buffers) is read and dropped.
*/
void mutt_socket_empty(struct Connection *conn)
{
if (!conn)
return;
char buf[1024];
int bytes;
while ((bytes = mutt_socket_poll(conn, 0)) > 0)
{
mutt_socket_read(conn, buf, MIN(bytes, sizeof(buf)));
}
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_4069_0 |
crossvul-cpp_data_bad_1906_2 | /*
* Copyright © 2014-2019 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <gio/gdesktopappinfo.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/vfs.h>
#include <sys/personality.h>
#include <grp.h>
#include <unistd.h>
#include <gio/gunixfdlist.h>
#ifdef HAVE_DCONF
#include <dconf/dconf.h>
#endif
#ifdef HAVE_LIBMALCONTENT
#include <libmalcontent/malcontent.h>
#endif
#ifdef ENABLE_SECCOMP
#include <seccomp.h>
#endif
#ifdef ENABLE_XAUTH
#include <X11/Xauth.h>
#endif
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include "libglnx/libglnx.h"
#include "flatpak-run-private.h"
#include "flatpak-proxy.h"
#include "flatpak-utils-base-private.h"
#include "flatpak-dir-private.h"
#include "flatpak-instance-private.h"
#include "flatpak-systemd-dbus-generated.h"
#include "flatpak-document-dbus-generated.h"
#include "flatpak-error.h"
#define DEFAULT_SHELL "/bin/sh"
const char * const abs_usrmerged_dirs[] =
{
"/bin",
"/lib",
"/lib32",
"/lib64",
"/sbin",
NULL
};
const char * const *flatpak_abs_usrmerged_dirs = abs_usrmerged_dirs;
static char *
extract_unix_path_from_dbus_address (const char *address)
{
const char *path, *path_end;
if (address == NULL)
return NULL;
if (!g_str_has_prefix (address, "unix:"))
return NULL;
path = strstr (address, "path=");
if (path == NULL)
return NULL;
path += strlen ("path=");
path_end = path;
while (*path_end != 0 && *path_end != ',')
path_end++;
return g_strndup (path, path_end - path);
}
#ifdef ENABLE_XAUTH
static gboolean
auth_streq (char *str,
char *au_str,
int au_len)
{
return au_len == strlen (str) && memcmp (str, au_str, au_len) == 0;
}
static gboolean
xauth_entry_should_propagate (Xauth *xa,
char *hostname,
char *number)
{
/* ensure entry isn't for remote access */
if (xa->family != FamilyLocal && xa->family != FamilyWild)
return FALSE;
/* ensure entry is for this machine */
if (xa->family == FamilyLocal && !auth_streq (hostname, xa->address, xa->address_length))
return FALSE;
/* ensure entry is for this session */
if (xa->number != NULL && !auth_streq (number, xa->number, xa->number_length))
return FALSE;
return TRUE;
}
static void
write_xauth (char *number, FILE *output)
{
Xauth *xa, local_xa;
char *filename;
FILE *f;
struct utsname unames;
if (uname (&unames))
{
g_warning ("uname failed");
return;
}
filename = XauFileName ();
f = fopen (filename, "rb");
if (f == NULL)
return;
while (TRUE)
{
xa = XauReadAuth (f);
if (xa == NULL)
break;
if (xauth_entry_should_propagate (xa, unames.nodename, number))
{
local_xa = *xa;
if (local_xa.number)
{
local_xa.number = "99";
local_xa.number_length = 2;
}
if (!XauWriteAuth (output, &local_xa))
g_warning ("xauth write error");
}
XauDisposeAuth (xa);
}
fclose (f);
}
#endif /* ENABLE_XAUTH */
static void
flatpak_run_add_x11_args (FlatpakBwrap *bwrap,
gboolean allowed)
{
g_autofree char *x11_socket = NULL;
const char *display;
/* Always cover /tmp/.X11-unix, that way we never see the host one in case
* we have access to the host /tmp. If you request X access we'll put the right
* thing in this anyway.
*/
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/tmp/.X11-unix",
NULL);
if (!allowed)
{
flatpak_bwrap_unset_env (bwrap, "DISPLAY");
return;
}
g_debug ("Allowing x11 access");
display = g_getenv ("DISPLAY");
if (display && display[0] == ':' && g_ascii_isdigit (display[1]))
{
const char *display_nr = &display[1];
const char *display_nr_end = display_nr;
g_autofree char *d = NULL;
while (g_ascii_isdigit (*display_nr_end))
display_nr_end++;
d = g_strndup (display_nr, display_nr_end - display_nr);
x11_socket = g_strdup_printf ("/tmp/.X11-unix/X%s", d);
flatpak_bwrap_add_args (bwrap,
"--ro-bind", x11_socket, "/tmp/.X11-unix/X99",
NULL);
flatpak_bwrap_set_env (bwrap, "DISPLAY", ":99.0", TRUE);
#ifdef ENABLE_XAUTH
g_auto(GLnxTmpfile) xauth_tmpf = { 0, };
if (glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, "/tmp", &xauth_tmpf, NULL))
{
FILE *output = fdopen (xauth_tmpf.fd, "wb");
if (output != NULL)
{
/* fd is now owned by output, steal it from the tmpfile */
int tmp_fd = dup (glnx_steal_fd (&xauth_tmpf.fd));
if (tmp_fd != -1)
{
g_autofree char *dest = g_strdup_printf ("/run/user/%d/Xauthority", getuid ());
write_xauth (d, output);
flatpak_bwrap_add_args_data_fd (bwrap, "--ro-bind-data", tmp_fd, dest);
flatpak_bwrap_set_env (bwrap, "XAUTHORITY", dest, TRUE);
}
fclose (output);
if (tmp_fd != -1)
lseek (tmp_fd, 0, SEEK_SET);
}
}
#endif
}
else
{
flatpak_bwrap_unset_env (bwrap, "DISPLAY");
}
}
static gboolean
flatpak_run_add_wayland_args (FlatpakBwrap *bwrap)
{
const char *wayland_display;
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *wayland_socket = NULL;
g_autofree char *sandbox_wayland_socket = NULL;
gboolean res = FALSE;
struct stat statbuf;
wayland_display = g_getenv ("WAYLAND_DISPLAY");
if (!wayland_display)
wayland_display = "wayland-0";
wayland_socket = g_build_filename (user_runtime_dir, wayland_display, NULL);
sandbox_wayland_socket = g_strdup_printf ("/run/user/%d/%s", getuid (), wayland_display);
if (stat (wayland_socket, &statbuf) == 0 &&
(statbuf.st_mode & S_IFMT) == S_IFSOCK)
{
res = TRUE;
flatpak_bwrap_add_args (bwrap,
"--ro-bind", wayland_socket, sandbox_wayland_socket,
NULL);
}
return res;
}
static void
flatpak_run_add_ssh_args (FlatpakBwrap *bwrap)
{
const char * auth_socket;
g_autofree char * sandbox_auth_socket = NULL;
auth_socket = g_getenv ("SSH_AUTH_SOCK");
if (!auth_socket)
return; /* ssh agent not present */
if (!g_file_test (auth_socket, G_FILE_TEST_EXISTS))
{
/* Let's clean it up, so that the application will not try to connect */
flatpak_bwrap_unset_env (bwrap, "SSH_AUTH_SOCK");
return;
}
sandbox_auth_socket = g_strdup_printf ("/run/user/%d/ssh-auth", getuid ());
flatpak_bwrap_add_args (bwrap,
"--ro-bind", auth_socket, sandbox_auth_socket,
NULL);
flatpak_bwrap_set_env (bwrap, "SSH_AUTH_SOCK", sandbox_auth_socket, TRUE);
}
static void
flatpak_run_add_pcsc_args (FlatpakBwrap *bwrap)
{
const char * pcsc_socket;
const char * sandbox_pcsc_socket = "/run/pcscd/pcscd.comm";
pcsc_socket = g_getenv ("PCSCLITE_CSOCK_NAME");
if (pcsc_socket)
{
if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_unset_env (bwrap, "PCSCLITE_CSOCK_NAME");
return;
}
}
else
{
pcsc_socket = "/run/pcscd/pcscd.comm";
if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))
return;
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", pcsc_socket, sandbox_pcsc_socket,
NULL);
flatpak_bwrap_set_env (bwrap, "PCSCLITE_CSOCK_NAME", sandbox_pcsc_socket, TRUE);
}
static gboolean
flatpak_run_cups_check_server_is_socket (const char *server)
{
if (g_str_has_prefix (server, "/") && strstr (server, ":") == NULL)
return TRUE;
return FALSE;
}
/* Try to find a default server from a cups confguration file */
static char *
flatpak_run_get_cups_server_name_config (const char *path)
{
g_autoptr(GFile) file = g_file_new_for_path (path);
g_autoptr(GError) my_error = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
size_t len;
input_stream = g_file_read (file, NULL, &my_error);
if (my_error)
{
g_debug ("CUPS configuration file '%s': %s", path, my_error->message);
return NULL;
}
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);
if (line == NULL)
break;
g_strchug (line);
if ((*line == '\0') || (*line == '#'))
continue;
g_auto(GStrv) tokens = g_strsplit (line, " ", 2);
if ((tokens[0] != NULL) && (tokens[1] != NULL))
{
if (strcmp ("ServerName", tokens[0]) == 0)
{
g_strchug (tokens[1]);
if (flatpak_run_cups_check_server_is_socket (tokens[1]))
return g_strdup (tokens[1]);
}
}
}
return NULL;
}
static char *
flatpak_run_get_cups_server_name (void)
{
g_autofree char * cups_server = NULL;
g_autofree char * cups_config_path = NULL;
/* TODO
* we don't currently support cups servers located on the network, if such
* server is detected, we simply ignore it and in the worst case we fallback
* to the default socket
*/
cups_server = g_strdup (g_getenv ("CUPS_SERVER"));
if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))
return g_steal_pointer (&cups_server);
g_clear_pointer (&cups_server, g_free);
cups_config_path = g_build_filename (g_get_home_dir (), ".cups/client.conf", NULL);
cups_server = flatpak_run_get_cups_server_name_config (cups_config_path);
if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))
return g_steal_pointer (&cups_server);
g_clear_pointer (&cups_server, g_free);
cups_server = flatpak_run_get_cups_server_name_config ("/etc/cups/client.conf");
if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))
return g_steal_pointer (&cups_server);
// Fallback to default socket
return g_strdup ("/var/run/cups/cups.sock");
}
static void
flatpak_run_add_cups_args (FlatpakBwrap *bwrap)
{
g_autofree char * sandbox_server_name = g_strdup ("/var/run/cups/cups.sock");
g_autofree char * cups_server_name = flatpak_run_get_cups_server_name ();
if (!g_file_test (cups_server_name, G_FILE_TEST_EXISTS))
{
g_debug ("Could not find CUPS server");
return;
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", cups_server_name, sandbox_server_name,
NULL);
}
/* Try to find a default server from a pulseaudio confguration file */
static char *
flatpak_run_get_pulseaudio_server_user_config (const char *path)
{
g_autoptr(GFile) file = g_file_new_for_path (path);
g_autoptr(GError) my_error = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
size_t len;
input_stream = g_file_read (file, NULL, &my_error);
if (my_error)
{
g_debug ("Pulseaudio user configuration file '%s': %s", path, my_error->message);
return NULL;
}
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);
if (line == NULL)
break;
g_strchug (line);
if ((*line == '\0') || (*line == ';') || (*line == '#'))
continue;
if (g_str_has_prefix (line, ".include "))
{
g_autofree char *rec_path = g_strdup (line + 9);
g_strstrip (rec_path);
char *found = flatpak_run_get_pulseaudio_server_user_config (rec_path);
if (found)
return found;
}
else if (g_str_has_prefix (line, "["))
{
return NULL;
}
else
{
g_auto(GStrv) tokens = g_strsplit (line, "=", 2);
if ((tokens[0] != NULL) && (tokens[1] != NULL))
{
g_strchomp (tokens[0]);
if (strcmp ("default-server", tokens[0]) == 0)
{
g_strstrip (tokens[1]);
g_debug ("Found pulseaudio socket from configuration file '%s': %s", path, tokens[1]);
return g_strdup (tokens[1]);
}
}
}
}
return NULL;
}
static char *
flatpak_run_get_pulseaudio_server (void)
{
const char * pulse_clientconfig;
char *pulse_server;
g_autofree char *pulse_user_config = NULL;
pulse_server = g_strdup (g_getenv ("PULSE_SERVER"));
if (pulse_server)
return pulse_server;
pulse_clientconfig = g_getenv ("PULSE_CLIENTCONFIG");
if (pulse_clientconfig)
return flatpak_run_get_pulseaudio_server_user_config (pulse_clientconfig);
pulse_user_config = g_build_filename (g_get_user_config_dir (), "pulse/client.conf", NULL);
pulse_server = flatpak_run_get_pulseaudio_server_user_config (pulse_user_config);
if (pulse_server)
return pulse_server;
pulse_server = flatpak_run_get_pulseaudio_server_user_config ("/etc/pulse/client.conf");
if (pulse_server)
return pulse_server;
return NULL;
}
static char *
flatpak_run_parse_pulse_server (const char *value)
{
g_auto(GStrv) servers = g_strsplit (value, " ", 0);
gsize i;
for (i = 0; servers[i] != NULL; i++)
{
const char *server = servers[i];
if (g_str_has_prefix (server, "{"))
{
const char * closing = strstr (server, "}");
if (closing == NULL)
continue;
server = closing + 1;
}
if (g_str_has_prefix (server, "unix:"))
return g_strdup (server + 5);
}
return NULL;
}
/*
* Get the machine ID as used by PulseAudio. This is the systemd/D-Bus
* machine ID, or failing that, the hostname.
*/
static char *
flatpak_run_get_pulse_machine_id (void)
{
static const char * const machine_ids[] =
{
"/etc/machine-id",
"/var/lib/dbus/machine-id",
};
gsize i;
for (i = 0; i < G_N_ELEMENTS (machine_ids); i++)
{
g_autofree char *ret = NULL;
if (g_file_get_contents (machine_ids[i], &ret, NULL, NULL))
{
gsize j;
g_strstrip (ret);
for (j = 0; ret[j] != '\0'; j++)
{
if (!g_ascii_isxdigit (ret[j]))
break;
}
if (ret[0] != '\0' && ret[j] == '\0')
return g_steal_pointer (&ret);
}
}
return g_strdup (g_get_host_name ());
}
/*
* Get the directory used by PulseAudio for its configuration.
*/
static char *
flatpak_run_get_pulse_home (void)
{
/* Legacy path ~/.pulse is tried first, for compatibility */
{
const char *parent = g_get_home_dir ();
g_autofree char *ret = g_build_filename (parent, ".pulse", NULL);
if (g_file_test (ret, G_FILE_TEST_IS_DIR))
return g_steal_pointer (&ret);
}
/* The more modern path, usually ~/.config/pulse */
{
const char *parent = g_get_user_config_dir ();
/* Usually ~/.config/pulse */
g_autofree char *ret = g_build_filename (parent, "pulse", NULL);
if (g_file_test (ret, G_FILE_TEST_IS_DIR))
return g_steal_pointer (&ret);
}
return NULL;
}
/*
* Get the runtime directory used by PulseAudio for its socket.
*/
static char *
flatpak_run_get_pulse_runtime_dir (void)
{
const char *val = NULL;
val = g_getenv ("PULSE_RUNTIME_PATH");
if (val != NULL)
return realpath (val, NULL);
{
const char *user_runtime_dir = g_get_user_runtime_dir ();
if (user_runtime_dir != NULL)
{
g_autofree char *dir = g_build_filename (user_runtime_dir, "pulse", NULL);
if (g_file_test (dir, G_FILE_TEST_IS_DIR))
return realpath (dir, NULL);
}
}
{
g_autofree char *pulse_home = flatpak_run_get_pulse_home ();
g_autofree char *machine_id = flatpak_run_get_pulse_machine_id ();
if (pulse_home != NULL && machine_id != NULL)
{
/* This is usually a symlink, but we take its realpath() anyway */
g_autofree char *dir = g_strdup_printf ("%s/%s-runtime", pulse_home, machine_id);
if (g_file_test (dir, G_FILE_TEST_IS_DIR))
return realpath (dir, NULL);
}
}
return NULL;
}
static void
flatpak_run_add_pulseaudio_args (FlatpakBwrap *bwrap)
{
g_autofree char *pulseaudio_server = flatpak_run_get_pulseaudio_server ();
g_autofree char *pulseaudio_socket = NULL;
g_autofree char *pulse_runtime_dir = flatpak_run_get_pulse_runtime_dir ();
if (pulseaudio_server)
pulseaudio_socket = flatpak_run_parse_pulse_server (pulseaudio_server);
if (!pulseaudio_socket)
{
pulseaudio_socket = g_build_filename (pulse_runtime_dir, "native", NULL);
if (!g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))
g_clear_pointer (&pulseaudio_socket, g_free);
}
if (!pulseaudio_socket)
{
pulseaudio_socket = realpath ("/var/run/pulse/native", NULL);
if (pulseaudio_socket && !g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))
g_clear_pointer (&pulseaudio_socket, g_free);
}
flatpak_bwrap_unset_env (bwrap, "PULSE_SERVER");
if (pulseaudio_socket && g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))
{
gboolean share_shm = FALSE; /* TODO: When do we add this? */
g_autofree char *client_config = g_strdup_printf ("enable-shm=%s\n", share_shm ? "yes" : "no");
g_autofree char *sandbox_socket_path = g_strdup_printf ("/run/user/%d/pulse/native", getuid ());
g_autofree char *pulse_server = g_strdup_printf ("unix:/run/user/%d/pulse/native", getuid ());
g_autofree char *config_path = g_strdup_printf ("/run/user/%d/pulse/config", getuid ());
/* FIXME - error handling */
if (!flatpak_bwrap_add_args_data (bwrap, "pulseaudio", client_config, -1, config_path, NULL))
return;
flatpak_bwrap_add_args (bwrap,
"--ro-bind", pulseaudio_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (bwrap, "PULSE_SERVER", pulse_server, TRUE);
flatpak_bwrap_set_env (bwrap, "PULSE_CLIENTCONFIG", config_path, TRUE);
}
else
g_debug ("Could not find pulseaudio socket");
/* Also allow ALSA access. This was added in 1.8, and is not ideally named. However,
* since the practical permission of ALSA and PulseAudio are essentially the same, and
* since we don't want to add more permissions for something we plan to replace with
* portals/pipewire going forward we reinterpret pulseaudio to also mean ALSA.
*/
if (g_file_test ("/dev/snd", G_FILE_TEST_IS_DIR))
flatpak_bwrap_add_args (bwrap, "--dev-bind", "/dev/snd", "/dev/snd", NULL);
}
static void
flatpak_run_add_resolved_args (FlatpakBwrap *bwrap)
{
const char *resolved_socket = "/run/systemd/resolve/io.systemd.Resolve";
if (g_file_test (resolved_socket, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--bind", resolved_socket, resolved_socket, NULL);
}
static void
flatpak_run_add_journal_args (FlatpakBwrap *bwrap)
{
g_autofree char *journal_socket_socket = g_strdup ("/run/systemd/journal/socket");
g_autofree char *journal_stdout_socket = g_strdup ("/run/systemd/journal/stdout");
if (g_file_test (journal_socket_socket, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", journal_socket_socket, journal_socket_socket,
NULL);
}
if (g_file_test (journal_stdout_socket, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", journal_stdout_socket, journal_stdout_socket,
NULL);
}
}
static char *
create_proxy_socket (char *template)
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, ".dbus-proxy", NULL);
g_autofree char *proxy_socket = g_build_filename (proxy_socket_dir, template, NULL);
int fd;
if (!glnx_shutil_mkdir_p_at (AT_FDCWD, proxy_socket_dir, 0755, NULL, NULL))
return NULL;
fd = g_mkstemp (proxy_socket);
if (fd == -1)
return NULL;
close (fd);
return g_steal_pointer (&proxy_socket);
}
static gboolean
flatpak_run_add_system_dbus_args (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
FlatpakContext *context,
FlatpakRunFlags flags)
{
gboolean unrestricted, no_proxy;
const char *dbus_address = g_getenv ("DBUS_SYSTEM_BUS_ADDRESS");
g_autofree char *real_dbus_address = NULL;
g_autofree char *dbus_system_socket = NULL;
unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) != 0;
if (unrestricted)
g_debug ("Allowing system-dbus access");
no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY) != 0;
if (dbus_address != NULL)
dbus_system_socket = extract_unix_path_from_dbus_address (dbus_address);
else if (g_file_test ("/var/run/dbus/system_bus_socket", G_FILE_TEST_EXISTS))
dbus_system_socket = g_strdup ("/var/run/dbus/system_bus_socket");
if (dbus_system_socket != NULL && unrestricted)
{
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", dbus_system_socket, "/run/dbus/system_bus_socket",
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SYSTEM_BUS_ADDRESS", "unix:path=/run/dbus/system_bus_socket", TRUE);
return TRUE;
}
else if (!no_proxy && flatpak_context_get_needs_system_bus_proxy (context))
{
g_autofree char *proxy_socket = create_proxy_socket ("system-bus-proxy-XXXXXX");
if (proxy_socket == NULL)
return FALSE;
if (dbus_address)
real_dbus_address = g_strdup (dbus_address);
else
real_dbus_address = g_strdup_printf ("unix:path=%s", dbus_system_socket);
flatpak_bwrap_add_args (proxy_arg_bwrap, real_dbus_address, proxy_socket, NULL);
if (!unrestricted)
flatpak_context_add_bus_filters (context, NULL, FALSE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);
if ((flags & FLATPAK_RUN_FLAG_LOG_SYSTEM_BUS) != 0)
flatpak_bwrap_add_args (proxy_arg_bwrap, "--log", NULL);
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", proxy_socket, "/run/dbus/system_bus_socket",
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SYSTEM_BUS_ADDRESS", "unix:path=/run/dbus/system_bus_socket", TRUE);
return TRUE;
}
return FALSE;
}
static gboolean
flatpak_run_add_session_dbus_args (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
FlatpakContext *context,
FlatpakRunFlags flags,
const char *app_id)
{
gboolean unrestricted, no_proxy;
const char *dbus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
g_autofree char *dbus_session_socket = NULL;
g_autofree char *sandbox_socket_path = g_strdup_printf ("/run/user/%d/bus", getuid ());
g_autofree char *sandbox_dbus_address = g_strdup_printf ("unix:path=/run/user/%d/bus", getuid ());
unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) != 0;
if (dbus_address != NULL)
{
dbus_session_socket = extract_unix_path_from_dbus_address (dbus_address);
}
else
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
struct stat statbuf;
dbus_session_socket = g_build_filename (user_runtime_dir, "bus", NULL);
if (stat (dbus_session_socket, &statbuf) < 0
|| (statbuf.st_mode & S_IFMT) != S_IFSOCK
|| statbuf.st_uid != getuid ())
return FALSE;
}
if (unrestricted)
g_debug ("Allowing session-dbus access");
no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY) != 0;
if (dbus_session_socket != NULL && unrestricted)
{
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", dbus_session_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SESSION_BUS_ADDRESS", sandbox_dbus_address, TRUE);
return TRUE;
}
else if (!no_proxy && dbus_address != NULL)
{
g_autofree char *proxy_socket = create_proxy_socket ("session-bus-proxy-XXXXXX");
if (proxy_socket == NULL)
return FALSE;
flatpak_bwrap_add_args (proxy_arg_bwrap, dbus_address, proxy_socket, NULL);
if (!unrestricted)
{
flatpak_context_add_bus_filters (context, app_id, TRUE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);
/* Allow calling any interface+method on all portals, but only receive broadcasts under /org/desktop/portal */
flatpak_bwrap_add_arg (proxy_arg_bwrap,
"--call=org.freedesktop.portal.*=*");
flatpak_bwrap_add_arg (proxy_arg_bwrap,
"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*");
}
if ((flags & FLATPAK_RUN_FLAG_LOG_SESSION_BUS) != 0)
flatpak_bwrap_add_args (proxy_arg_bwrap, "--log", NULL);
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", proxy_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SESSION_BUS_ADDRESS", sandbox_dbus_address, TRUE);
return TRUE;
}
return FALSE;
}
static gboolean
flatpak_run_add_a11y_dbus_args (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
FlatpakContext *context,
FlatpakRunFlags flags)
{
g_autoptr(GDBusConnection) session_bus = NULL;
g_autofree char *a11y_address = NULL;
g_autoptr(GError) local_error = NULL;
g_autoptr(GDBusMessage) reply = NULL;
g_autoptr(GDBusMessage) msg = NULL;
g_autofree char *proxy_socket = NULL;
if ((flags & FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY) != 0)
return FALSE;
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
if (session_bus == NULL)
return FALSE;
msg = g_dbus_message_new_method_call ("org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus", "GetAddress");
g_dbus_message_set_body (msg, g_variant_new ("()"));
reply =
g_dbus_connection_send_message_with_reply_sync (session_bus, msg,
G_DBUS_SEND_MESSAGE_FLAGS_NONE,
30000,
NULL,
NULL,
NULL);
if (reply)
{
if (g_dbus_message_to_gerror (reply, &local_error))
{
if (!g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))
g_message ("Can't find a11y bus: %s", local_error->message);
}
else
{
g_variant_get (g_dbus_message_get_body (reply),
"(s)", &a11y_address);
}
}
if (!a11y_address)
return FALSE;
proxy_socket = create_proxy_socket ("a11y-bus-proxy-XXXXXX");
if (proxy_socket == NULL)
return FALSE;
g_autofree char *sandbox_socket_path = g_strdup_printf ("/run/user/%d/at-spi-bus", getuid ());
g_autofree char *sandbox_dbus_address = g_strdup_printf ("unix:path=/run/user/%d/at-spi-bus", getuid ());
flatpak_bwrap_add_args (proxy_arg_bwrap,
a11y_address,
proxy_socket, "--filter", "--sloppy-names",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Embed@/org/a11y/atspi/accessible/root",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Unembed@/org/a11y/atspi/accessible/root",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.Registry.GetRegisteredEvents@/org/a11y/atspi/registry",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetKeystrokeListeners@/org/a11y/atspi/registry/deviceeventcontroller",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetDeviceEventListeners@/org/a11y/atspi/registry/deviceeventcontroller",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersSync@/org/a11y/atspi/registry/deviceeventcontroller",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersAsync@/org/a11y/atspi/registry/deviceeventcontroller",
NULL);
if ((flags & FLATPAK_RUN_FLAG_LOG_A11Y_BUS) != 0)
flatpak_bwrap_add_args (proxy_arg_bwrap, "--log", NULL);
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", proxy_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (app_bwrap, "AT_SPI_BUS_ADDRESS", sandbox_dbus_address, TRUE);
return TRUE;
}
/* This wraps the argv in a bwrap call, primary to allow the
command to be run with a proper /.flatpak-info with data
taken from app_info_path */
static gboolean
add_bwrap_wrapper (FlatpakBwrap *bwrap,
const char *app_info_path,
GError **error)
{
glnx_autofd int app_info_fd = -1;
g_auto(GLnxDirFdIterator) dir_iter = { 0 };
struct dirent *dent;
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, ".dbus-proxy/", NULL);
app_info_fd = open (app_info_path, O_RDONLY | O_CLOEXEC);
if (app_info_fd == -1)
return glnx_throw_errno_prefix (error, _("Failed to open app info file"));
if (!glnx_dirfd_iterator_init_at (AT_FDCWD, "/", FALSE, &dir_iter, error))
return FALSE;
flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());
while (TRUE)
{
glnx_autofd int o_path_fd = -1;
struct statfs stfs;
if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dir_iter, &dent, NULL, error))
return FALSE;
if (dent == NULL)
break;
if (strcmp (dent->d_name, ".flatpak-info") == 0)
continue;
/* O_PATH + fstatfs is the magic that we need to statfs without automounting the target */
o_path_fd = openat (dir_iter.fd, dent->d_name, O_PATH | O_NOFOLLOW | O_CLOEXEC);
if (o_path_fd == -1 || fstatfs (o_path_fd, &stfs) != 0 || stfs.f_type == AUTOFS_SUPER_MAGIC)
continue; /* AUTOFS mounts are risky and can cause us to block (see issue #1633), so ignore it. Its unlikely the proxy needs such a directory. */
if (dent->d_type == DT_DIR)
{
if (strcmp (dent->d_name, "tmp") == 0 ||
strcmp (dent->d_name, "var") == 0 ||
strcmp (dent->d_name, "run") == 0)
flatpak_bwrap_add_arg (bwrap, "--bind");
else
flatpak_bwrap_add_arg (bwrap, "--ro-bind");
flatpak_bwrap_add_arg_printf (bwrap, "/%s", dent->d_name);
flatpak_bwrap_add_arg_printf (bwrap, "/%s", dent->d_name);
}
else if (dent->d_type == DT_LNK)
{
g_autofree gchar *target = NULL;
target = glnx_readlinkat_malloc (dir_iter.fd, dent->d_name,
NULL, error);
if (target == NULL)
return FALSE;
flatpak_bwrap_add_args (bwrap, "--symlink", target, NULL);
flatpak_bwrap_add_arg_printf (bwrap, "/%s", dent->d_name);
}
}
flatpak_bwrap_add_args (bwrap, "--bind", proxy_socket_dir, proxy_socket_dir, NULL);
/* This is a file rather than a bind mount, because it will then
not be unmounted from the namespace when the namespace dies. */
flatpak_bwrap_add_args_data_fd (bwrap, "--file", glnx_steal_fd (&app_info_fd), "/.flatpak-info");
if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))
return FALSE;
return TRUE;
}
static gboolean
start_dbus_proxy (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
const char *app_info_path,
GError **error)
{
char x = 'x';
const char *proxy;
g_autofree char *commandline = NULL;
g_autoptr(FlatpakBwrap) proxy_bwrap = NULL;
int sync_fds[2] = {-1, -1};
int proxy_start_index;
g_auto(GStrv) minimal_envp = NULL;
minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);
proxy_bwrap = flatpak_bwrap_new (NULL);
if (!add_bwrap_wrapper (proxy_bwrap, app_info_path, error))
return FALSE;
proxy = g_getenv ("FLATPAK_DBUSPROXY");
if (proxy == NULL)
proxy = DBUSPROXY;
flatpak_bwrap_add_arg (proxy_bwrap, proxy);
proxy_start_index = proxy_bwrap->argv->len;
if (pipe2 (sync_fds, O_CLOEXEC) < 0)
{
g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),
_("Unable to create sync pipe"));
return FALSE;
}
/* read end goes to app */
flatpak_bwrap_add_args_data_fd (app_bwrap, "--sync-fd", sync_fds[0], NULL);
/* write end goes to proxy */
flatpak_bwrap_add_fd (proxy_bwrap, sync_fds[1]);
flatpak_bwrap_add_arg_printf (proxy_bwrap, "--fd=%d", sync_fds[1]);
/* Note: This steals the fds from proxy_arg_bwrap */
flatpak_bwrap_append_bwrap (proxy_bwrap, proxy_arg_bwrap);
if (!flatpak_bwrap_bundle_args (proxy_bwrap, proxy_start_index, -1, TRUE, error))
return FALSE;
flatpak_bwrap_finish (proxy_bwrap);
commandline = flatpak_quote_argv ((const char **) proxy_bwrap->argv->pdata, -1);
g_debug ("Running '%s'", commandline);
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_async (NULL,
(char **) proxy_bwrap->argv->pdata,
NULL,
G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
flatpak_bwrap_child_setup_cb, proxy_bwrap->fds,
NULL, error))
return FALSE;
/* The write end can be closed now, otherwise the read below will hang of xdg-dbus-proxy
fails to start. */
g_clear_pointer (&proxy_bwrap, flatpak_bwrap_free);
/* Sync with proxy, i.e. wait until its listening on the sockets */
if (read (sync_fds[0], &x, 1) != 1)
{
g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),
_("Failed to sync with dbus proxy"));
return FALSE;
}
return TRUE;
}
static int
flatpak_extension_compare_by_path (gconstpointer _a,
gconstpointer _b)
{
const FlatpakExtension *a = _a;
const FlatpakExtension *b = _b;
return g_strcmp0 (a->directory, b->directory);
}
gboolean
flatpak_run_add_extension_args (FlatpakBwrap *bwrap,
GKeyFile *metakey,
FlatpakDecomposed *ref,
gboolean use_ld_so_cache,
char **extensions_out,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GString) used_extensions = g_string_new ("");
GList *extensions, *path_sorted_extensions, *l;
g_autoptr(GString) ld_library_path = g_string_new ("");
int count = 0;
g_autoptr(GHashTable) mounted_tmpfs =
g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
g_autoptr(GHashTable) created_symlink =
g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
g_autofree char *arch = flatpak_decomposed_dup_arch (ref);
const char *branch = flatpak_decomposed_get_branch (ref);
gboolean is_app = flatpak_decomposed_is_app (ref);
extensions = flatpak_list_extensions (metakey, arch, branch);
/* First we apply all the bindings, they are sorted alphabetically in order for parent directory
to be mounted before child directories */
path_sorted_extensions = g_list_copy (extensions);
path_sorted_extensions = g_list_sort (path_sorted_extensions, flatpak_extension_compare_by_path);
for (l = path_sorted_extensions; l != NULL; l = l->next)
{
FlatpakExtension *ext = l->data;
g_autofree char *directory = g_build_filename (is_app ? "/app" : "/usr", ext->directory, NULL);
g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);
g_autofree char *ref_file = g_build_filename (full_directory, ".ref", NULL);
g_autofree char *real_ref = g_build_filename (ext->files_path, ext->directory, ".ref", NULL);
if (ext->needs_tmpfs)
{
g_autofree char *parent = g_path_get_dirname (directory);
if (g_hash_table_lookup (mounted_tmpfs, parent) == NULL)
{
flatpak_bwrap_add_args (bwrap,
"--tmpfs", parent,
NULL);
g_hash_table_insert (mounted_tmpfs, g_steal_pointer (&parent), "mounted");
}
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", ext->files_path, full_directory,
NULL);
if (g_file_test (real_ref, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--lock-file", ref_file,
NULL);
}
g_list_free (path_sorted_extensions);
/* Then apply library directories and file merging, in extension prio order */
for (l = extensions; l != NULL; l = l->next)
{
FlatpakExtension *ext = l->data;
g_autofree char *directory = g_build_filename (is_app ? "/app" : "/usr", ext->directory, NULL);
g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);
int i;
if (used_extensions->len > 0)
g_string_append (used_extensions, ";");
g_string_append (used_extensions, ext->installed_id);
g_string_append (used_extensions, "=");
if (ext->commit != NULL)
g_string_append (used_extensions, ext->commit);
else
g_string_append (used_extensions, "local");
if (ext->add_ld_path)
{
g_autofree char *ld_path = g_build_filename (full_directory, ext->add_ld_path, NULL);
if (use_ld_so_cache)
{
g_autofree char *contents = g_strconcat (ld_path, "\n", NULL);
/* We prepend app or runtime and a counter in order to get the include order correct for the conf files */
g_autofree char *ld_so_conf_file = g_strdup_printf ("%s-%03d-%s.conf", flatpak_decomposed_get_kind_str (ref), ++count, ext->installed_id);
g_autofree char *ld_so_conf_file_path = g_build_filename ("/run/flatpak/ld.so.conf.d", ld_so_conf_file, NULL);
if (!flatpak_bwrap_add_args_data (bwrap, "ld-so-conf",
contents, -1, ld_so_conf_file_path, error))
return FALSE;
}
else
{
if (ld_library_path->len != 0)
g_string_append (ld_library_path, ":");
g_string_append (ld_library_path, ld_path);
}
}
for (i = 0; ext->merge_dirs != NULL && ext->merge_dirs[i] != NULL; i++)
{
g_autofree char *parent = g_path_get_dirname (directory);
g_autofree char *merge_dir = g_build_filename (parent, ext->merge_dirs[i], NULL);
g_autofree char *source_dir = g_build_filename (ext->files_path, ext->merge_dirs[i], NULL);
g_auto(GLnxDirFdIterator) source_iter = { 0 };
struct dirent *dent;
if (glnx_dirfd_iterator_init_at (AT_FDCWD, source_dir, TRUE, &source_iter, NULL))
{
while (glnx_dirfd_iterator_next_dent (&source_iter, &dent, NULL, NULL) && dent != NULL)
{
g_autofree char *symlink_path = g_build_filename (merge_dir, dent->d_name, NULL);
/* Only create the first, because extensions are listed in prio order */
if (g_hash_table_lookup (created_symlink, symlink_path) == NULL)
{
g_autofree char *symlink = g_build_filename (directory, ext->merge_dirs[i], dent->d_name, NULL);
flatpak_bwrap_add_args (bwrap,
"--symlink", symlink, symlink_path,
NULL);
g_hash_table_insert (created_symlink, g_steal_pointer (&symlink_path), "created");
}
}
}
}
}
g_list_free_full (extensions, (GDestroyNotify) flatpak_extension_free);
if (ld_library_path->len != 0)
{
const gchar *old_ld_path = g_environ_getenv (bwrap->envp, "LD_LIBRARY_PATH");
if (old_ld_path != NULL && *old_ld_path != 0)
{
if (is_app)
{
g_string_append (ld_library_path, ":");
g_string_append (ld_library_path, old_ld_path);
}
else
{
g_string_prepend (ld_library_path, ":");
g_string_prepend (ld_library_path, old_ld_path);
}
}
flatpak_bwrap_set_env (bwrap, "LD_LIBRARY_PATH", ld_library_path->str, TRUE);
}
if (extensions_out)
*extensions_out = g_string_free (g_steal_pointer (&used_extensions), FALSE);
return TRUE;
}
gboolean
flatpak_run_add_environment_args (FlatpakBwrap *bwrap,
const char *app_info_path,
FlatpakRunFlags flags,
const char *app_id,
FlatpakContext *context,
GFile *app_id_dir,
GPtrArray *previous_app_id_dirs,
FlatpakExports **exports_out,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GError) my_error = NULL;
g_autoptr(FlatpakExports) exports = NULL;
g_autoptr(FlatpakBwrap) proxy_arg_bwrap = flatpak_bwrap_new (flatpak_bwrap_empty_env);
gboolean has_wayland = FALSE;
gboolean allow_x11 = FALSE;
if ((context->shares & FLATPAK_CONTEXT_SHARED_IPC) == 0)
{
g_debug ("Disallowing ipc access");
flatpak_bwrap_add_args (bwrap, "--unshare-ipc", NULL);
}
if ((context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) == 0)
{
g_debug ("Disallowing network access");
flatpak_bwrap_add_args (bwrap, "--unshare-net", NULL);
}
if (context->devices & FLATPAK_CONTEXT_DEVICE_ALL)
{
flatpak_bwrap_add_args (bwrap,
"--dev-bind", "/dev", "/dev",
NULL);
/* Don't expose the host /dev/shm, just the device nodes, unless explicitly allowed */
if (g_file_test ("/dev/shm", G_FILE_TEST_IS_DIR))
{
if ((context->devices & FLATPAK_CONTEXT_DEVICE_SHM) == 0)
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/dev/shm",
NULL);
}
else if (g_file_test ("/dev/shm", G_FILE_TEST_IS_SYMLINK))
{
g_autofree char *link = flatpak_readlink ("/dev/shm", NULL);
/* On debian (with sysv init) the host /dev/shm is a symlink to /run/shm, so we can't
mount on top of it. */
if (g_strcmp0 (link, "/run/shm") == 0)
{
if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM &&
g_file_test ("/run/shm", G_FILE_TEST_IS_DIR))
flatpak_bwrap_add_args (bwrap,
"--bind", "/run/shm", "/run/shm",
NULL);
else
flatpak_bwrap_add_args (bwrap,
"--dir", "/run/shm",
NULL);
}
else
g_warning ("Unexpected /dev/shm symlink %s", link);
}
}
else
{
flatpak_bwrap_add_args (bwrap,
"--dev", "/dev",
NULL);
if (context->devices & FLATPAK_CONTEXT_DEVICE_DRI)
{
g_debug ("Allowing dri access");
int i;
char *dri_devices[] = {
"/dev/dri",
/* mali */
"/dev/mali",
"/dev/mali0",
"/dev/umplock",
/* nvidia */
"/dev/nvidiactl",
"/dev/nvidia-modeset",
/* nvidia OpenCL/CUDA */
"/dev/nvidia-uvm",
"/dev/nvidia-uvm-tools",
};
for (i = 0; i < G_N_ELEMENTS (dri_devices); i++)
{
if (g_file_test (dri_devices[i], G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--dev-bind", dri_devices[i], dri_devices[i], NULL);
}
/* Each Nvidia card gets its own device.
This is a fairly arbitrary limit but ASUS sells mining boards supporting 20 in theory. */
char nvidia_dev[14]; /* /dev/nvidia plus up to 2 digits */
for (i = 0; i < 20; i++)
{
g_snprintf (nvidia_dev, sizeof (nvidia_dev), "/dev/nvidia%d", i);
if (g_file_test (nvidia_dev, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--dev-bind", nvidia_dev, nvidia_dev, NULL);
}
}
if (context->devices & FLATPAK_CONTEXT_DEVICE_KVM)
{
g_debug ("Allowing kvm access");
if (g_file_test ("/dev/kvm", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--dev-bind", "/dev/kvm", "/dev/kvm", NULL);
}
if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM)
{
/* This is a symlink to /run/shm on debian, so bind to real target */
g_autofree char *real_dev_shm = realpath ("/dev/shm", NULL);
g_debug ("Allowing /dev/shm access (as %s)", real_dev_shm);
if (real_dev_shm != NULL)
flatpak_bwrap_add_args (bwrap, "--bind", real_dev_shm, "/dev/shm", NULL);
}
}
flatpak_context_append_bwrap_filesystem (context, bwrap, app_id, app_id_dir, previous_app_id_dirs, &exports);
if (context->sockets & FLATPAK_CONTEXT_SOCKET_WAYLAND)
{
g_debug ("Allowing wayland access");
has_wayland = flatpak_run_add_wayland_args (bwrap);
}
if ((context->sockets & FLATPAK_CONTEXT_SOCKET_FALLBACK_X11) != 0)
allow_x11 = !has_wayland;
else
allow_x11 = (context->sockets & FLATPAK_CONTEXT_SOCKET_X11) != 0;
flatpak_run_add_x11_args (bwrap, allow_x11);
if (context->sockets & FLATPAK_CONTEXT_SOCKET_SSH_AUTH)
{
flatpak_run_add_ssh_args (bwrap);
}
if (context->sockets & FLATPAK_CONTEXT_SOCKET_PULSEAUDIO)
{
g_debug ("Allowing pulseaudio access");
flatpak_run_add_pulseaudio_args (bwrap);
}
if (context->sockets & FLATPAK_CONTEXT_SOCKET_PCSC)
{
flatpak_run_add_pcsc_args (bwrap);
}
if (context->sockets & FLATPAK_CONTEXT_SOCKET_CUPS)
{
flatpak_run_add_cups_args (bwrap);
}
flatpak_run_add_session_dbus_args (bwrap, proxy_arg_bwrap, context, flags, app_id);
flatpak_run_add_system_dbus_args (bwrap, proxy_arg_bwrap, context, flags);
flatpak_run_add_a11y_dbus_args (bwrap, proxy_arg_bwrap, context, flags);
if (g_environ_getenv (bwrap->envp, "LD_LIBRARY_PATH") != NULL)
{
/* LD_LIBRARY_PATH is overridden for setuid helper, so pass it as cmdline arg */
flatpak_bwrap_add_args (bwrap,
"--setenv", "LD_LIBRARY_PATH", g_environ_getenv (bwrap->envp, "LD_LIBRARY_PATH"),
NULL);
flatpak_bwrap_unset_env (bwrap, "LD_LIBRARY_PATH");
}
if (g_environ_getenv (bwrap->envp, "TMPDIR") != NULL)
{
/* TMPDIR is overridden for setuid helper, so pass it as cmdline arg */
flatpak_bwrap_add_args (bwrap,
"--setenv", "TMPDIR", g_environ_getenv (bwrap->envp, "TMPDIR"),
NULL);
flatpak_bwrap_unset_env (bwrap, "TMPDIR");
}
/* Must run this before spawning the dbus proxy, to ensure it
ends up in the app cgroup */
if (!flatpak_run_in_transient_unit (app_id, &my_error))
{
/* We still run along even if we don't get a cgroup, as nothing
really depends on it. Its just nice to have */
g_debug ("Failed to run in transient scope: %s", my_error->message);
g_clear_error (&my_error);
}
if (!flatpak_bwrap_is_empty (proxy_arg_bwrap) &&
!start_dbus_proxy (bwrap, proxy_arg_bwrap, app_info_path, error))
return FALSE;
if (exports_out)
*exports_out = g_steal_pointer (&exports);
return TRUE;
}
typedef struct
{
const char *env;
const char *val;
} ExportData;
static const ExportData default_exports[] = {
{"PATH", "/app/bin:/usr/bin"},
/* We always want to unset LD_LIBRARY_PATH to avoid inheriting weird
* dependencies from the host. But if not using ld.so.cache this is
* later set. */
{"LD_LIBRARY_PATH", NULL},
{"XDG_CONFIG_DIRS", "/app/etc/xdg:/etc/xdg"},
{"XDG_DATA_DIRS", "/app/share:/usr/share"},
{"SHELL", "/bin/sh"},
{"TMPDIR", NULL}, /* Unset TMPDIR as it may not exist in the sandbox */
/* Some env vars are common enough and will affect the sandbox badly
if set on the host. We clear these always. */
{"PYTHONPATH", NULL},
{"PERLLIB", NULL},
{"PERL5LIB", NULL},
{"XCURSOR_PATH", NULL},
};
static const ExportData no_ld_so_cache_exports[] = {
{"LD_LIBRARY_PATH", "/app/lib"},
};
static const ExportData devel_exports[] = {
{"ACLOCAL_PATH", "/app/share/aclocal"},
{"C_INCLUDE_PATH", "/app/include"},
{"CPLUS_INCLUDE_PATH", "/app/include"},
{"LDFLAGS", "-L/app/lib "},
{"PKG_CONFIG_PATH", "/app/lib/pkgconfig:/app/share/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig"},
{"LC_ALL", "en_US.utf8"},
};
static void
add_exports (GPtrArray *env_array,
const ExportData *exports,
gsize n_exports)
{
int i;
for (i = 0; i < n_exports; i++)
{
if (exports[i].val)
g_ptr_array_add (env_array, g_strdup_printf ("%s=%s", exports[i].env, exports[i].val));
}
}
char **
flatpak_run_get_minimal_env (gboolean devel, gboolean use_ld_so_cache)
{
GPtrArray *env_array;
static const char * const copy[] = {
"PWD",
"GDMSESSION",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"DESKTOP_SESSION",
"EMAIL_ADDRESS",
"HOME",
"HOSTNAME",
"LOGNAME",
"REAL_NAME",
"TERM",
"USER",
"USERNAME",
};
static const char * const copy_nodevel[] = {
"LANG",
"LANGUAGE",
"LC_ALL",
"LC_ADDRESS",
"LC_COLLATE",
"LC_CTYPE",
"LC_IDENTIFICATION",
"LC_MEASUREMENT",
"LC_MESSAGES",
"LC_MONETARY",
"LC_NAME",
"LC_NUMERIC",
"LC_PAPER",
"LC_TELEPHONE",
"LC_TIME",
};
int i;
env_array = g_ptr_array_new_with_free_func (g_free);
add_exports (env_array, default_exports, G_N_ELEMENTS (default_exports));
if (!use_ld_so_cache)
add_exports (env_array, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));
if (devel)
add_exports (env_array, devel_exports, G_N_ELEMENTS (devel_exports));
for (i = 0; i < G_N_ELEMENTS (copy); i++)
{
const char *current = g_getenv (copy[i]);
if (current)
g_ptr_array_add (env_array, g_strdup_printf ("%s=%s", copy[i], current));
}
if (!devel)
{
for (i = 0; i < G_N_ELEMENTS (copy_nodevel); i++)
{
const char *current = g_getenv (copy_nodevel[i]);
if (current)
g_ptr_array_add (env_array, g_strdup_printf ("%s=%s", copy_nodevel[i], current));
}
}
g_ptr_array_add (env_array, NULL);
return (char **) g_ptr_array_free (env_array, FALSE);
}
static char **
apply_exports (char **envp,
const ExportData *exports,
gsize n_exports)
{
int i;
for (i = 0; i < n_exports; i++)
{
const char *value = exports[i].val;
if (value)
envp = g_environ_setenv (envp, exports[i].env, value, TRUE);
else
envp = g_environ_unsetenv (envp, exports[i].env);
}
return envp;
}
void
flatpak_run_apply_env_default (FlatpakBwrap *bwrap, gboolean use_ld_so_cache)
{
bwrap->envp = apply_exports (bwrap->envp, default_exports, G_N_ELEMENTS (default_exports));
if (!use_ld_so_cache)
bwrap->envp = apply_exports (bwrap->envp, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));
}
static void
flatpak_run_apply_env_prompt (FlatpakBwrap *bwrap, const char *app_id)
{
/* A custom shell prompt. FLATPAK_ID is always set.
* PS1 can be overwritten by runtime metadata or by --env overrides
*/
flatpak_bwrap_set_env (bwrap, "FLATPAK_ID", app_id, TRUE);
flatpak_bwrap_set_env (bwrap, "PS1", "[📦 $FLATPAK_ID \\W]\\$ ", FALSE);
}
void
flatpak_run_apply_env_appid (FlatpakBwrap *bwrap,
GFile *app_dir)
{
g_autoptr(GFile) app_dir_data = NULL;
g_autoptr(GFile) app_dir_config = NULL;
g_autoptr(GFile) app_dir_cache = NULL;
app_dir_data = g_file_get_child (app_dir, "data");
app_dir_config = g_file_get_child (app_dir, "config");
app_dir_cache = g_file_get_child (app_dir, "cache");
flatpak_bwrap_set_env (bwrap, "XDG_DATA_HOME", flatpak_file_get_path_cached (app_dir_data), TRUE);
flatpak_bwrap_set_env (bwrap, "XDG_CONFIG_HOME", flatpak_file_get_path_cached (app_dir_config), TRUE);
flatpak_bwrap_set_env (bwrap, "XDG_CACHE_HOME", flatpak_file_get_path_cached (app_dir_cache), TRUE);
if (g_getenv ("XDG_DATA_HOME"))
flatpak_bwrap_set_env (bwrap, "HOST_XDG_DATA_HOME", g_getenv ("XDG_DATA_HOME"), TRUE);
if (g_getenv ("XDG_CONFIG_HOME"))
flatpak_bwrap_set_env (bwrap, "HOST_XDG_CONFIG_HOME", g_getenv ("XDG_CONFIG_HOME"), TRUE);
if (g_getenv ("XDG_CACHE_HOME"))
flatpak_bwrap_set_env (bwrap, "HOST_XDG_CACHE_HOME", g_getenv ("XDG_CACHE_HOME"), TRUE);
}
void
flatpak_run_apply_env_vars (FlatpakBwrap *bwrap, FlatpakContext *context)
{
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init (&iter, context->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *var = key;
const char *val = value;
if (val && val[0] != 0)
flatpak_bwrap_set_env (bwrap, var, val, TRUE);
else
flatpak_bwrap_unset_env (bwrap, var);
}
}
GFile *
flatpak_get_data_dir (const char *app_id)
{
g_autoptr(GFile) home = g_file_new_for_path (g_get_home_dir ());
g_autoptr(GFile) var_app = g_file_resolve_relative_path (home, ".var/app");
return g_file_get_child (var_app, app_id);
}
gboolean
flatpak_ensure_data_dir (GFile *app_id_dir,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GFile) data_dir = g_file_get_child (app_id_dir, "data");
g_autoptr(GFile) cache_dir = g_file_get_child (app_id_dir, "cache");
g_autoptr(GFile) fontconfig_cache_dir = g_file_get_child (cache_dir, "fontconfig");
g_autoptr(GFile) tmp_dir = g_file_get_child (cache_dir, "tmp");
g_autoptr(GFile) config_dir = g_file_get_child (app_id_dir, "config");
if (!flatpak_mkdir_p (data_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (cache_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (fontconfig_cache_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (tmp_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (config_dir, cancellable, error))
return FALSE;
return TRUE;
}
struct JobData
{
char *job;
GMainLoop *main_loop;
};
static void
job_removed_cb (SystemdManager *manager,
guint32 id,
char *job,
char *unit,
char *result,
struct JobData *data)
{
if (strcmp (job, data->job) == 0)
g_main_loop_quit (data->main_loop);
}
static gchar *
systemd_unit_name_escape (const gchar *in)
{
/* Adapted from systemd source */
GString * const str = g_string_sized_new (strlen (in));
for (; *in; in++)
{
if (g_ascii_isalnum (*in) || *in == ':' || *in == '_' || *in == '.')
g_string_append_c (str, *in);
else
g_string_append_printf (str, "\\x%02x", *in);
}
return g_string_free (str, FALSE);
}
gboolean
flatpak_run_in_transient_unit (const char *appid, GError **error)
{
g_autoptr(GDBusConnection) conn = NULL;
g_autofree char *path = NULL;
g_autofree char *address = NULL;
g_autofree char *name = NULL;
g_autofree char *appid_escaped = NULL;
g_autofree char *job = NULL;
SystemdManager *manager = NULL;
GVariantBuilder builder;
GVariant *properties = NULL;
GVariant *aux = NULL;
guint32 pid;
GMainLoop *main_loop = NULL;
struct JobData data;
gboolean res = FALSE;
g_autoptr(GMainContextPopDefault) main_context = NULL;
path = g_strdup_printf ("/run/user/%d/systemd/private", getuid ());
if (!g_file_test (path, G_FILE_TEST_EXISTS))
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,
_("No systemd user session available, cgroups not available"));
main_context = flatpak_main_context_new_default ();
main_loop = g_main_loop_new (main_context, FALSE);
address = g_strconcat ("unix:path=", path, NULL);
conn = g_dbus_connection_new_for_address_sync (address,
G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
NULL,
NULL, error);
if (!conn)
goto out;
manager = systemd_manager_proxy_new_sync (conn,
G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
NULL,
"/org/freedesktop/systemd1",
NULL, error);
if (!manager)
goto out;
appid_escaped = systemd_unit_name_escape (appid);
name = g_strdup_printf ("app-flatpak-%s-%d.scope", appid_escaped, getpid ());
g_variant_builder_init (&builder, G_VARIANT_TYPE ("a(sv)"));
pid = getpid ();
g_variant_builder_add (&builder, "(sv)",
"PIDs",
g_variant_new_fixed_array (G_VARIANT_TYPE ("u"),
&pid, 1, sizeof (guint32))
);
properties = g_variant_builder_end (&builder);
aux = g_variant_new_array (G_VARIANT_TYPE ("(sa(sv))"), NULL, 0);
if (!systemd_manager_call_start_transient_unit_sync (manager,
name,
"fail",
properties,
aux,
&job,
NULL,
error))
goto out;
data.job = job;
data.main_loop = main_loop;
g_signal_connect (manager, "job-removed", G_CALLBACK (job_removed_cb), &data);
g_main_loop_run (main_loop);
res = TRUE;
out:
if (main_loop)
g_main_loop_unref (main_loop);
if (manager)
g_object_unref (manager);
return res;
}
static void
add_font_path_args (FlatpakBwrap *bwrap)
{
g_autoptr(GString) xml_snippet = g_string_new ("");
gchar *path_build_tmp = NULL;
g_autoptr(GFile) user_font1 = NULL;
g_autoptr(GFile) user_font2 = NULL;
g_autoptr(GFile) user_font_cache = NULL;
g_auto(GStrv) system_cache_dirs = NULL;
gboolean found_cache = FALSE;
int i;
g_string_append (xml_snippet,
"<?xml version=\"1.0\"?>\n"
"<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n"
"<fontconfig>\n");
if (g_file_test (SYSTEM_FONTS_DIR, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", SYSTEM_FONTS_DIR, "/run/host/fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/fonts</remap-dir>\n",
SYSTEM_FONTS_DIR);
}
if (g_file_test ("/usr/local/share/fonts", G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/usr/local/share/fonts", "/run/host/local-fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/local-fonts</remap-dir>\n",
"/usr/local/share/fonts");
}
system_cache_dirs = g_strsplit (SYSTEM_FONT_CACHE_DIRS, ":", 0);
for (i = 0; system_cache_dirs[i] != NULL; i++)
{
if (g_file_test (system_cache_dirs[i], G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", system_cache_dirs[i], "/run/host/fonts-cache",
NULL);
found_cache = TRUE;
break;
}
}
if (!found_cache)
{
/* We ensure these directories are never writable, or fontconfig
will use them to write the default cache */
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/run/host/fonts-cache",
"--remount-ro", "/run/host/fonts-cache",
NULL);
}
path_build_tmp = g_build_filename (g_get_user_data_dir (), "fonts", NULL);
user_font1 = g_file_new_for_path (path_build_tmp);
g_clear_pointer (&path_build_tmp, g_free);
path_build_tmp = g_build_filename (g_get_home_dir (), ".fonts", NULL);
user_font2 = g_file_new_for_path (path_build_tmp);
g_clear_pointer (&path_build_tmp, g_free);
if (g_file_query_exists (user_font1, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_font1), "/run/host/user-fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/user-fonts</remap-dir>\n",
flatpak_file_get_path_cached (user_font1));
}
else if (g_file_query_exists (user_font2, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_font2), "/run/host/user-fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/user-fonts</remap-dir>\n",
flatpak_file_get_path_cached (user_font2));
}
path_build_tmp = g_build_filename (g_get_user_cache_dir (), "fontconfig", NULL);
user_font_cache = g_file_new_for_path (path_build_tmp);
g_clear_pointer (&path_build_tmp, g_free);
if (g_file_query_exists (user_font_cache, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_font_cache), "/run/host/user-fonts-cache",
NULL);
}
else
{
/* We ensure these directories are never writable, or fontconfig
will use them to write the default cache */
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/run/host/user-fonts-cache",
"--remount-ro", "/run/host/user-fonts-cache",
NULL);
}
g_string_append (xml_snippet,
"</fontconfig>\n");
if (!flatpak_bwrap_add_args_data (bwrap, "font-dirs.xml", xml_snippet->str, xml_snippet->len, "/run/host/font-dirs.xml", NULL))
g_warning ("Unable to add fontconfig data snippet");
}
static void
add_icon_path_args (FlatpakBwrap *bwrap)
{
g_autofree gchar *user_icons_path = NULL;
g_autoptr(GFile) user_icons = NULL;
if (g_file_test ("/usr/share/icons", G_FILE_TEST_IS_DIR))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/usr/share/icons", "/run/host/share/icons",
NULL);
}
user_icons_path = g_build_filename (g_get_user_data_dir (), "icons", NULL);
user_icons = g_file_new_for_path (user_icons_path);
if (g_file_query_exists (user_icons, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_icons), "/run/host/user-share/icons",
NULL);
}
}
FlatpakContext *
flatpak_app_compute_permissions (GKeyFile *app_metadata,
GKeyFile *runtime_metadata,
GError **error)
{
g_autoptr(FlatpakContext) app_context = NULL;
app_context = flatpak_context_new ();
if (runtime_metadata != NULL)
{
if (!flatpak_context_load_metadata (app_context, runtime_metadata, error))
return NULL;
/* Don't inherit any permissions from the runtime, only things like env vars. */
flatpak_context_reset_permissions (app_context);
}
if (app_metadata != NULL &&
!flatpak_context_load_metadata (app_context, app_metadata, error))
return NULL;
return g_steal_pointer (&app_context);
}
static void
flatpak_run_gc_ids (void)
{
flatpak_instance_iterate_all_and_gc (NULL);
}
static char *
flatpak_run_allocate_id (int *lock_fd_out)
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *base_dir = g_build_filename (user_runtime_dir, ".flatpak", NULL);
int count;
g_mkdir_with_parents (base_dir, 0755);
flatpak_run_gc_ids ();
for (count = 0; count < 1000; count++)
{
g_autofree char *instance_id = NULL;
g_autofree char *instance_dir = NULL;
instance_id = g_strdup_printf ("%u", g_random_int ());
instance_dir = g_build_filename (base_dir, instance_id, NULL);
/* We use an atomic mkdir to ensure the instance id is unique */
if (mkdir (instance_dir, 0755) == 0)
{
g_autofree char *lock_file = g_build_filename (instance_dir, ".ref", NULL);
glnx_autofd int lock_fd = -1;
struct flock l = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
/* Then we take a file lock inside the dir, hold that during
* setup and in bwrap. Anyone trying to clean up unused
* directories need to first verify that there is a .ref
* file and take a write lock on .ref to ensure its not in
* use. */
lock_fd = open (lock_file, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
/* There is a tiny race here between the open creating the file and the lock succeeding.
We work around that by only gc:ing "old" .ref files */
if (lock_fd != -1 && fcntl (lock_fd, F_SETLK, &l) == 0)
{
*lock_fd_out = glnx_steal_fd (&lock_fd);
g_debug ("Allocated instance id %s", instance_id);
return g_steal_pointer (&instance_id);
}
}
}
return NULL;
}
#ifdef HAVE_DCONF
static void
add_dconf_key_to_keyfile (GKeyFile *keyfile,
DConfClient *client,
const char *key,
DConfReadFlags flags)
{
g_autofree char *group = g_path_get_dirname (key);
g_autofree char *k = g_path_get_basename (key);
GVariant *value = dconf_client_read_full (client, key, flags, NULL);
if (value)
{
g_autofree char *val = g_variant_print (value, TRUE);
g_key_file_set_value (keyfile, group + 1, k, val);
}
}
static void
add_dconf_dir_to_keyfile (GKeyFile *keyfile,
DConfClient *client,
const char *dir,
DConfReadFlags flags)
{
g_auto(GStrv) keys = NULL;
int i;
keys = dconf_client_list (client, dir, NULL);
for (i = 0; keys[i]; i++)
{
g_autofree char *k = g_strconcat (dir, keys[i], NULL);
if (dconf_is_dir (k, NULL))
add_dconf_dir_to_keyfile (keyfile, client, k, flags);
else if (dconf_is_key (k, NULL))
add_dconf_key_to_keyfile (keyfile, client, k, flags);
}
}
static void
add_dconf_locks_to_list (GString *s,
DConfClient *client,
const char *dir)
{
g_auto(GStrv) locks = NULL;
int i;
locks = dconf_client_list_locks (client, dir, NULL);
for (i = 0; locks[i]; i++)
{
g_string_append (s, locks[i]);
g_string_append_c (s, '\n');
}
}
#endif /* HAVE_DCONF */
static void
get_dconf_data (const char *app_id,
const char **paths,
const char *migrate_path,
char **defaults,
gsize *defaults_size,
char **values,
gsize *values_size,
char **locks,
gsize *locks_size)
{
#ifdef HAVE_DCONF
DConfClient *client = NULL;
g_autofree char *prefix = NULL;
#endif
g_autoptr(GKeyFile) defaults_data = NULL;
g_autoptr(GKeyFile) values_data = NULL;
g_autoptr(GString) locks_data = NULL;
defaults_data = g_key_file_new ();
values_data = g_key_file_new ();
locks_data = g_string_new ("");
#ifdef HAVE_DCONF
client = dconf_client_new ();
prefix = flatpak_dconf_path_for_app_id (app_id);
if (migrate_path)
{
g_debug ("Add values in dir '%s', prefix is '%s'", migrate_path, prefix);
if (flatpak_dconf_path_is_similar (migrate_path, prefix))
add_dconf_dir_to_keyfile (values_data, client, migrate_path, DCONF_READ_USER_VALUE);
else
g_warning ("Ignoring D-Conf migrate-path setting %s", migrate_path);
}
g_debug ("Add defaults in dir %s", prefix);
add_dconf_dir_to_keyfile (defaults_data, client, prefix, DCONF_READ_DEFAULT_VALUE);
g_debug ("Add locks in dir %s", prefix);
add_dconf_locks_to_list (locks_data, client, prefix);
/* We allow extra paths for defaults and locks, but not for user values */
if (paths)
{
int i;
for (i = 0; paths[i]; i++)
{
if (dconf_is_dir (paths[i], NULL))
{
g_debug ("Add defaults in dir %s", paths[i]);
add_dconf_dir_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);
g_debug ("Add locks in dir %s", paths[i]);
add_dconf_locks_to_list (locks_data, client, paths[i]);
}
else if (dconf_is_key (paths[i], NULL))
{
g_debug ("Add individual key %s", paths[i]);
add_dconf_key_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);
add_dconf_key_to_keyfile (values_data, client, paths[i], DCONF_READ_USER_VALUE);
}
else
{
g_warning ("Ignoring settings path '%s': neither dir nor key", paths[i]);
}
}
}
#endif
*defaults = g_key_file_to_data (defaults_data, defaults_size, NULL);
*values = g_key_file_to_data (values_data, values_size, NULL);
*locks_size = locks_data->len;
*locks = g_string_free (g_steal_pointer (&locks_data), FALSE);
#ifdef HAVE_DCONF
g_object_unref (client);
#endif
}
static gboolean
flatpak_run_add_dconf_args (FlatpakBwrap *bwrap,
const char *app_id,
GKeyFile *metakey,
GError **error)
{
g_auto(GStrv) paths = NULL;
g_autofree char *migrate_path = NULL;
g_autofree char *defaults = NULL;
g_autofree char *values = NULL;
g_autofree char *locks = NULL;
gsize defaults_size;
gsize values_size;
gsize locks_size;
if (metakey)
{
paths = g_key_file_get_string_list (metakey,
FLATPAK_METADATA_GROUP_DCONF,
FLATPAK_METADATA_KEY_DCONF_PATHS,
NULL, NULL);
migrate_path = g_key_file_get_string (metakey,
FLATPAK_METADATA_GROUP_DCONF,
FLATPAK_METADATA_KEY_DCONF_MIGRATE_PATH,
NULL);
}
get_dconf_data (app_id,
(const char **) paths,
migrate_path,
&defaults, &defaults_size,
&values, &values_size,
&locks, &locks_size);
if (defaults_size != 0 &&
!flatpak_bwrap_add_args_data (bwrap,
"dconf-defaults",
defaults, defaults_size,
"/etc/glib-2.0/settings/defaults",
error))
return FALSE;
if (locks_size != 0 &&
!flatpak_bwrap_add_args_data (bwrap,
"dconf-locks",
locks, locks_size,
"/etc/glib-2.0/settings/locks",
error))
return FALSE;
/* We do a one-time conversion of existing dconf settings to a keyfile.
* Only do that once the app stops requesting dconf access.
*/
if (migrate_path)
{
g_autofree char *filename = NULL;
filename = g_build_filename (g_get_home_dir (),
".var/app", app_id,
"config/glib-2.0/settings/keyfile",
NULL);
g_debug ("writing D-Conf values to %s", filename);
if (values_size != 0 && !g_file_test (filename, G_FILE_TEST_EXISTS))
{
g_autofree char *dir = g_path_get_dirname (filename);
if (g_mkdir_with_parents (dir, 0700) == -1)
{
g_warning ("failed creating dirs for %s", filename);
return FALSE;
}
if (!g_file_set_contents (filename, values, values_size, error))
{
g_warning ("failed writing %s", filename);
return FALSE;
}
}
}
return TRUE;
}
gboolean
flatpak_run_add_app_info_args (FlatpakBwrap *bwrap,
GFile *app_files,
GBytes *app_deploy_data,
const char *app_extensions,
GFile *runtime_files,
GBytes *runtime_deploy_data,
const char *runtime_extensions,
const char *app_id,
const char *app_branch,
FlatpakDecomposed *runtime_ref,
GFile *app_id_dir,
FlatpakContext *final_app_context,
FlatpakContext *cmdline_context,
gboolean sandbox,
gboolean build,
gboolean devel,
char **app_info_path_out,
int instance_id_fd,
char **instance_id_host_dir_out,
GError **error)
{
g_autofree char *info_path = NULL;
g_autofree char *bwrapinfo_path = NULL;
int fd, fd2, fd3;
g_autoptr(GKeyFile) keyfile = NULL;
g_autofree char *runtime_path = NULL;
g_autofree char *old_dest = g_strdup_printf ("/run/user/%d/flatpak-info", getuid ());
const char *group;
g_autofree char *instance_id = NULL;
glnx_autofd int lock_fd = -1;
g_autofree char *instance_id_host_dir = NULL;
g_autofree char *instance_id_sandbox_dir = NULL;
g_autofree char *instance_id_lock_file = NULL;
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *arch = flatpak_decomposed_dup_arch (runtime_ref);
instance_id = flatpak_run_allocate_id (&lock_fd);
if (instance_id == NULL)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Unable to allocate instance id"));
instance_id_host_dir = g_build_filename (user_runtime_dir, ".flatpak", instance_id, NULL);
instance_id_sandbox_dir = g_strdup_printf ("/run/user/%d/.flatpak/%s", getuid (), instance_id);
instance_id_lock_file = g_build_filename (instance_id_sandbox_dir, ".ref", NULL);
flatpak_bwrap_add_args (bwrap,
"--ro-bind",
instance_id_host_dir,
instance_id_sandbox_dir,
"--lock-file",
instance_id_lock_file,
NULL);
/* Keep the .ref lock held until we've started bwrap to avoid races */
flatpak_bwrap_add_noinherit_fd (bwrap, glnx_steal_fd (&lock_fd));
info_path = g_build_filename (instance_id_host_dir, "info", NULL);
keyfile = g_key_file_new ();
if (app_files)
group = FLATPAK_METADATA_GROUP_APPLICATION;
else
group = FLATPAK_METADATA_GROUP_RUNTIME;
g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_NAME, app_id);
g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_RUNTIME,
flatpak_decomposed_get_ref (runtime_ref));
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_ID, instance_id);
if (app_id_dir)
{
g_autofree char *instance_path = g_file_get_path (app_id_dir);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_PATH, instance_path);
}
if (app_files)
{
g_autofree char *app_path = g_file_get_path (app_files);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_PATH, app_path);
}
if (app_deploy_data)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_COMMIT, flatpak_deploy_data_get_commit (app_deploy_data));
if (app_extensions && *app_extensions != 0)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_EXTENSIONS, app_extensions);
runtime_path = g_file_get_path (runtime_files);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_PATH, runtime_path);
if (runtime_deploy_data)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_COMMIT, flatpak_deploy_data_get_commit (runtime_deploy_data));
if (runtime_extensions && *runtime_extensions != 0)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_EXTENSIONS, runtime_extensions);
if (app_branch != NULL)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BRANCH, app_branch);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_ARCH, arch);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_FLATPAK_VERSION, PACKAGE_VERSION);
if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) == 0)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_SESSION_BUS_PROXY, TRUE);
if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) == 0)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_SYSTEM_BUS_PROXY, TRUE);
if (sandbox)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_SANDBOX, TRUE);
if (build)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BUILD, TRUE);
if (devel)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_DEVEL, TRUE);
if (cmdline_context)
{
g_autoptr(GPtrArray) cmdline_args = g_ptr_array_new_with_free_func (g_free);
flatpak_context_to_args (cmdline_context, cmdline_args);
if (cmdline_args->len > 0)
{
g_key_file_set_string_list (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_EXTRA_ARGS,
(const char * const *) cmdline_args->pdata,
cmdline_args->len);
}
}
flatpak_context_save_metadata (final_app_context, TRUE, keyfile);
if (!g_key_file_save_to_file (keyfile, info_path, error))
return FALSE;
/* We want to create a file on /.flatpak-info that the app cannot modify, which
we do by creating a read-only bind mount. This way one can openat()
/proc/$pid/root, and if that succeeds use openat via that to find the
unfakable .flatpak-info file. However, there is a tiny race in that if
you manage to open /proc/$pid/root, but then the pid dies, then
every mount but the root is unmounted in the namespace, so the
.flatpak-info will be empty. We fix this by first creating a real file
with the real info in, then bind-mounting on top of that, the same info.
This way even if the bind-mount is unmounted we can find the real data.
*/
fd = open (info_path, O_RDONLY);
if (fd == -1)
{
int errsv = errno;
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to open flatpak-info file: %s"), g_strerror (errsv));
return FALSE;
}
fd2 = open (info_path, O_RDONLY);
if (fd2 == -1)
{
close (fd);
int errsv = errno;
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to open flatpak-info file: %s"), g_strerror (errsv));
return FALSE;
}
flatpak_bwrap_add_args_data_fd (bwrap,
"--file", fd, "/.flatpak-info");
flatpak_bwrap_add_args_data_fd (bwrap,
"--ro-bind-data", fd2, "/.flatpak-info");
flatpak_bwrap_add_args (bwrap,
"--symlink", "../../../.flatpak-info", old_dest,
NULL);
/* Tell the application that it's running under Flatpak in a generic way. */
flatpak_bwrap_add_args (bwrap,
"--setenv", "container", "flatpak",
NULL);
if (!flatpak_bwrap_add_args_data (bwrap,
"container-manager",
"flatpak\n", -1,
"/run/host/container-manager",
error))
return FALSE;
bwrapinfo_path = g_build_filename (instance_id_host_dir, "bwrapinfo.json", NULL);
fd3 = open (bwrapinfo_path, O_RDWR | O_CREAT, 0644);
if (fd3 == -1)
{
close (fd);
close (fd2);
int errsv = errno;
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to open bwrapinfo.json file: %s"), g_strerror (errsv));
return FALSE;
}
/* NOTE: It is important that this takes place after bwrapinfo.json is created,
otherwise start notifications in the portal may not work. */
if (instance_id_fd != -1)
{
gsize instance_id_position = 0;
gsize instance_id_size = strlen (instance_id);
while (instance_id_size > 0)
{
gssize bytes_written = write (instance_id_fd, instance_id + instance_id_position, instance_id_size);
if (G_UNLIKELY (bytes_written <= 0))
{
int errsv = bytes_written == -1 ? errno : ENOSPC;
if (errsv == EINTR)
continue;
close (fd);
close (fd2);
close (fd3);
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to write to instance id fd: %s"), g_strerror (errsv));
return FALSE;
}
instance_id_position += bytes_written;
instance_id_size -= bytes_written;
}
close (instance_id_fd);
}
flatpak_bwrap_add_args_data_fd (bwrap, "--info-fd", fd3, NULL);
if (app_info_path_out != NULL)
*app_info_path_out = g_strdup_printf ("/proc/self/fd/%d", fd);
if (instance_id_host_dir_out != NULL)
*instance_id_host_dir_out = g_steal_pointer (&instance_id_host_dir);
return TRUE;
}
static void
add_tzdata_args (FlatpakBwrap *bwrap,
GFile *runtime_files)
{
g_autofree char *raw_timezone = flatpak_get_timezone ();
g_autofree char *timezone_content = g_strdup_printf ("%s\n", raw_timezone);
g_autofree char *localtime_content = g_strconcat ("../usr/share/zoneinfo/", raw_timezone, NULL);
g_autoptr(GFile) runtime_zoneinfo = NULL;
if (runtime_files)
runtime_zoneinfo = g_file_resolve_relative_path (runtime_files, "share/zoneinfo");
/* Check for runtime /usr/share/zoneinfo */
if (runtime_zoneinfo != NULL && g_file_query_exists (runtime_zoneinfo, NULL))
{
/* Check for host /usr/share/zoneinfo */
if (g_file_test ("/usr/share/zoneinfo", G_FILE_TEST_IS_DIR))
{
/* Here we assume the host timezone file exist in the host data */
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/usr/share/zoneinfo", "/usr/share/zoneinfo",
"--symlink", localtime_content, "/etc/localtime",
NULL);
}
else
{
g_autoptr(GFile) runtime_tzfile = g_file_resolve_relative_path (runtime_zoneinfo, raw_timezone);
/* Check if host timezone file exist in the runtime tzdata */
if (g_file_query_exists (runtime_tzfile, NULL))
flatpak_bwrap_add_args (bwrap,
"--symlink", localtime_content, "/etc/localtime",
NULL);
}
}
flatpak_bwrap_add_args_data (bwrap, "timezone",
timezone_content, -1, "/etc/timezone",
NULL);
}
static void
add_monitor_path_args (gboolean use_session_helper,
FlatpakBwrap *bwrap)
{
g_autoptr(AutoFlatpakSessionHelper) session_helper = NULL;
g_autofree char *monitor_path = NULL;
g_autofree char *pkcs11_socket_path = NULL;
g_autoptr(GVariant) session_data = NULL;
if (use_session_helper)
{
session_helper =
flatpak_session_helper_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
"org.freedesktop.Flatpak",
"/org/freedesktop/Flatpak/SessionHelper",
NULL, NULL);
}
if (session_helper &&
flatpak_session_helper_call_request_session_sync (session_helper,
&session_data,
NULL, NULL))
{
if (g_variant_lookup (session_data, "path", "s", &monitor_path))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", monitor_path, "/run/host/monitor",
"--symlink", "/run/host/monitor/resolv.conf", "/etc/resolv.conf",
"--symlink", "/run/host/monitor/host.conf", "/etc/host.conf",
"--symlink", "/run/host/monitor/hosts", "/etc/hosts",
NULL);
if (g_variant_lookup (session_data, "pkcs11-socket", "s", &pkcs11_socket_path))
{
g_autofree char *sandbox_pkcs11_socket_path = g_strdup_printf ("/run/user/%d/p11-kit/pkcs11", getuid ());
const char *trusted_module_contents =
"# This overrides the runtime p11-kit-trusted module with a client one talking to the trust module on the host\n"
"module: p11-kit-client.so\n";
if (flatpak_bwrap_add_args_data (bwrap, "p11-kit-trust.module",
trusted_module_contents, -1,
"/etc/pkcs11/modules/p11-kit-trust.module", NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", pkcs11_socket_path, sandbox_pkcs11_socket_path,
NULL);
flatpak_bwrap_unset_env (bwrap, "P11_KIT_SERVER_ADDRESS");
}
}
}
else
{
if (g_file_test ("/etc/resolv.conf", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf",
NULL);
if (g_file_test ("/etc/host.conf", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/etc/host.conf", "/etc/host.conf",
NULL);
if (g_file_test ("/etc/hosts", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/etc/hosts", "/etc/hosts",
NULL);
}
}
static void
add_document_portal_args (FlatpakBwrap *bwrap,
const char *app_id,
char **out_mount_path)
{
g_autoptr(GDBusConnection) session_bus = NULL;
g_autofree char *doc_mount_path = NULL;
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
if (session_bus)
{
g_autoptr(GError) local_error = NULL;
g_autoptr(GDBusMessage) reply = NULL;
g_autoptr(GDBusMessage) msg =
g_dbus_message_new_method_call ("org.freedesktop.portal.Documents",
"/org/freedesktop/portal/documents",
"org.freedesktop.portal.Documents",
"GetMountPoint");
g_dbus_message_set_body (msg, g_variant_new ("()"));
reply =
g_dbus_connection_send_message_with_reply_sync (session_bus, msg,
G_DBUS_SEND_MESSAGE_FLAGS_NONE,
30000,
NULL,
NULL,
NULL);
if (reply)
{
if (g_dbus_message_to_gerror (reply, &local_error))
{
if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))
g_debug ("Document portal not available, not mounting /run/user/%d/doc", getuid ());
else
g_message ("Can't get document portal: %s", local_error->message);
}
else
{
g_autofree char *src_path = NULL;
g_autofree char *dst_path = NULL;
g_variant_get (g_dbus_message_get_body (reply),
"(^ay)", &doc_mount_path);
src_path = g_strdup_printf ("%s/by-app/%s",
doc_mount_path, app_id);
dst_path = g_strdup_printf ("/run/user/%d/doc", getuid ());
flatpak_bwrap_add_args (bwrap, "--bind", src_path, dst_path, NULL);
}
}
}
*out_mount_path = g_steal_pointer (&doc_mount_path);
}
#ifdef ENABLE_SECCOMP
static const uint32_t seccomp_x86_64_extra_arches[] = { SCMP_ARCH_X86, 0, };
#ifdef SCMP_ARCH_AARCH64
static const uint32_t seccomp_aarch64_extra_arches[] = { SCMP_ARCH_ARM, 0 };
#endif
static inline void
cleanup_seccomp (void *p)
{
scmp_filter_ctx *pp = (scmp_filter_ctx *) p;
if (*pp)
seccomp_release (*pp);
}
static gboolean
setup_seccomp (FlatpakBwrap *bwrap,
const char *arch,
gulong allowed_personality,
FlatpakRunFlags run_flags,
GError **error)
{
gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;
gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;
__attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;
/**** BEGIN NOTE ON CODE SHARING
*
* There are today a number of different Linux container
* implementations. That will likely continue for long into the
* future. But we can still try to share code, and it's important
* to do so because it affects what library and application writers
* can do, and we should support code portability between different
* container tools.
*
* This syscall blocklist is copied from linux-user-chroot, which was in turn
* clearly influenced by the Sandstorm.io blocklist.
*
* If you make any changes here, I suggest sending the changes along
* to other sandbox maintainers. Using the libseccomp list is also
* an appropriate venue:
* https://groups.google.com/forum/#!forum/libseccomp
*
* A non-exhaustive list of links to container tooling that might
* want to share this blocklist:
*
* https://github.com/sandstorm-io/sandstorm
* in src/sandstorm/supervisor.c++
* https://github.com/flatpak/flatpak.git
* in common/flatpak-run.c
* https://git.gnome.org/browse/linux-user-chroot
* in src/setup-seccomp.c
*
**** END NOTE ON CODE SHARING
*/
struct
{
int scall;
struct scmp_arg_cmp *arg;
} syscall_blocklist[] = {
/* Block dmesg */
{SCMP_SYS (syslog)},
/* Useless old syscall */
{SCMP_SYS (uselib)},
/* Don't allow disabling accounting */
{SCMP_SYS (acct)},
/* 16-bit code is unnecessary in the sandbox, and modify_ldt is a
historic source of interesting information leaks. */
{SCMP_SYS (modify_ldt)},
/* Don't allow reading current quota use */
{SCMP_SYS (quotactl)},
/* Don't allow access to the kernel keyring */
{SCMP_SYS (add_key)},
{SCMP_SYS (keyctl)},
{SCMP_SYS (request_key)},
/* Scary VM/NUMA ops */
{SCMP_SYS (move_pages)},
{SCMP_SYS (mbind)},
{SCMP_SYS (get_mempolicy)},
{SCMP_SYS (set_mempolicy)},
{SCMP_SYS (migrate_pages)},
/* Don't allow subnamespace setups: */
{SCMP_SYS (unshare)},
{SCMP_SYS (mount)},
{SCMP_SYS (pivot_root)},
#if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)
/* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack
* and flags arguments are reversed so the flags come second */
{SCMP_SYS (clone), &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},
#else
/* Normally the flags come first */
{SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},
#endif
/* Don't allow faking input to the controlling tty (CVE-2017-5226) */
{SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)},
};
struct
{
int scall;
struct scmp_arg_cmp *arg;
} syscall_nondevel_blocklist[] = {
/* Profiling operations; we expect these to be done by tools from outside
* the sandbox. In particular perf has been the source of many CVEs.
*/
{SCMP_SYS (perf_event_open)},
/* Don't allow you to switch to bsd emulation or whatnot */
{SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},
{SCMP_SYS (ptrace)}
};
/* Blocklist all but unix, inet, inet6 and netlink */
struct
{
int family;
FlatpakRunFlags flags_mask;
} socket_family_allowlist[] = {
/* NOTE: Keep in numerical order */
{ AF_UNSPEC, 0 },
{ AF_LOCAL, 0 },
{ AF_INET, 0 },
{ AF_INET6, 0 },
{ AF_NETLINK, 0 },
{ AF_CAN, FLATPAK_RUN_FLAG_CANBUS },
{ AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },
};
int last_allowed_family;
int i, r;
g_auto(GLnxTmpfile) seccomp_tmpf = { 0, };
seccomp = seccomp_init (SCMP_ACT_ALLOW);
if (!seccomp)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Initialize seccomp failed"));
if (arch != NULL)
{
uint32_t arch_id = 0;
const uint32_t *extra_arches = NULL;
if (strcmp (arch, "i386") == 0)
{
arch_id = SCMP_ARCH_X86;
}
else if (strcmp (arch, "x86_64") == 0)
{
arch_id = SCMP_ARCH_X86_64;
extra_arches = seccomp_x86_64_extra_arches;
}
else if (strcmp (arch, "arm") == 0)
{
arch_id = SCMP_ARCH_ARM;
}
#ifdef SCMP_ARCH_AARCH64
else if (strcmp (arch, "aarch64") == 0)
{
arch_id = SCMP_ARCH_AARCH64;
extra_arches = seccomp_aarch64_extra_arches;
}
#endif
/* We only really need to handle arches on multiarch systems.
* If only one arch is supported the default is fine */
if (arch_id != 0)
{
/* This *adds* the target arch, instead of replacing the
native one. This is not ideal, because we'd like to only
allow the target arch, but we can't really disallow the
native arch at this point, because then bubblewrap
couldn't continue running. */
r = seccomp_arch_add (seccomp, arch_id);
if (r < 0 && r != -EEXIST)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add architecture to seccomp filter"));
if (multiarch && extra_arches != NULL)
{
for (i = 0; extra_arches[i] != 0; i++)
{
r = seccomp_arch_add (seccomp, extra_arches[i]);
if (r < 0 && r != -EEXIST)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add multiarch architecture to seccomp filter"));
}
}
}
}
/* TODO: Should we filter the kernel keyring syscalls in some way?
* We do want them to be used by desktop apps, but they could also perhaps
* leak system stuff or secrets from other apps.
*/
for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++)
{
int scall = syscall_blocklist[i].scall;
if (syscall_blocklist[i].arg)
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blocklist[i].arg);
else
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);
if (r < 0 && r == -EFAULT /* unknown syscall */)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall);
}
if (!devel)
{
for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++)
{
int scall = syscall_nondevel_blocklist[i].scall;
if (syscall_nondevel_blocklist[i].arg)
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blocklist[i].arg);
else
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);
if (r < 0 && r == -EFAULT /* unknown syscall */)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall);
}
}
/* Socket filtering doesn't work on e.g. i386, so ignore failures here
* However, we need to user seccomp_rule_add_exact to avoid libseccomp doing
* something else: https://github.com/seccomp/libseccomp/issues/8 */
last_allowed_family = -1;
for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++)
{
int family = socket_family_allowlist[i].family;
int disallowed;
if (socket_family_allowlist[i].flags_mask != 0 &&
(socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask)
continue;
for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)
{
/* Blocklist the in-between valid families */
seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));
}
last_allowed_family = family;
}
/* Blocklist the rest */
seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));
if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, "/tmp", &seccomp_tmpf, error))
return FALSE;
if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to export bpf"));
lseek (seccomp_tmpf.fd, 0, SEEK_SET);
flatpak_bwrap_add_args_data_fd (bwrap,
"--seccomp", glnx_steal_fd (&seccomp_tmpf.fd), NULL);
return TRUE;
}
#endif
static void
flatpak_run_setup_usr_links (FlatpakBwrap *bwrap,
GFile *runtime_files)
{
int i;
if (runtime_files == NULL)
return;
for (i = 0; flatpak_abs_usrmerged_dirs[i] != NULL; i++)
{
const char *subdir = flatpak_abs_usrmerged_dirs[i];
g_autoptr(GFile) runtime_subdir = NULL;
g_assert (subdir[0] == '/');
/* Skip the '/' when using as a subdirectory of the runtime */
runtime_subdir = g_file_get_child (runtime_files, subdir + 1);
if (g_file_query_exists (runtime_subdir, NULL))
{
g_autofree char *link = g_strconcat ("usr", subdir, NULL);
flatpak_bwrap_add_args (bwrap,
"--symlink", link, subdir,
NULL);
}
}
}
gboolean
flatpak_run_setup_base_argv (FlatpakBwrap *bwrap,
GFile *runtime_files,
GFile *app_id_dir,
const char *arch,
FlatpakRunFlags flags,
GError **error)
{
g_autofree char *run_dir = NULL;
g_autofree char *passwd_contents = NULL;
g_autoptr(GString) group_contents = NULL;
const char *pkcs11_conf_contents = NULL;
struct group *g;
gulong pers;
gid_t gid = getgid ();
g_autoptr(GFile) etc = NULL;
run_dir = g_strdup_printf ("/run/user/%d", getuid ());
passwd_contents = g_strdup_printf ("%s:x:%d:%d:%s:%s:%s\n"
"nfsnobody:x:65534:65534:Unmapped user:/:/sbin/nologin\n",
g_get_user_name (),
getuid (), gid,
g_get_real_name (),
g_get_home_dir (),
DEFAULT_SHELL);
group_contents = g_string_new ("");
g = getgrgid (gid);
/* if NULL, the primary group is not known outside the container, so
* it might as well stay unknown inside the container... */
if (g != NULL)
g_string_append_printf (group_contents, "%s:x:%d:%s\n",
g->gr_name, gid, g_get_user_name ());
g_string_append (group_contents, "nfsnobody:x:65534:\n");
pkcs11_conf_contents =
"# Disable user pkcs11 config, because the host modules don't work in the runtime\n"
"user-config: none\n";
if ((flags & FLATPAK_RUN_FLAG_NO_PROC) == 0)
flatpak_bwrap_add_args (bwrap,
"--proc", "/proc",
NULL);
if (!(flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS))
flatpak_bwrap_add_arg (bwrap, "--unshare-pid");
flatpak_bwrap_add_args (bwrap,
"--dir", "/tmp",
"--dir", "/var/tmp",
"--dir", "/run/host",
"--dir", run_dir,
"--setenv", "XDG_RUNTIME_DIR", run_dir,
"--symlink", "../run", "/var/run",
"--ro-bind", "/sys/block", "/sys/block",
"--ro-bind", "/sys/bus", "/sys/bus",
"--ro-bind", "/sys/class", "/sys/class",
"--ro-bind", "/sys/dev", "/sys/dev",
"--ro-bind", "/sys/devices", "/sys/devices",
"--ro-bind-try", "/proc/self/ns/user", "/run/.userns",
/* glib uses this like /etc/timezone */
"--symlink", "/etc/timezone", "/var/db/zoneinfo",
NULL);
if (flags & FLATPAK_RUN_FLAG_DIE_WITH_PARENT)
flatpak_bwrap_add_args (bwrap,
"--die-with-parent",
NULL);
if (flags & FLATPAK_RUN_FLAG_WRITABLE_ETC)
flatpak_bwrap_add_args (bwrap,
"--dir", "/usr/etc",
"--symlink", "usr/etc", "/etc",
NULL);
if (!flatpak_bwrap_add_args_data (bwrap, "passwd", passwd_contents, -1, "/etc/passwd", error))
return FALSE;
if (!flatpak_bwrap_add_args_data (bwrap, "group", group_contents->str, -1, "/etc/group", error))
return FALSE;
if (!flatpak_bwrap_add_args_data (bwrap, "pkcs11.conf", pkcs11_conf_contents, -1, "/etc/pkcs11/pkcs11.conf", error))
return FALSE;
if (g_file_test ("/etc/machine-id", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--ro-bind", "/etc/machine-id", "/etc/machine-id", NULL);
else if (g_file_test ("/var/lib/dbus/machine-id", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--ro-bind", "/var/lib/dbus/machine-id", "/etc/machine-id", NULL);
if (runtime_files)
etc = g_file_get_child (runtime_files, "etc");
if (etc != NULL &&
(flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0 &&
g_file_query_exists (etc, NULL))
{
g_auto(GLnxDirFdIterator) dfd_iter = { 0, };
struct dirent *dent;
gboolean inited;
inited = glnx_dirfd_iterator_init_at (AT_FDCWD, flatpak_file_get_path_cached (etc), FALSE, &dfd_iter, NULL);
while (inited)
{
g_autofree char *src = NULL;
g_autofree char *dest = NULL;
if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dfd_iter, &dent, NULL, NULL) || dent == NULL)
break;
if (strcmp (dent->d_name, "passwd") == 0 ||
strcmp (dent->d_name, "group") == 0 ||
strcmp (dent->d_name, "machine-id") == 0 ||
strcmp (dent->d_name, "resolv.conf") == 0 ||
strcmp (dent->d_name, "host.conf") == 0 ||
strcmp (dent->d_name, "hosts") == 0 ||
strcmp (dent->d_name, "localtime") == 0 ||
strcmp (dent->d_name, "timezone") == 0 ||
strcmp (dent->d_name, "pkcs11") == 0)
continue;
src = g_build_filename (flatpak_file_get_path_cached (etc), dent->d_name, NULL);
dest = g_build_filename ("/etc", dent->d_name, NULL);
if (dent->d_type == DT_LNK)
{
g_autofree char *target = NULL;
target = glnx_readlinkat_malloc (dfd_iter.fd, dent->d_name,
NULL, error);
if (target == NULL)
return FALSE;
flatpak_bwrap_add_args (bwrap, "--symlink", target, dest, NULL);
}
else
{
flatpak_bwrap_add_args (bwrap, "--ro-bind", src, dest, NULL);
}
}
}
if (app_id_dir != NULL)
{
g_autoptr(GFile) app_cache_dir = g_file_get_child (app_id_dir, "cache");
g_autoptr(GFile) app_tmp_dir = g_file_get_child (app_cache_dir, "tmp");
g_autoptr(GFile) app_data_dir = g_file_get_child (app_id_dir, "data");
g_autoptr(GFile) app_config_dir = g_file_get_child (app_id_dir, "config");
flatpak_bwrap_add_args (bwrap,
/* These are nice to have as a fixed path */
"--bind", flatpak_file_get_path_cached (app_cache_dir), "/var/cache",
"--bind", flatpak_file_get_path_cached (app_data_dir), "/var/data",
"--bind", flatpak_file_get_path_cached (app_config_dir), "/var/config",
"--bind", flatpak_file_get_path_cached (app_tmp_dir), "/var/tmp",
NULL);
}
flatpak_run_setup_usr_links (bwrap, runtime_files);
add_tzdata_args (bwrap, runtime_files);
pers = PER_LINUX;
if ((flags & FLATPAK_RUN_FLAG_SET_PERSONALITY) &&
flatpak_is_linux32_arch (arch))
{
g_debug ("Setting personality linux32");
pers = PER_LINUX32;
}
/* Always set the personallity, and clear all weird flags */
personality (pers);
#ifdef ENABLE_SECCOMP
if (!setup_seccomp (bwrap, arch, pers, flags, error))
return FALSE;
#endif
if ((flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0)
add_monitor_path_args ((flags & FLATPAK_RUN_FLAG_NO_SESSION_HELPER) == 0, bwrap);
return TRUE;
}
static gboolean
forward_file (XdpDbusDocuments *documents,
const char *app_id,
const char *file,
char **out_doc_id,
GError **error)
{
int fd, fd_id;
g_autofree char *doc_id = NULL;
g_autoptr(GUnixFDList) fd_list = NULL;
const char *perms[] = { "read", "write", NULL };
fd = open (file, O_PATH | O_CLOEXEC);
if (fd == -1)
return flatpak_fail (error, _("Failed to open ‘%s’"), file);
fd_list = g_unix_fd_list_new ();
fd_id = g_unix_fd_list_append (fd_list, fd, error);
close (fd);
if (!xdp_dbus_documents_call_add_sync (documents,
g_variant_new ("h", fd_id),
TRUE, /* reuse */
FALSE, /* not persistent */
fd_list,
&doc_id,
NULL,
NULL,
error))
{
if (error)
g_dbus_error_strip_remote_error (*error);
return FALSE;
}
if (!xdp_dbus_documents_call_grant_permissions_sync (documents,
doc_id,
app_id,
perms,
NULL,
error))
{
if (error)
g_dbus_error_strip_remote_error (*error);
return FALSE;
}
*out_doc_id = g_steal_pointer (&doc_id);
return TRUE;
}
static gboolean
add_rest_args (FlatpakBwrap *bwrap,
const char *app_id,
FlatpakExports *exports,
gboolean file_forwarding,
const char *doc_mount_path,
char *args[],
int n_args,
GError **error)
{
g_autoptr(XdpDbusDocuments) documents = NULL;
gboolean forwarding = FALSE;
gboolean forwarding_uri = FALSE;
gboolean can_forward = TRUE;
int i;
if (file_forwarding && doc_mount_path == NULL)
{
g_message ("Can't get document portal mount path");
can_forward = FALSE;
}
else if (file_forwarding)
{
g_autoptr(GError) local_error = NULL;
documents = xdp_dbus_documents_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION, 0,
"org.freedesktop.portal.Documents",
"/org/freedesktop/portal/documents",
NULL,
&local_error);
if (documents == NULL)
{
g_message ("Can't get document portal: %s", local_error->message);
can_forward = FALSE;
}
}
for (i = 0; i < n_args; i++)
{
g_autoptr(GFile) file = NULL;
if (file_forwarding &&
(strcmp (args[i], "@@") == 0 ||
strcmp (args[i], "@@u") == 0))
{
forwarding_uri = strcmp (args[i], "@@u") == 0;
forwarding = !forwarding;
continue;
}
if (can_forward && forwarding)
{
if (forwarding_uri)
{
if (g_str_has_prefix (args[i], "file:"))
file = g_file_new_for_uri (args[i]);
else if (G_IS_DIR_SEPARATOR (args[i][0]))
file = g_file_new_for_path (args[i]);
}
else
file = g_file_new_for_path (args[i]);
}
if (file && !flatpak_exports_path_is_visible (exports,
flatpak_file_get_path_cached (file)))
{
g_autofree char *doc_id = NULL;
g_autofree char *basename = NULL;
g_autofree char *doc_path = NULL;
if (!forward_file (documents, app_id, flatpak_file_get_path_cached (file),
&doc_id, error))
return FALSE;
basename = g_file_get_basename (file);
doc_path = g_build_filename (doc_mount_path, doc_id, basename, NULL);
if (forwarding_uri)
{
g_autofree char *path = doc_path;
doc_path = g_filename_to_uri (path, NULL, NULL);
/* This should never fail */
g_assert (doc_path != NULL);
}
g_debug ("Forwarding file '%s' as '%s' to %s", args[i], doc_path, app_id);
flatpak_bwrap_add_arg (bwrap, doc_path);
}
else
flatpak_bwrap_add_arg (bwrap, args[i]);
}
return TRUE;
}
FlatpakContext *
flatpak_context_load_for_deploy (FlatpakDeploy *deploy,
GError **error)
{
g_autoptr(FlatpakContext) context = NULL;
g_autoptr(FlatpakContext) overrides = NULL;
g_autoptr(GKeyFile) metakey = NULL;
metakey = flatpak_deploy_get_metadata (deploy);
context = flatpak_app_compute_permissions (metakey, NULL, error);
if (context == NULL)
return NULL;
overrides = flatpak_deploy_get_overrides (deploy);
flatpak_context_merge (context, overrides);
return g_steal_pointer (&context);
}
static char *
calculate_ld_cache_checksum (GBytes *app_deploy_data,
GBytes *runtime_deploy_data,
const char *app_extensions,
const char *runtime_extensions)
{
g_autoptr(GChecksum) ld_so_checksum = g_checksum_new (G_CHECKSUM_SHA256);
if (app_deploy_data)
g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (app_deploy_data), -1);
g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (runtime_deploy_data), -1);
if (app_extensions)
g_checksum_update (ld_so_checksum, (guchar *) app_extensions, -1);
if (runtime_extensions)
g_checksum_update (ld_so_checksum, (guchar *) runtime_extensions, -1);
return g_strdup (g_checksum_get_string (ld_so_checksum));
}
static gboolean
add_ld_so_conf (FlatpakBwrap *bwrap,
GError **error)
{
const char *contents =
"include /run/flatpak/ld.so.conf.d/app-*.conf\n"
"include /app/etc/ld.so.conf\n"
"/app/lib\n"
"include /run/flatpak/ld.so.conf.d/runtime-*.conf\n";
return flatpak_bwrap_add_args_data (bwrap, "ld-so-conf",
contents, -1, "/etc/ld.so.conf", error);
}
static int
regenerate_ld_cache (GPtrArray *base_argv_array,
GArray *base_fd_array,
GFile *app_id_dir,
const char *checksum,
GFile *runtime_files,
gboolean generate_ld_so_conf,
GCancellable *cancellable,
GError **error)
{
g_autoptr(FlatpakBwrap) bwrap = NULL;
g_autoptr(GArray) combined_fd_array = NULL;
g_autoptr(GFile) ld_so_cache = NULL;
g_autoptr(GFile) ld_so_cache_tmp = NULL;
g_autofree char *sandbox_cache_path = NULL;
g_autofree char *tmp_basename = NULL;
g_auto(GStrv) minimal_envp = NULL;
g_autofree char *commandline = NULL;
int exit_status;
glnx_autofd int ld_so_fd = -1;
g_autoptr(GFile) ld_so_dir = NULL;
if (app_id_dir)
ld_so_dir = g_file_get_child (app_id_dir, ".ld.so");
else
{
g_autoptr(GFile) base_dir = g_file_new_for_path (g_get_user_cache_dir ());
ld_so_dir = g_file_resolve_relative_path (base_dir, "flatpak/ld.so");
}
ld_so_cache = g_file_get_child (ld_so_dir, checksum);
ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache), O_RDONLY);
if (ld_so_fd >= 0)
return glnx_steal_fd (&ld_so_fd);
g_debug ("Regenerating ld.so.cache %s", flatpak_file_get_path_cached (ld_so_cache));
if (!flatpak_mkdir_p (ld_so_dir, cancellable, error))
return FALSE;
minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);
bwrap = flatpak_bwrap_new (minimal_envp);
flatpak_bwrap_append_args (bwrap, base_argv_array);
flatpak_run_setup_usr_links (bwrap, runtime_files);
if (generate_ld_so_conf)
{
if (!add_ld_so_conf (bwrap, error))
return -1;
}
else
flatpak_bwrap_add_args (bwrap,
"--symlink", "../usr/etc/ld.so.conf", "/etc/ld.so.conf",
NULL);
tmp_basename = g_strconcat (checksum, ".XXXXXX", NULL);
glnx_gen_temp_name (tmp_basename);
sandbox_cache_path = g_build_filename ("/run/ld-so-cache-dir", tmp_basename, NULL);
ld_so_cache_tmp = g_file_get_child (ld_so_dir, tmp_basename);
flatpak_bwrap_add_args (bwrap,
"--unshare-pid",
"--unshare-ipc",
"--unshare-net",
"--proc", "/proc",
"--dev", "/dev",
"--bind", flatpak_file_get_path_cached (ld_so_dir), "/run/ld-so-cache-dir",
NULL);
if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))
return -1;
flatpak_bwrap_add_args (bwrap,
"ldconfig", "-X", "-C", sandbox_cache_path, NULL);
flatpak_bwrap_finish (bwrap);
commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);
g_debug ("Running: '%s'", commandline);
combined_fd_array = g_array_new (FALSE, TRUE, sizeof (int));
g_array_append_vals (combined_fd_array, base_fd_array->data, base_fd_array->len);
g_array_append_vals (combined_fd_array, bwrap->fds->data, bwrap->fds->len);
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_sync (NULL,
(char **) bwrap->argv->pdata,
bwrap->envp,
G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
flatpak_bwrap_child_setup_cb, combined_fd_array,
NULL, NULL,
&exit_status,
error))
return -1;
if (!WIFEXITED (exit_status) || WEXITSTATUS (exit_status) != 0)
{
flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,
_("ldconfig failed, exit status %d"), exit_status);
return -1;
}
ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache_tmp), O_RDONLY);
if (ld_so_fd < 0)
{
flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Can't open generated ld.so.cache"));
return -1;
}
if (app_id_dir == NULL)
{
/* For runs without an app id dir we always regenerate the ld.so.cache */
unlink (flatpak_file_get_path_cached (ld_so_cache_tmp));
}
else
{
g_autoptr(GFile) active = g_file_get_child (ld_so_dir, "active");
/* For app-dirs we keep one checksum alive, by pointing the active symlink to it */
/* Rename to known name, possibly overwriting existing ref if race */
if (rename (flatpak_file_get_path_cached (ld_so_cache_tmp), flatpak_file_get_path_cached (ld_so_cache)) == -1)
{
glnx_set_error_from_errno (error);
return -1;
}
if (!flatpak_switch_symlink_and_remove (flatpak_file_get_path_cached (active),
checksum, error))
return -1;
}
return glnx_steal_fd (&ld_so_fd);
}
/* Check that this user is actually allowed to run this app. When running
* from the gnome-initial-setup session, an app filter might not be available. */
static gboolean
check_parental_controls (FlatpakDecomposed *app_ref,
FlatpakDeploy *deploy,
GCancellable *cancellable,
GError **error)
{
#ifdef HAVE_LIBMALCONTENT
g_autoptr(MctManager) manager = NULL;
g_autoptr(MctAppFilter) app_filter = NULL;
g_autoptr(GAsyncResult) app_filter_result = NULL;
g_autoptr(GDBusConnection) system_bus = NULL;
g_autoptr(GError) local_error = NULL;
g_autoptr(GDesktopAppInfo) app_info = NULL;
gboolean allowed = FALSE;
system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
if (system_bus == NULL)
return FALSE;
manager = mct_manager_new (system_bus);
app_filter = mct_manager_get_app_filter (manager, getuid (),
MCT_GET_APP_FILTER_FLAGS_INTERACTIVE,
cancellable, &local_error);
if (g_error_matches (local_error, MCT_APP_FILTER_ERROR, MCT_APP_FILTER_ERROR_DISABLED))
{
g_debug ("Skipping parental controls check for %s since parental "
"controls are disabled globally", flatpak_decomposed_get_ref (app_ref));
return TRUE;
}
else if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN) ||
g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_NAME_HAS_NO_OWNER))
{
g_debug ("Skipping parental controls check for %s since a required "
"service was not found", flatpak_decomposed_get_ref (app_ref));
return TRUE;
}
else if (local_error != NULL)
{
g_propagate_error (error, g_steal_pointer (&local_error));
return FALSE;
}
/* Always filter by app ID. Additionally, filter by app info (which runs
* multiple checks, including whether the app ID, executable path and
* content types are allowed) if available. If the flatpak contains
* multiple .desktop files, we use the main one. The app ID check is
* always done, as the binary executed by `flatpak run` isn’t necessarily
* extracted from a .desktop file. */
allowed = mct_app_filter_is_flatpak_ref_allowed (app_filter, flatpak_decomposed_get_ref (app_ref));
/* Look up the app’s main .desktop file. */
if (deploy != NULL && allowed)
{
g_autoptr(GFile) deploy_dir = NULL;
const char *deploy_path;
g_autofree char *desktop_file_name = NULL;
g_autofree char *desktop_file_path = NULL;
g_autofree char *app_id = flatpak_decomposed_dup_id (app_ref);
deploy_dir = flatpak_deploy_get_dir (deploy);
deploy_path = flatpak_file_get_path_cached (deploy_dir);
desktop_file_name = g_strconcat (app_id, ".desktop", NULL);
desktop_file_path = g_build_path (G_DIR_SEPARATOR_S,
deploy_path,
"export",
"share",
"applications",
desktop_file_name,
NULL);
app_info = g_desktop_app_info_new_from_filename (desktop_file_path);
}
if (app_info != NULL)
allowed = allowed && mct_app_filter_is_appinfo_allowed (app_filter,
G_APP_INFO (app_info));
if (!allowed)
return flatpak_fail_error (error, FLATPAK_ERROR_PERMISSION_DENIED,
/* Translators: The placeholder is for an app ref. */
_("Running %s is not allowed by the policy set by your administrator"),
flatpak_decomposed_get_ref (app_ref));
#endif /* HAVE_LIBMALCONTENT */
return TRUE;
}
static int
open_namespace_fd_if_needed (const char *path,
const char *other_path) {
struct stat s, other_s;
if (stat (path, &s) != 0)
return -1; /* No such namespace, ignore */
if (stat (other_path, &other_s) != 0)
return -1; /* No such namespace, ignore */
/* setns calls fail if the process is already in the desired namespace, hence the
check here to ensure the namespaces are different. */
if (s.st_ino != other_s.st_ino)
return open (path, O_RDONLY|O_CLOEXEC);
return -1;
}
static gboolean
check_sudo (GError **error)
{
const char *sudo_command_env = g_getenv ("SUDO_COMMAND");
g_auto(GStrv) split_command = NULL;
/* This check exists to stop accidental usage of `sudo flatpak run`
and is not to prevent running as root.
*/
if (!sudo_command_env)
return TRUE;
/* SUDO_COMMAND could be a value like `/usr/bin/flatpak run foo` */
split_command = g_strsplit (sudo_command_env, " ", 2);
if (g_str_has_suffix (split_command[0], "flatpak"))
return flatpak_fail_error (error, FLATPAK_ERROR, _("\"flatpak run\" is not intended to be ran with sudo"));
return TRUE;
}
gboolean
flatpak_run_app (FlatpakDecomposed *app_ref,
FlatpakDeploy *app_deploy,
FlatpakContext *extra_context,
const char *custom_runtime,
const char *custom_runtime_version,
const char *custom_runtime_commit,
int parent_pid,
FlatpakRunFlags flags,
const char *cwd,
const char *custom_command,
char *args[],
int n_args,
int instance_id_fd,
char **instance_dir_out,
GCancellable *cancellable,
GError **error)
{
g_autoptr(FlatpakDeploy) runtime_deploy = NULL;
g_autoptr(GBytes) runtime_deploy_data = NULL;
g_autoptr(GBytes) app_deploy_data = NULL;
g_autoptr(GFile) app_files = NULL;
g_autoptr(GFile) runtime_files = NULL;
g_autoptr(GFile) bin_ldconfig = NULL;
g_autoptr(GFile) app_id_dir = NULL;
g_autoptr(GFile) real_app_id_dir = NULL;
g_autofree char *default_runtime_pref = NULL;
g_autoptr(FlatpakDecomposed) default_runtime = NULL;
g_autofree char *default_command = NULL;
g_autoptr(GKeyFile) metakey = NULL;
g_autoptr(GKeyFile) runtime_metakey = NULL;
g_autoptr(FlatpakBwrap) bwrap = NULL;
const char *command = "/bin/sh";
g_autoptr(GError) my_error = NULL;
g_autoptr(FlatpakDecomposed) runtime_ref = NULL;
int i;
g_autoptr(GPtrArray) previous_app_id_dirs = NULL;
g_autofree char *app_id = NULL;
g_autofree char *app_arch = NULL;
g_autofree char *app_info_path = NULL;
g_autofree char *instance_id_host_dir = NULL;
g_autoptr(FlatpakContext) app_context = NULL;
g_autoptr(FlatpakContext) overrides = NULL;
g_autoptr(FlatpakExports) exports = NULL;
g_autofree char *commandline = NULL;
g_autofree char *doc_mount_path = NULL;
g_autofree char *app_extensions = NULL;
g_autofree char *runtime_extensions = NULL;
g_autofree char *checksum = NULL;
int ld_so_fd = -1;
g_autoptr(GFile) runtime_ld_so_conf = NULL;
gboolean generate_ld_so_conf = TRUE;
gboolean use_ld_so_cache = TRUE;
gboolean sandboxed = (flags & FLATPAK_RUN_FLAG_SANDBOX) != 0;
gboolean parent_expose_pids = (flags & FLATPAK_RUN_FLAG_PARENT_EXPOSE_PIDS) != 0;
gboolean parent_share_pids = (flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS) != 0;
struct stat s;
if (!check_sudo (error))
return FALSE;
app_id = flatpak_decomposed_dup_id (app_ref);
app_arch = flatpak_decomposed_dup_arch (app_ref);
/* Check the user is allowed to run this flatpak. */
if (!check_parental_controls (app_ref, app_deploy, cancellable, error))
return FALSE;
/* Construct the bwrap context. */
bwrap = flatpak_bwrap_new (NULL);
flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());
if (app_deploy == NULL)
{
g_assert (flatpak_decomposed_is_runtime (app_ref));
default_runtime_pref = flatpak_decomposed_dup_pref (app_ref);
}
else
{
const gchar *key;
app_deploy_data = flatpak_deploy_get_deploy_data (app_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);
if (app_deploy_data == NULL)
return FALSE;
if ((flags & FLATPAK_RUN_FLAG_DEVEL) != 0)
key = FLATPAK_METADATA_KEY_SDK;
else
key = FLATPAK_METADATA_KEY_RUNTIME;
metakey = flatpak_deploy_get_metadata (app_deploy);
default_runtime_pref = g_key_file_get_string (metakey,
FLATPAK_METADATA_GROUP_APPLICATION,
key, &my_error);
if (my_error)
{
g_propagate_error (error, g_steal_pointer (&my_error));
return FALSE;
}
}
default_runtime = flatpak_decomposed_new_from_pref (FLATPAK_KINDS_RUNTIME, default_runtime_pref, error);
if (default_runtime == NULL)
return FALSE;
if (custom_runtime != NULL || custom_runtime_version != NULL)
{
g_auto(GStrv) custom_runtime_parts = NULL;
const char *custom_runtime_id = NULL;
const char *custom_runtime_arch = NULL;
if (custom_runtime)
{
custom_runtime_parts = g_strsplit (custom_runtime, "/", 0);
for (i = 0; i < 3 && custom_runtime_parts[i] != NULL; i++)
{
if (strlen (custom_runtime_parts[i]) > 0)
{
if (i == 0)
custom_runtime_id = custom_runtime_parts[i];
if (i == 1)
custom_runtime_arch = custom_runtime_parts[i];
if (i == 2 && custom_runtime_version == NULL)
custom_runtime_version = custom_runtime_parts[i];
}
}
}
runtime_ref = flatpak_decomposed_new_from_decomposed (default_runtime,
FLATPAK_KINDS_RUNTIME,
custom_runtime_id,
custom_runtime_arch,
custom_runtime_version,
error);
if (runtime_ref == NULL)
return FALSE;
}
else
runtime_ref = flatpak_decomposed_ref (default_runtime);
runtime_deploy = flatpak_find_deploy_for_ref (flatpak_decomposed_get_ref (runtime_ref), custom_runtime_commit, NULL, cancellable, error);
if (runtime_deploy == NULL)
return FALSE;
runtime_deploy_data = flatpak_deploy_get_deploy_data (runtime_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);
if (runtime_deploy_data == NULL)
return FALSE;
runtime_metakey = flatpak_deploy_get_metadata (runtime_deploy);
app_context = flatpak_app_compute_permissions (metakey, runtime_metakey, error);
if (app_context == NULL)
return FALSE;
if (app_deploy != NULL)
{
overrides = flatpak_deploy_get_overrides (app_deploy);
flatpak_context_merge (app_context, overrides);
}
if (sandboxed)
flatpak_context_make_sandboxed (app_context);
if (extra_context)
flatpak_context_merge (app_context, extra_context);
runtime_files = flatpak_deploy_get_files (runtime_deploy);
bin_ldconfig = g_file_resolve_relative_path (runtime_files, "bin/ldconfig");
if (!g_file_query_exists (bin_ldconfig, NULL))
use_ld_so_cache = FALSE;
if (app_deploy != NULL)
{
g_autofree const char **previous_ids = NULL;
gsize len = 0;
gboolean do_migrate;
real_app_id_dir = flatpak_get_data_dir (app_id);
app_files = flatpak_deploy_get_files (app_deploy);
previous_app_id_dirs = g_ptr_array_new_with_free_func (g_object_unref);
previous_ids = flatpak_deploy_data_get_previous_ids (app_deploy_data, &len);
do_migrate = !g_file_query_exists (real_app_id_dir, cancellable);
/* When migrating, find most recent old existing source and rename that to
* the new name.
*
* We ignore other names than that. For more recent names that don't exist
* we never ran them so nothing will even reference them. For older names
* either they were not used, or they were used but then the more recent
* name was used and a symlink to it was created.
*
* This means we may end up with a chain of symlinks: oldest -> old -> current.
* This is unfortunate but not really a problem, but for robustness reasons we
* don't want to mess with user files unnecessary. For example, the app dir could
* actually be a symlink for other reasons. Imagine for instance that you want to put the
* steam games somewhere else so you leave the app dir as a symlink to /mnt/steam.
*/
for (i = len - 1; i >= 0; i--)
{
g_autoptr(GFile) previous_app_id_dir = NULL;
g_autoptr(GFileInfo) previous_app_id_dir_info = NULL;
g_autoptr(GError) local_error = NULL;
previous_app_id_dir = flatpak_get_data_dir (previous_ids[i]);
previous_app_id_dir_info = g_file_query_info (previous_app_id_dir,
G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK ","
G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
cancellable,
&local_error);
/* Warn about the migration failures, but don't make them fatal, then you can never run the app */
if (previous_app_id_dir_info == NULL)
{
if (!g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND) && do_migrate)
{
g_warning (_("Failed to migrate from %s: %s"), flatpak_file_get_path_cached (previous_app_id_dir),
local_error->message);
do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to the thing that we failed on */
}
g_clear_error (&local_error);
continue;
}
if (do_migrate)
{
do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to this dir */
if (!flatpak_file_rename (previous_app_id_dir, real_app_id_dir, cancellable, &local_error))
{
g_warning (_("Failed to migrate old app data directory %s to new name %s: %s"),
flatpak_file_get_path_cached (previous_app_id_dir), app_id,
local_error->message);
}
else
{
/* Leave a symlink in place of the old data dir */
if (!g_file_make_symbolic_link (previous_app_id_dir, app_id, cancellable, &local_error))
{
g_warning (_("Failed to create symlink while migrating %s: %s"),
flatpak_file_get_path_cached (previous_app_id_dir),
local_error->message);
}
}
}
/* Give app access to this old dir */
g_ptr_array_add (previous_app_id_dirs, g_steal_pointer (&previous_app_id_dir));
}
if (!flatpak_ensure_data_dir (real_app_id_dir, cancellable, error))
return FALSE;
if (!sandboxed)
app_id_dir = g_object_ref (real_app_id_dir);
}
flatpak_run_apply_env_default (bwrap, use_ld_so_cache);
flatpak_run_apply_env_vars (bwrap, app_context);
flatpak_run_apply_env_prompt (bwrap, app_id);
if (real_app_id_dir)
{
g_autoptr(GFile) sandbox_dir = g_file_get_child (real_app_id_dir, "sandbox");
flatpak_bwrap_set_env (bwrap, "FLATPAK_SANDBOX_DIR", flatpak_file_get_path_cached (sandbox_dir), TRUE);
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (runtime_files), "/usr",
"--lock-file", "/usr/.ref",
NULL);
if (app_files != NULL)
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (app_files), "/app",
"--lock-file", "/app/.ref",
NULL);
else
flatpak_bwrap_add_args (bwrap,
"--dir", "/app",
NULL);
if (metakey != NULL &&
!flatpak_run_add_extension_args (bwrap, metakey, app_ref, use_ld_so_cache, &app_extensions, cancellable, error))
return FALSE;
if (!flatpak_run_add_extension_args (bwrap, runtime_metakey, runtime_ref, use_ld_so_cache, &runtime_extensions, cancellable, error))
return FALSE;
runtime_ld_so_conf = g_file_resolve_relative_path (runtime_files, "etc/ld.so.conf");
if (lstat (flatpak_file_get_path_cached (runtime_ld_so_conf), &s) == 0)
generate_ld_so_conf = S_ISREG (s.st_mode) && s.st_size == 0;
/* At this point we have the minimal argv set up, with just the app, runtime and extensions.
We can reuse this to generate the ld.so.cache (if needed) */
if (use_ld_so_cache)
{
checksum = calculate_ld_cache_checksum (app_deploy_data, runtime_deploy_data,
app_extensions, runtime_extensions);
ld_so_fd = regenerate_ld_cache (bwrap->argv,
bwrap->fds,
app_id_dir,
checksum,
runtime_files,
generate_ld_so_conf,
cancellable, error);
if (ld_so_fd == -1)
return FALSE;
flatpak_bwrap_add_fd (bwrap, ld_so_fd);
}
flags |= flatpak_context_get_run_flags (app_context);
if (!flatpak_run_setup_base_argv (bwrap, runtime_files, app_id_dir, app_arch, flags, error))
return FALSE;
if (generate_ld_so_conf)
{
if (!add_ld_so_conf (bwrap, error))
return FALSE;
}
if (ld_so_fd != -1)
{
/* Don't add to fd_array, its already there */
flatpak_bwrap_add_arg (bwrap, "--ro-bind-data");
flatpak_bwrap_add_arg_printf (bwrap, "%d", ld_so_fd);
flatpak_bwrap_add_arg (bwrap, "/etc/ld.so.cache");
}
if (!flatpak_run_add_app_info_args (bwrap,
app_files, app_deploy_data, app_extensions,
runtime_files, runtime_deploy_data, runtime_extensions,
app_id, flatpak_decomposed_get_branch (app_ref),
runtime_ref, app_id_dir, app_context, extra_context,
sandboxed, FALSE, flags & FLATPAK_RUN_FLAG_DEVEL,
&app_info_path, instance_id_fd, &instance_id_host_dir,
error))
return FALSE;
if (!flatpak_run_add_dconf_args (bwrap, app_id, metakey, error))
return FALSE;
if (!sandboxed && !(flags & FLATPAK_RUN_FLAG_NO_DOCUMENTS_PORTAL))
add_document_portal_args (bwrap, app_id, &doc_mount_path);
if (!flatpak_run_add_environment_args (bwrap, app_info_path, flags,
app_id, app_context, app_id_dir, previous_app_id_dirs,
&exports, cancellable, error))
return FALSE;
if ((app_context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) != 0)
flatpak_run_add_resolved_args (bwrap);
flatpak_run_add_journal_args (bwrap);
add_font_path_args (bwrap);
add_icon_path_args (bwrap);
flatpak_bwrap_add_args (bwrap,
/* Not in base, because we don't want this for flatpak build */
"--symlink", "/app/lib/debug/source", "/run/build",
"--symlink", "/usr/lib/debug/source", "/run/build-runtime",
NULL);
if (cwd)
flatpak_bwrap_add_args (bwrap, "--chdir", cwd, NULL);
if (parent_expose_pids || parent_share_pids)
{
g_autofree char *userns_path = NULL;
g_autofree char *pidns_path = NULL;
g_autofree char *userns2_path = NULL;
int userns_fd, userns2_fd, pidns_fd;
if (parent_pid == 0)
return flatpak_fail (error, "No parent pid specified");
userns_path = g_strdup_printf ("/proc/%d/root/run/.userns", parent_pid);
userns_fd = open_namespace_fd_if_needed (userns_path, "/proc/self/ns/user");
if (userns_fd != -1)
{
flatpak_bwrap_add_args_data_fd (bwrap, "--userns", userns_fd, NULL);
userns2_path = g_strdup_printf ("/proc/%d/ns/user", parent_pid);
userns2_fd = open_namespace_fd_if_needed (userns2_path, userns_path);
if (userns2_fd != -1)
flatpak_bwrap_add_args_data_fd (bwrap, "--userns2", userns2_fd, NULL);
}
pidns_path = g_strdup_printf ("/proc/%d/ns/pid", parent_pid);
pidns_fd = open (pidns_path, O_RDONLY|O_CLOEXEC);
if (pidns_fd != -1)
flatpak_bwrap_add_args_data_fd (bwrap, "--pidns", pidns_fd, NULL);
}
if (custom_command)
{
command = custom_command;
}
else if (metakey)
{
default_command = g_key_file_get_string (metakey,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_COMMAND,
&my_error);
if (my_error)
{
g_propagate_error (error, g_steal_pointer (&my_error));
return FALSE;
}
command = default_command;
}
if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))
return FALSE;
flatpak_bwrap_add_arg (bwrap, command);
if (!add_rest_args (bwrap, app_id,
exports, (flags & FLATPAK_RUN_FLAG_FILE_FORWARDING) != 0,
doc_mount_path,
args, n_args, error))
return FALSE;
flatpak_bwrap_finish (bwrap);
commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);
g_debug ("Running '%s'", commandline);
if ((flags & FLATPAK_RUN_FLAG_BACKGROUND) != 0)
{
GPid child_pid;
char pid_str[64];
g_autofree char *pid_path = NULL;
GSpawnFlags spawn_flags;
spawn_flags = G_SPAWN_SEARCH_PATH;
if (flags & FLATPAK_RUN_FLAG_DO_NOT_REAP)
spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
if (!g_spawn_async (NULL,
(char **) bwrap->argv->pdata,
bwrap->envp,
spawn_flags,
flatpak_bwrap_child_setup_cb, bwrap->fds,
&child_pid,
error))
return FALSE;
g_snprintf (pid_str, sizeof (pid_str), "%d", child_pid);
pid_path = g_build_filename (instance_id_host_dir, "pid", NULL);
g_file_set_contents (pid_path, pid_str, -1, NULL);
}
else
{
char pid_str[64];
g_autofree char *pid_path = NULL;
g_snprintf (pid_str, sizeof (pid_str), "%d", getpid ());
pid_path = g_build_filename (instance_id_host_dir, "pid", NULL);
g_file_set_contents (pid_path, pid_str, -1, NULL);
/* Ensure we unset O_CLOEXEC for marked fds and rewind fds as needed.
* Note that this does not close fds that are not already marked O_CLOEXEC, because
* we do want to allow inheriting fds into flatpak run. */
flatpak_bwrap_child_setup (bwrap->fds, FALSE);
if (execvpe (flatpak_get_bwrap (), (char **) bwrap->argv->pdata, bwrap->envp) == -1)
{
g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),
_("Unable to start app"));
return FALSE;
}
/* Not actually reached... */
}
if (instance_dir_out)
*instance_dir_out = g_steal_pointer (&instance_id_host_dir);
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1906_2 |
crossvul-cpp_data_bad_4069_7 | /**
* @file
* Send email to an SMTP server
*
* @authors
* Copyright (C) 2002 Michael R. Elkins <me@mutt.org>
* Copyright (C) 2005-2009 Brendan Cully <brendan@kublai.com>
* Copyright (C) 2019 Pietro Cerutti <gahr@gahr.ch>
*
* @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 smtp Send email to an SMTP server
*
* Send email to an SMTP server
*/
/* This file contains code for direct SMTP delivery of email messages. */
#include "config.h"
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "mutt/lib.h"
#include "address/lib.h"
#include "email/lib.h"
#include "conn/lib.h"
#include "smtp.h"
#include "globals.h"
#include "init.h"
#include "mutt_account.h"
#include "mutt_socket.h"
#include "progress.h"
#include "sendlib.h"
#ifdef USE_SSL
#include "config/lib.h"
#endif
#ifdef USE_SASL
#include <sasl/sasl.h>
#include <sasl/saslutil.h>
#include "options.h"
#endif
/* These Config Variables are only used in smtp.c */
struct Slist *C_SmtpAuthenticators; ///< Config: (smtp) List of allowed authentication methods
char *C_SmtpOauthRefreshCommand; ///< Config: (smtp) External command to generate OAUTH refresh token
char *C_SmtpPass; ///< Config: (smtp) Password for the SMTP server
char *C_SmtpUser; ///< Config: (smtp) Username for the SMTP server
#define smtp_success(x) ((x) / 100 == 2)
#define SMTP_READY 334
#define SMTP_CONTINUE 354
#define SMTP_ERR_READ -2
#define SMTP_ERR_WRITE -3
#define SMTP_ERR_CODE -4
#define SMTP_PORT 25
#define SMTPS_PORT 465
#define SMTP_AUTH_SUCCESS 0
#define SMTP_AUTH_UNAVAIL 1
#define SMTP_AUTH_FAIL -1
// clang-format off
/**
* typedef SmtpCapFlags - SMTP server capabilities
*/
typedef uint8_t SmtpCapFlags; ///< Flags, e.g. #SMTP_CAP_STARTTLS
#define SMTP_CAP_NO_FLAGS 0 ///< No flags are set
#define SMTP_CAP_STARTTLS (1 << 0) ///< Server supports STARTTLS command
#define SMTP_CAP_AUTH (1 << 1) ///< Server supports AUTH command
#define SMTP_CAP_DSN (1 << 2) ///< Server supports Delivery Status Notification
#define SMTP_CAP_EIGHTBITMIME (1 << 3) ///< Server supports 8-bit MIME content
#define SMTP_CAP_SMTPUTF8 (1 << 4) ///< Server accepts UTF-8 strings
#define SMTP_CAP_ALL ((1 << 5) - 1)
// clang-format on
static char *AuthMechs = NULL;
static SmtpCapFlags Capabilities;
/**
* valid_smtp_code - Is the is a valid SMTP return code?
* @param[in] buf String to check
* @param[in] buflen Length of string
* @param[out] n Numeric value of code
* @retval true Valid number
*/
static bool valid_smtp_code(char *buf, size_t buflen, int *n)
{
char code[4];
if (buflen < 4)
return false;
code[0] = buf[0];
code[1] = buf[1];
code[2] = buf[2];
code[3] = '\0';
if (mutt_str_atoi(code, n) < 0)
return false;
return true;
}
/**
* smtp_get_resp - Read a command response from the SMTP server
* @param conn SMTP connection
* @retval 0 Success (2xx code) or continue (354 code)
* @retval -1 Write error, or any other response code
*/
static int smtp_get_resp(struct Connection *conn)
{
int n;
char buf[1024];
do
{
n = mutt_socket_readln(buf, sizeof(buf), conn);
if (n < 4)
{
/* read error, or no response code */
return SMTP_ERR_READ;
}
const char *s = buf + 4; /* Skip the response code and the space/dash */
size_t plen;
if (mutt_str_startswith(s, "8BITMIME", CASE_IGNORE))
Capabilities |= SMTP_CAP_EIGHTBITMIME;
else if ((plen = mutt_str_startswith(s, "AUTH ", CASE_IGNORE)))
{
Capabilities |= SMTP_CAP_AUTH;
FREE(&AuthMechs);
AuthMechs = mutt_str_strdup(s + plen);
}
else if (mutt_str_startswith(s, "DSN", CASE_IGNORE))
Capabilities |= SMTP_CAP_DSN;
else if (mutt_str_startswith(s, "STARTTLS", CASE_IGNORE))
Capabilities |= SMTP_CAP_STARTTLS;
else if (mutt_str_startswith(s, "SMTPUTF8", CASE_IGNORE))
Capabilities |= SMTP_CAP_SMTPUTF8;
if (!valid_smtp_code(buf, n, &n))
return SMTP_ERR_CODE;
} while (buf[3] == '-');
if (smtp_success(n) || (n == SMTP_CONTINUE))
return 0;
mutt_error(_("SMTP session failed: %s"), buf);
return -1;
}
/**
* smtp_rcpt_to - Set the recipient to an Address
* @param conn Server Connection
* @param al AddressList to use
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_ERR_WRITE
*/
static int smtp_rcpt_to(struct Connection *conn, const struct AddressList *al)
{
if (!al)
return 0;
struct Address *a = NULL;
TAILQ_FOREACH(a, al, entries)
{
/* weed out group mailboxes, since those are for display only */
if (!a->mailbox || a->group)
{
continue;
}
char buf[1024];
if ((Capabilities & SMTP_CAP_DSN) && C_DsnNotify)
snprintf(buf, sizeof(buf), "RCPT TO:<%s> NOTIFY=%s\r\n", a->mailbox, C_DsnNotify);
else
snprintf(buf, sizeof(buf), "RCPT TO:<%s>\r\n", a->mailbox);
if (mutt_socket_send(conn, buf) == -1)
return SMTP_ERR_WRITE;
int rc = smtp_get_resp(conn);
if (rc != 0)
return rc;
}
return 0;
}
/**
* smtp_data - Send data to an SMTP server
* @param conn SMTP Connection
* @param msgfile Filename containing data
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_ERR_WRITE
*/
static int smtp_data(struct Connection *conn, const char *msgfile)
{
char buf[1024];
struct Progress progress;
struct stat st;
int rc, term = 0;
size_t buflen = 0;
FILE *fp = fopen(msgfile, "r");
if (!fp)
{
mutt_error(_("SMTP session failed: unable to open %s"), msgfile);
return -1;
}
stat(msgfile, &st);
unlink(msgfile);
mutt_progress_init(&progress, _("Sending message..."), MUTT_PROGRESS_NET, st.st_size);
snprintf(buf, sizeof(buf), "DATA\r\n");
if (mutt_socket_send(conn, buf) == -1)
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
rc = smtp_get_resp(conn);
if (rc != 0)
{
mutt_file_fclose(&fp);
return rc;
}
while (fgets(buf, sizeof(buf) - 1, fp))
{
buflen = mutt_str_strlen(buf);
term = buflen && buf[buflen - 1] == '\n';
if (term && ((buflen == 1) || (buf[buflen - 2] != '\r')))
snprintf(buf + buflen - 1, sizeof(buf) - buflen + 1, "\r\n");
if (buf[0] == '.')
{
if (mutt_socket_send_d(conn, ".", MUTT_SOCK_LOG_FULL) == -1)
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
}
if (mutt_socket_send_d(conn, buf, MUTT_SOCK_LOG_FULL) == -1)
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
mutt_progress_update(&progress, ftell(fp), -1);
}
if (!term && buflen && (mutt_socket_send_d(conn, "\r\n", MUTT_SOCK_LOG_FULL) == -1))
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
mutt_file_fclose(&fp);
/* terminate the message body */
if (mutt_socket_send(conn, ".\r\n") == -1)
return SMTP_ERR_WRITE;
rc = smtp_get_resp(conn);
if (rc != 0)
return rc;
return 0;
}
/**
* address_uses_unicode - Do any addresses use Unicode
* @param a Address list to check
* @retval true if any of the string of addresses use 8-bit characters
*/
static bool address_uses_unicode(const char *a)
{
if (!a)
return false;
while (*a)
{
if ((unsigned char) *a & (1 << 7))
return true;
a++;
}
return false;
}
/**
* addresses_use_unicode - Do any of a list of addresses use Unicode
* @param al Address list to check
* @retval true if any use 8-bit characters
*/
static bool addresses_use_unicode(const struct AddressList *al)
{
if (!al)
{
return false;
}
struct Address *a = NULL;
TAILQ_FOREACH(a, al, entries)
{
if (a->mailbox && !a->group && address_uses_unicode(a->mailbox))
return true;
}
return false;
}
/**
* smtp_get_field - Get connection login credentials - Implements ConnAccount::get_field()
*/
static const char *smtp_get_field(enum ConnAccountField field)
{
switch (field)
{
case MUTT_CA_LOGIN:
case MUTT_CA_USER:
return C_SmtpUser;
case MUTT_CA_PASS:
return C_SmtpPass;
case MUTT_CA_OAUTH_CMD:
return C_SmtpOauthRefreshCommand;
case MUTT_CA_HOST:
default:
return NULL;
}
}
/**
* smtp_fill_account - Create ConnAccount object from SMTP Url
* @param cac ConnAccount to populate
* @retval 0 Success
* @retval -1 Error
*/
static int smtp_fill_account(struct ConnAccount *cac)
{
cac->flags = 0;
cac->port = 0;
cac->type = MUTT_ACCT_TYPE_SMTP;
cac->service = "smtp";
cac->get_field = smtp_get_field;
struct Url *url = url_parse(C_SmtpUrl);
if (!url || ((url->scheme != U_SMTP) && (url->scheme != U_SMTPS)) ||
!url->host || (mutt_account_fromurl(cac, url) < 0))
{
url_free(&url);
mutt_error(_("Invalid SMTP URL: %s"), C_SmtpUrl);
return -1;
}
if (url->scheme == U_SMTPS)
cac->flags |= MUTT_ACCT_SSL;
if (cac->port == 0)
{
if (cac->flags & MUTT_ACCT_SSL)
cac->port = SMTPS_PORT;
else
{
static unsigned short SmtpPort = 0;
if (SmtpPort == 0)
{
struct servent *service = getservbyname("smtp", "tcp");
if (service)
SmtpPort = ntohs(service->s_port);
else
SmtpPort = SMTP_PORT;
mutt_debug(LL_DEBUG3, "Using default SMTP port %d\n", SmtpPort);
}
cac->port = SmtpPort;
}
}
url_free(&url);
return 0;
}
/**
* smtp_helo - Say hello to an SMTP Server
* @param conn SMTP Connection
* @param esmtp If true, use ESMTP
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_ERR_WRITE
*/
static int smtp_helo(struct Connection *conn, bool esmtp)
{
Capabilities = 0;
if (!esmtp)
{
/* if TLS or AUTH are requested, use EHLO */
if (conn->account.flags & MUTT_ACCT_USER)
esmtp = true;
#ifdef USE_SSL
if (C_SslForceTls || (C_SslStarttls != MUTT_NO))
esmtp = true;
#endif
}
const char *fqdn = mutt_fqdn(false);
if (!fqdn)
fqdn = NONULL(ShortHostname);
char buf[1024];
snprintf(buf, sizeof(buf), "%s %s\r\n", esmtp ? "EHLO" : "HELO", fqdn);
/* XXX there should probably be a wrapper in mutt_socket.c that
* repeatedly calls conn->write until all data is sent. This
* currently doesn't check for a short write. */
if (mutt_socket_send(conn, buf) == -1)
return SMTP_ERR_WRITE;
return smtp_get_resp(conn);
}
#ifdef USE_SASL
/**
* smtp_auth_sasl - Authenticate using SASL
* @param conn SMTP Connection
* @param mechlist List of mechanisms to use
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_AUTH_FAIL
*/
static int smtp_auth_sasl(struct Connection *conn, const char *mechlist)
{
sasl_conn_t *saslconn = NULL;
sasl_interact_t *interaction = NULL;
const char *mech = NULL;
const char *data = NULL;
unsigned int len;
char *buf = NULL;
size_t bufsize = 0;
int rc, saslrc;
if (mutt_sasl_client_new(conn, &saslconn) < 0)
return SMTP_AUTH_FAIL;
do
{
rc = sasl_client_start(saslconn, mechlist, &interaction, &data, &len, &mech);
if (rc == SASL_INTERACT)
mutt_sasl_interact(interaction);
} while (rc == SASL_INTERACT);
if ((rc != SASL_OK) && (rc != SASL_CONTINUE))
{
mutt_debug(LL_DEBUG2, "%s unavailable\n", mech);
sasl_dispose(&saslconn);
return SMTP_AUTH_UNAVAIL;
}
if (!OptNoCurses)
mutt_message(_("Authenticating (%s)..."), mech);
bufsize = MAX((len * 2), 1024);
buf = mutt_mem_malloc(bufsize);
snprintf(buf, bufsize, "AUTH %s", mech);
if (len)
{
mutt_str_strcat(buf, bufsize, " ");
if (sasl_encode64(data, len, buf + mutt_str_strlen(buf),
bufsize - mutt_str_strlen(buf), &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "#1 error base64-encoding client response\n");
goto fail;
}
}
mutt_str_strcat(buf, bufsize, "\r\n");
do
{
if (mutt_socket_send(conn, buf) < 0)
goto fail;
rc = mutt_socket_readln_d(buf, bufsize, conn, MUTT_SOCK_LOG_FULL);
if (rc < 0)
goto fail;
if (!valid_smtp_code(buf, rc, &rc))
goto fail;
if (rc != SMTP_READY)
break;
if (sasl_decode64(buf + 4, strlen(buf + 4), buf, bufsize - 1, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "error base64-decoding server response\n");
goto fail;
}
do
{
saslrc = sasl_client_step(saslconn, buf, len, &interaction, &data, &len);
if (saslrc == SASL_INTERACT)
mutt_sasl_interact(interaction);
} while (saslrc == SASL_INTERACT);
if (len)
{
if ((len * 2) > bufsize)
{
bufsize = len * 2;
mutt_mem_realloc(&buf, bufsize);
}
if (sasl_encode64(data, len, buf, bufsize, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "#2 error base64-encoding client response\n");
goto fail;
}
}
mutt_str_strfcpy(buf + len, "\r\n", bufsize - len);
} while (rc == SMTP_READY && saslrc != SASL_FAIL);
if (smtp_success(rc))
{
mutt_sasl_setup_conn(conn, saslconn);
FREE(&buf);
return SMTP_AUTH_SUCCESS;
}
fail:
sasl_dispose(&saslconn);
FREE(&buf);
return SMTP_AUTH_FAIL;
}
#endif
/**
* smtp_auth_oauth - Authenticate an SMTP connection using OAUTHBEARER
* @param conn Connection info
* @retval num Result, e.g. #SMTP_AUTH_SUCCESS
*/
static int smtp_auth_oauth(struct Connection *conn)
{
mutt_message(_("Authenticating (OAUTHBEARER)..."));
/* We get the access token from the smtp_oauth_refresh_command */
char *oauthbearer = mutt_account_getoauthbearer(&conn->account);
if (!oauthbearer)
return SMTP_AUTH_FAIL;
size_t ilen = strlen(oauthbearer) + 30;
char *ibuf = mutt_mem_malloc(ilen);
snprintf(ibuf, ilen, "AUTH OAUTHBEARER %s\r\n", oauthbearer);
int rc = mutt_socket_send(conn, ibuf);
FREE(&oauthbearer);
FREE(&ibuf);
if (rc == -1)
return SMTP_AUTH_FAIL;
if (smtp_get_resp(conn) != 0)
return SMTP_AUTH_FAIL;
return SMTP_AUTH_SUCCESS;
}
/**
* smtp_auth_plain - Authenticate using plain text
* @param conn SMTP Connection
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_AUTH_FAIL
*/
static int smtp_auth_plain(struct Connection *conn)
{
char buf[1024];
/* Get username and password. Bail out of any can't be retrieved. */
if ((mutt_account_getuser(&conn->account) < 0) ||
(mutt_account_getpass(&conn->account) < 0))
{
goto error;
}
/* Build the initial client response. */
size_t len = mutt_sasl_plain_msg(buf, sizeof(buf), "AUTH PLAIN", conn->account.user,
conn->account.user, conn->account.pass);
/* Terminate as per SMTP protocol. Bail out if there's no room left. */
if (snprintf(buf + len, sizeof(buf) - len, "\r\n") != 2)
{
goto error;
}
/* Send request, receive response (with a check for OK code). */
if ((mutt_socket_send(conn, buf) < 0) || smtp_get_resp(conn))
{
goto error;
}
/* If we got here, auth was successful. */
return 0;
error:
mutt_error(_("SASL authentication failed"));
return -1;
}
/**
* smtp_auth - Authenticate to an SMTP server
* @param conn SMTP Connection
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_AUTH_FAIL
*/
static int smtp_auth(struct Connection *conn)
{
int r = SMTP_AUTH_UNAVAIL;
if (C_SmtpAuthenticators)
{
struct ListNode *np = NULL;
STAILQ_FOREACH(np, &C_SmtpAuthenticators->head, entries)
{
mutt_debug(LL_DEBUG2, "Trying method %s\n", np->data);
if (strcmp(np->data, "oauthbearer") == 0)
{
r = smtp_auth_oauth(conn);
}
else if (strcmp(np->data, "plain") == 0)
{
r = smtp_auth_plain(conn);
}
else
{
#ifdef USE_SASL
r = smtp_auth_sasl(conn, np->data);
#else
mutt_error(_("SMTP authentication method %s requires SASL"), np->data);
continue;
#endif
}
if ((r == SMTP_AUTH_FAIL) && (C_SmtpAuthenticators->count > 1))
{
mutt_error(_("%s authentication failed, trying next method"), np->data);
}
else if (r != SMTP_AUTH_UNAVAIL)
break;
}
}
else
{
#ifdef USE_SASL
r = smtp_auth_sasl(conn, AuthMechs);
#else
mutt_error(_("SMTP authentication requires SASL"));
r = SMTP_AUTH_UNAVAIL;
#endif
}
if (r != SMTP_AUTH_SUCCESS)
mutt_account_unsetpass(&conn->account);
if (r == SMTP_AUTH_FAIL)
{
mutt_error(_("SASL authentication failed"));
}
else if (r == SMTP_AUTH_UNAVAIL)
{
mutt_error(_("No authenticators available"));
}
return (r == SMTP_AUTH_SUCCESS) ? 0 : -1;
}
/**
* smtp_open - Open an SMTP Connection
* @param conn SMTP Connection
* @param esmtp If true, use ESMTP
* @retval 0 Success
* @retval -1 Error
*/
static int smtp_open(struct Connection *conn, bool esmtp)
{
int rc;
if (mutt_socket_open(conn))
return -1;
/* get greeting string */
rc = smtp_get_resp(conn);
if (rc != 0)
return rc;
rc = smtp_helo(conn, esmtp);
if (rc != 0)
return rc;
#ifdef USE_SSL
enum QuadOption ans = MUTT_NO;
if (conn->ssf)
ans = MUTT_NO;
else if (C_SslForceTls)
ans = MUTT_YES;
else if ((Capabilities & SMTP_CAP_STARTTLS) &&
((ans = query_quadoption(C_SslStarttls,
_("Secure connection with TLS?"))) == MUTT_ABORT))
{
return -1;
}
if (ans == MUTT_YES)
{
if (mutt_socket_send(conn, "STARTTLS\r\n") < 0)
return SMTP_ERR_WRITE;
rc = smtp_get_resp(conn);
if (rc != 0)
return rc;
if (mutt_ssl_starttls(conn))
{
mutt_error(_("Could not negotiate TLS connection"));
return -1;
}
/* re-EHLO to get authentication mechanisms */
rc = smtp_helo(conn, esmtp);
if (rc != 0)
return rc;
}
#endif
if (conn->account.flags & MUTT_ACCT_USER)
{
if (!(Capabilities & SMTP_CAP_AUTH))
{
mutt_error(_("SMTP server does not support authentication"));
return -1;
}
return smtp_auth(conn);
}
return 0;
}
/**
* mutt_smtp_send - Send a message using SMTP
* @param from From Address
* @param to To Address
* @param cc Cc Address
* @param bcc Bcc Address
* @param msgfile Message to send to the server
* @param eightbit If true, try for an 8-bit friendly connection
* @retval 0 Success
* @retval -1 Error
*/
int mutt_smtp_send(const struct AddressList *from, const struct AddressList *to,
const struct AddressList *cc, const struct AddressList *bcc,
const char *msgfile, bool eightbit)
{
struct Connection *conn = NULL;
struct ConnAccount cac = { { 0 } };
const char *envfrom = NULL;
char buf[1024];
int rc = -1;
/* it might be better to synthesize an envelope from from user and host
* but this condition is most likely arrived at accidentally */
if (C_EnvelopeFromAddress)
envfrom = C_EnvelopeFromAddress->mailbox;
else if (from && !TAILQ_EMPTY(from))
envfrom = TAILQ_FIRST(from)->mailbox;
else
{
mutt_error(_("No from address given"));
return -1;
}
if (smtp_fill_account(&cac) < 0)
return rc;
conn = mutt_conn_find(&cac);
if (!conn)
return -1;
do
{
/* send our greeting */
rc = smtp_open(conn, eightbit);
if (rc != 0)
break;
FREE(&AuthMechs);
/* send the sender's address */
int len = snprintf(buf, sizeof(buf), "MAIL FROM:<%s>", envfrom);
if (eightbit && (Capabilities & SMTP_CAP_EIGHTBITMIME))
{
mutt_str_strncat(buf, sizeof(buf), " BODY=8BITMIME", 15);
len += 14;
}
if (C_DsnReturn && (Capabilities & SMTP_CAP_DSN))
len += snprintf(buf + len, sizeof(buf) - len, " RET=%s", C_DsnReturn);
if ((Capabilities & SMTP_CAP_SMTPUTF8) &&
(address_uses_unicode(envfrom) || addresses_use_unicode(to) ||
addresses_use_unicode(cc) || addresses_use_unicode(bcc)))
{
snprintf(buf + len, sizeof(buf) - len, " SMTPUTF8");
}
mutt_str_strncat(buf, sizeof(buf), "\r\n", 3);
if (mutt_socket_send(conn, buf) == -1)
{
rc = SMTP_ERR_WRITE;
break;
}
rc = smtp_get_resp(conn);
if (rc != 0)
break;
/* send the recipient list */
if ((rc = smtp_rcpt_to(conn, to)) || (rc = smtp_rcpt_to(conn, cc)) ||
(rc = smtp_rcpt_to(conn, bcc)))
{
break;
}
/* send the message data */
rc = smtp_data(conn, msgfile);
if (rc != 0)
break;
mutt_socket_send(conn, "QUIT\r\n");
rc = 0;
} while (false);
mutt_socket_close(conn);
FREE(&conn);
if (rc == SMTP_ERR_READ)
mutt_error(_("SMTP session failed: read error"));
else if (rc == SMTP_ERR_WRITE)
mutt_error(_("SMTP session failed: write error"));
else if (rc == SMTP_ERR_CODE)
mutt_error(_("Invalid server response"));
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_4069_7 |
crossvul-cpp_data_bad_1909_0 | /*
* Copyright © 2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
/* NOTE: This code was copied mostly as-is from xdg-desktop-portal */
#include <locale.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
#include <gio/gdesktopappinfo.h>
#include "flatpak-portal-dbus.h"
#include "flatpak-portal.h"
#include "flatpak-dir-private.h"
#include "flatpak-utils-private.h"
#include "flatpak-transaction.h"
#include "flatpak-installation-private.h"
#include "flatpak-instance-private.h"
#include "flatpak-portal-app-info.h"
#include "flatpak-portal-error.h"
#include "flatpak-utils-base-private.h"
#include "portal-impl.h"
#include "flatpak-permission-dbus.h"
/* GLib 2.47.92 was the first release to define these in gdbus-codegen */
#if !GLIB_CHECK_VERSION (2, 47, 92)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakSkeleton, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorSkeleton, g_object_unref)
#endif
#define IDLE_TIMEOUT_SECS 10 * 60
/* Should be roughly 2 seconds */
#define CHILD_STATUS_CHECK_ATTEMPTS 20
static GHashTable *client_pid_data_hash = NULL;
static GDBusConnection *session_bus = NULL;
static GNetworkMonitor *network_monitor = NULL;
static gboolean no_idle_exit = FALSE;
static guint name_owner_id = 0;
static GMainLoop *main_loop;
static PortalFlatpak *portal;
static gboolean opt_verbose;
static int opt_poll_timeout;
static gboolean opt_poll_when_metered;
static FlatpakSpawnSupportFlags supports = 0;
G_LOCK_DEFINE (update_monitors); /* This protects the three variables below */
static GHashTable *update_monitors;
static guint update_monitors_timeout = 0;
static gboolean update_monitors_timeout_running_thread = FALSE;
/* Poll all update monitors twice an hour */
#define DEFAULT_UPDATE_POLL_TIMEOUT_SEC (30 * 60)
#define PERMISSION_TABLE "flatpak"
#define PERMISSION_ID "updates"
/* Instance IDs are 32-bit unsigned integers */
#define INSTANCE_ID_BUFFER_SIZE 16
typedef enum { UNSET, ASK, YES, NO } Permission;
typedef enum {
PROGRESS_STATUS_RUNNING = 0,
PROGRESS_STATUS_EMPTY = 1,
PROGRESS_STATUS_DONE = 2,
PROGRESS_STATUS_ERROR = 3
} UpdateStatus;
static XdpDbusPermissionStore *permission_store;
typedef struct {
GMutex lock; /* This protects the closed, running and installed state */
gboolean closed;
gboolean running; /* While this is set, don't close the monitor */
gboolean installing;
char *sender;
char *obj_path;
GCancellable *cancellable;
/* Static data */
char *name;
char *arch;
char *branch;
char *commit;
char *app_path;
/* Last reported values, starting at the instance commit */
char *reported_local_commit;
char *reported_remote_commit;
} UpdateMonitorData;
static gboolean check_all_for_updates_cb (void *data);
static gboolean has_update_monitors (void);
static UpdateMonitorData *update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor);
static gboolean handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation);
static gboolean handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options);
static void
skeleton_died_cb (gpointer data)
{
g_debug ("skeleton finalized, exiting");
g_main_loop_quit (main_loop);
}
static gboolean
unref_skeleton_in_timeout_cb (gpointer user_data)
{
static gboolean unreffed = FALSE;
g_debug ("unreffing portal main ref");
if (!unreffed)
{
g_object_unref (portal);
unreffed = TRUE;
}
return G_SOURCE_REMOVE;
}
static void
unref_skeleton_in_timeout (void)
{
if (name_owner_id)
g_bus_unown_name (name_owner_id);
name_owner_id = 0;
/* After we've lost the name or idled we drop the main ref on the helper
so that we'll exit when it drops to zero. However, if there are
outstanding calls these will keep the refcount up during the
execution of them. We do the unref on a timeout to make sure
we're completely draining the queue of (stale) requests. */
g_timeout_add (500, unref_skeleton_in_timeout_cb, NULL);
}
static guint idle_timeout_id = 0;
static gboolean
idle_timeout_cb (gpointer user_data)
{
if (name_owner_id &&
g_hash_table_size (client_pid_data_hash) == 0 &&
!has_update_monitors ())
{
g_debug ("Idle - unowning name");
unref_skeleton_in_timeout ();
}
idle_timeout_id = 0;
return G_SOURCE_REMOVE;
}
G_LOCK_DEFINE_STATIC (idle);
static void
schedule_idle_callback (void)
{
G_LOCK (idle);
if (!no_idle_exit)
{
if (idle_timeout_id != 0)
g_source_remove (idle_timeout_id);
idle_timeout_id = g_timeout_add_seconds (IDLE_TIMEOUT_SECS, idle_timeout_cb, NULL);
}
G_UNLOCK (idle);
}
typedef struct
{
GPid pid;
char *client;
guint child_watch;
gboolean watch_bus;
gboolean expose_or_share_pids;
} PidData;
static void
pid_data_free (PidData *data)
{
g_free (data->client);
g_free (data);
}
static void
child_watch_died (GPid pid,
gint status,
gpointer user_data)
{
PidData *pid_data = user_data;
g_autoptr(GVariant) signal_variant = NULL;
g_debug ("Client Pid %d died", pid_data->pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, status));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnExited",
signal_variant,
NULL);
/* This frees the pid_data, so be careful */
g_hash_table_remove (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid));
/* This might have caused us to go to idle (zero children) */
schedule_idle_callback ();
}
typedef struct
{
int from;
int to;
int final;
} FdMapEntry;
typedef struct
{
FdMapEntry *fd_map;
int fd_map_len;
int instance_id_fd;
gboolean set_tty;
int tty;
int env_fd;
} ChildSetupData;
typedef struct
{
guint pid;
gchar buffer[INSTANCE_ID_BUFFER_SIZE];
} InstanceIdReadData;
typedef struct
{
FlatpakInstance *instance;
guint pid;
guint attempt;
} BwrapinfoWatcherData;
static void
bwrapinfo_watcher_data_free (BwrapinfoWatcherData* data)
{
g_object_unref (data->instance);
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (BwrapinfoWatcherData, bwrapinfo_watcher_data_free)
static int
get_child_pid_relative_to_parent_sandbox (int pid,
GError **error)
{
g_autofree char *status_file_path = NULL;
g_autoptr(GFile) status_file = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
int relative_pid = 0;
status_file_path = g_strdup_printf ("/proc/%u/status", pid);
status_file = g_file_new_for_path (status_file_path);
input_stream = g_file_read (status_file, NULL, error);
if (input_stream == NULL)
return 0;
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line_utf8 (data_stream, NULL, NULL, error);
if (line == NULL)
break;
g_strchug (line);
if (g_str_has_prefix (line, "NSpid:"))
{
g_auto(GStrv) fields = NULL;
guint nfields = 0;
char *endptr = NULL;
fields = g_strsplit (line, "\t", -1);
nfields = g_strv_length (fields);
if (nfields < 3)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"NSpid line has too few fields: %s", line);
return 0;
}
/* The second to last PID namespace is the one that spawned this process */
relative_pid = strtol (fields[nfields - 2], &endptr, 10);
if (*endptr)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"Invalid parent-relative PID in NSpid line: %s", line);
return 0;
}
return relative_pid;
}
}
if (*error == NULL)
/* EOF was reached while reading the file */
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "NSpid not found");
return 0;
}
static int
check_child_pid_status (void *user_data)
{
/* Stores a sequence of the time interval to use until the child PID is checked again.
In general from testing, bwrapinfo is never ready before 25ms have passed at minimum,
thus 25ms is the first interval, doubling until a max interval of 100ms is reached.
In addition, if the program is not available after 100ms for an extended period of time,
the timeout is further increased to a full second. */
static gint timeouts[] = {25, 50, 100};
g_autoptr(GVariant) signal_variant = NULL;
g_autoptr(BwrapinfoWatcherData) data = user_data;
PidData *pid_data;
guint pid;
int child_pid;
int relative_child_pid = 0;
pid = data->pid;
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (pid));
/* Process likely already exited if pid_data == NULL, so don't send the
signal to avoid an awkward out-of-order SpawnExited -> SpawnStarted. */
if (pid_data == NULL)
{
g_warning ("%u already exited, skipping SpawnStarted", pid);
return G_SOURCE_REMOVE;
}
child_pid = flatpak_instance_get_child_pid (data->instance);
if (child_pid == 0)
{
gint timeout;
gboolean readd_timer = FALSE;
if (data->attempt >= CHILD_STATUS_CHECK_ATTEMPTS)
/* If too many attempts, use a 1 second timeout */
timeout = 1000;
else
timeout = timeouts[MIN (data->attempt, G_N_ELEMENTS (timeouts) - 1)];
g_debug ("Failed to read child PID, trying again in %d ms", timeout);
/* The timer source only needs to be re-added if the timeout has changed,
which won't happen while staying on the 100 or 1000ms timeouts.
This test must happen *before* the attempt counter is incremented, since the
attempt counter represents the *current* timeout. */
readd_timer = data->attempt <= G_N_ELEMENTS (timeouts) || data->attempt == CHILD_STATUS_CHECK_ATTEMPTS;
data->attempt++;
/* Make sure the data isn't destroyed */
data = NULL;
if (readd_timer)
{
g_timeout_add (timeout, check_child_pid_status, user_data);
return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
/* Only send the child PID if it's exposed */
if (pid_data->expose_or_share_pids)
{
g_autoptr(GError) error = NULL;
relative_child_pid = get_child_pid_relative_to_parent_sandbox (child_pid, &error);
if (relative_child_pid == 0)
g_warning ("Failed to find relative PID for %d: %s", child_pid, error->message);
}
g_debug ("Emitting SpawnStarted(%u, %d)", pid, relative_child_pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, relative_child_pid));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnStarted",
signal_variant,
NULL);
return G_SOURCE_REMOVE;
}
static void
instance_id_read_finish (GObject *source,
GAsyncResult *res,
gpointer user_data)
{
g_autoptr(GInputStream) stream = NULL;
g_autofree InstanceIdReadData *data = NULL;
g_autoptr(FlatpakInstance) instance = NULL;
g_autoptr(GError) error = NULL;
BwrapinfoWatcherData *watcher_data = NULL;
gssize bytes_read;
stream = G_INPUT_STREAM (source);
data = (InstanceIdReadData *) user_data;
bytes_read = g_input_stream_read_finish (stream, res, &error);
if (bytes_read <= 0)
{
/* 0 means EOF, so the process could never have been started. */
if (bytes_read == -1)
g_warning ("Failed to read instance id: %s", error->message);
return;
}
data->buffer[bytes_read] = 0;
instance = flatpak_instance_new_for_id (data->buffer);
watcher_data = g_new0 (BwrapinfoWatcherData, 1);
watcher_data->instance = g_steal_pointer (&instance);
watcher_data->pid = data->pid;
check_child_pid_status (watcher_data);
}
static void
drop_cloexec (int fd)
{
fcntl (fd, F_SETFD, 0);
}
static void
child_setup_func (gpointer user_data)
{
ChildSetupData *data = (ChildSetupData *) user_data;
FdMapEntry *fd_map = data->fd_map;
sigset_t set;
int i;
flatpak_close_fds_workaround (3);
if (data->instance_id_fd != -1)
drop_cloexec (data->instance_id_fd);
if (data->env_fd != -1)
drop_cloexec (data->env_fd);
/* Unblock all signals */
sigemptyset (&set);
if (pthread_sigmask (SIG_SETMASK, &set, NULL) == -1)
{
g_warning ("Failed to unblock signals when starting child");
return;
}
/* Reset the handlers for all signals to their defaults. */
for (i = 1; i < NSIG; i++)
{
if (i != SIGSTOP && i != SIGKILL)
signal (i, SIG_DFL);
}
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from != fd_map[i].to)
{
dup2 (fd_map[i].from, fd_map[i].to);
close (fd_map[i].from);
}
}
/* Second pass in case we needed an in-between fd value to avoid conflicts */
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].to != fd_map[i].final)
{
dup2 (fd_map[i].to, fd_map[i].final);
close (fd_map[i].to);
}
/* Ensure we inherit the final fd value */
drop_cloexec (fd_map[i].final);
}
/* We become our own session and process group, because it never makes sense
to share the flatpak-session-helper dbus activated process group */
setsid ();
setpgid (0, 0);
if (data->set_tty)
{
/* data->tty is our from fd which is closed at this point.
* so locate the destination fd and use it for the ioctl.
*/
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from == data->tty)
{
if (ioctl (fd_map[i].final, TIOCSCTTY, 0) == -1)
g_debug ("ioctl(%d, TIOCSCTTY, 0) failed: %s",
fd_map[i].final, strerror (errno));
break;
}
}
}
}
static gboolean
is_valid_expose (const char *expose,
GError **error)
{
/* No subdirs or absolute paths */
if (expose[0] == '/')
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: absolute paths not allowed");
return FALSE;
}
else if (strchr (expose, '/'))
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: subdirectories not allowed");
return FALSE;
}
return TRUE;
}
static char *
filesystem_arg (const char *path,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
filesystem_sandbox_arg (const char *path,
const char *sandbox,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
g_string_append (s, "/sandbox/");
for (p = sandbox; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
bubblewrap_remap_path (const char *path)
{
if (g_str_has_prefix (path, "/newroot/"))
path = path + strlen ("/newroot");
return g_strdup (path);
}
static char *
verify_proc_self_fd (const char *proc_path,
GError **error)
{
char path_buffer[PATH_MAX + 1];
ssize_t symlink_size;
symlink_size = readlink (proc_path, path_buffer, PATH_MAX);
if (symlink_size < 0)
return glnx_null_throw_errno_prefix (error, "readlink");
path_buffer[symlink_size] = 0;
/* All normal paths start with /, but some weird things
don't, such as socket:[27345] or anon_inode:[eventfd].
We don't support any of these */
if (path_buffer[0] != '/')
return glnx_null_throw (error, "%s resolves to non-absolute path %s",
proc_path, path_buffer);
/* File descriptors to actually deleted files have " (deleted)"
appended to them. This also happens to some fake fd types
like shmem which are "/<name> (deleted)". All such
files are considered invalid. Unfortunatelly this also
matches files with filenames that actually end in " (deleted)",
but there is not much to do about this. */
if (g_str_has_suffix (path_buffer, " (deleted)"))
return glnx_null_throw (error, "%s resolves to deleted path %s",
proc_path, path_buffer);
/* remap from sandbox to host if needed */
return bubblewrap_remap_path (path_buffer);
}
static char *
get_path_for_fd (int fd,
gboolean *writable_out,
GError **error)
{
g_autofree char *proc_path = NULL;
int fd_flags;
struct stat st_buf;
struct stat real_st_buf;
g_autofree char *path = NULL;
gboolean writable = FALSE;
int read_access_mode;
/* Must be able to get fd flags */
fd_flags = fcntl (fd, F_GETFL);
if (fd_flags == -1)
return glnx_null_throw_errno_prefix (error, "fcntl F_GETFL");
/* Must be O_PATH */
if ((fd_flags & O_PATH) != O_PATH)
return glnx_null_throw (error, "not opened with O_PATH");
/* We don't want to allow exposing symlinks, because if they are
* under the callers control they could be changed between now and
* starting the child allowing it to point anywhere, so enforce NOFOLLOW.
* and verify that stat is not a link.
*/
if ((fd_flags & O_NOFOLLOW) != O_NOFOLLOW)
return glnx_null_throw (error, "not opened with O_NOFOLLOW");
/* Must be able to fstat */
if (fstat (fd, &st_buf) < 0)
return glnx_null_throw_errno_prefix (error, "fstat");
/* As per above, no symlinks */
if (S_ISLNK (st_buf.st_mode))
return glnx_null_throw (error, "is a symbolic link");
proc_path = g_strdup_printf ("/proc/self/fd/%d", fd);
/* Must be able to read valid path from /proc/self/fd */
/* This is an absolute and (at least at open time) symlink-expanded path */
path = verify_proc_self_fd (proc_path, error);
if (path == NULL)
return NULL;
/* Verify that this is the same file as the app opened */
if (stat (path, &real_st_buf) < 0 ||
st_buf.st_dev != real_st_buf.st_dev ||
st_buf.st_ino != real_st_buf.st_ino)
{
/* Different files on the inside and the outside, reject the request */
return glnx_null_throw (error,
"different file inside and outside sandbox");
}
read_access_mode = R_OK;
if (S_ISDIR (st_buf.st_mode))
read_access_mode |= X_OK;
/* Must be able to access the path via the sandbox supplied O_PATH fd,
which applies the sandbox side mount options (like readonly). */
if (access (proc_path, read_access_mode) != 0)
return glnx_null_throw (error, "not %s in sandbox",
read_access_mode & X_OK ? "accessible" : "readable");
if (access (proc_path, W_OK) == 0)
writable = TRUE;
*writable_out = writable;
return g_steal_pointer (&path);
}
static gboolean
handle_spawn (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GUnixFDList *fd_list,
const gchar *arg_cwd_path,
const gchar *const *arg_argv,
GVariant *arg_fds,
GVariant *arg_envs,
guint arg_flags,
GVariant *arg_options)
{
g_autoptr(GError) error = NULL;
ChildSetupData child_setup_data = { NULL };
GPid pid;
PidData *pid_data;
InstanceIdReadData *instance_id_read_data = NULL;
gsize i, j, n_fds, n_envs;
const gint *fds = NULL;
gint fds_len = 0;
g_autofree FdMapEntry *fd_map = NULL;
gchar **env;
gint32 max_fd;
GKeyFile *app_info;
g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);
g_autofree char *app_id = NULL;
g_autofree char *branch = NULL;
g_autofree char *arch = NULL;
g_autofree char *app_commit = NULL;
g_autofree char *runtime_ref = NULL;
g_auto(GStrv) runtime_parts = NULL;
g_autofree char *runtime_commit = NULL;
g_autofree char *instance_path = NULL;
g_auto(GStrv) extra_args = NULL;
g_auto(GStrv) shares = NULL;
g_auto(GStrv) sockets = NULL;
g_auto(GStrv) devices = NULL;
g_auto(GStrv) sandbox_expose = NULL;
g_auto(GStrv) sandbox_expose_ro = NULL;
g_autoptr(GVariant) sandbox_expose_fd = NULL;
g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;
g_autoptr(GOutputStream) instance_id_out_stream = NULL;
guint sandbox_flags = 0;
gboolean sandboxed;
gboolean expose_pids;
gboolean share_pids;
gboolean notify_start;
gboolean devel;
g_autoptr(GString) env_string = g_string_new ("");
child_setup_data.instance_id_fd = -1;
child_setup_data.env_fd = -1;
if (fd_list != NULL)
fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);
app_info = g_object_get_data (G_OBJECT (invocation), "app-info");
g_assert (app_info != NULL);
app_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, NULL);
g_assert (app_id != NULL);
g_debug ("spawn() called from app: '%s'", app_id);
if (*app_id == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (*arg_cwd_path == 0)
arg_cwd_path = NULL;
if (arg_argv == NULL || *arg_argv == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No command given");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_ref = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_RUNTIME, NULL);
if (runtime_ref == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"No runtime found");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_parts = g_strsplit (runtime_ref, "/", -1);
branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BRANCH, NULL);
instance_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);
arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_ARCH, NULL);
extra_args = g_key_file_get_string_list (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);
app_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_COMMIT, NULL);
runtime_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);
shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED, NULL, NULL);
sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);
devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);
devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_DEVEL, NULL);
g_variant_lookup (arg_options, "sandbox-expose", "^as", &sandbox_expose);
g_variant_lookup (arg_options, "sandbox-expose-ro", "^as", &sandbox_expose_ro);
g_variant_lookup (arg_options, "sandbox-flags", "u", &sandbox_flags);
sandbox_expose_fd = g_variant_lookup_value (arg_options, "sandbox-expose-fd", G_VARIANT_TYPE ("ah"));
sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, "sandbox-expose-fd-ro", G_VARIANT_TYPE ("ah"));
if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported sandbox flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_path == NULL &&
((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||
(sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose, caller has no instance path");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
{
const char *expose = sandbox_expose[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
g_debug ("Running spawn command %s", arg_argv[0]);
n_fds = 0;
if (fds != NULL)
n_fds = g_variant_n_children (arg_fds);
fd_map = g_new0 (FdMapEntry, n_fds);
child_setup_data.fd_map = fd_map;
child_setup_data.fd_map_len = n_fds;
max_fd = -1;
for (i = 0; i < n_fds; i++)
{
gint32 handle, dest_fd;
int handle_fd;
g_variant_get_child (arg_fds, i, "{uh}", &dest_fd, &handle);
if (handle >= fds_len || handle < 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
handle_fd = fds[handle];
fd_map[i].to = dest_fd;
fd_map[i].from = handle_fd;
fd_map[i].final = fd_map[i].to;
/* If stdin/out/err is a tty we try to set it as the controlling
tty for the app, this way we can use this to run in a terminal. */
if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&
!child_setup_data.set_tty &&
isatty (handle_fd))
{
child_setup_data.set_tty = TRUE;
child_setup_data.tty = handle_fd;
}
max_fd = MAX (max_fd, fd_map[i].to);
max_fd = MAX (max_fd, fd_map[i].from);
}
/* We make a second pass over the fds to find if any "to" fd index
overlaps an already in use fd (i.e. one in the "from" category
that are allocated randomly). If a fd overlaps "to" fd then its
a caller issue and not our fault, so we ignore that. */
for (i = 0; i < n_fds; i++)
{
int to_fd = fd_map[i].to;
gboolean conflict = FALSE;
/* At this point we're fine with using "from" values for this
value (because we handle to==from in the code), or values
that are before "i" in the fd_map (because those will be
closed at this point when dup:ing). However, we can't
reuse a fd that is in "from" for j > i. */
for (j = i + 1; j < n_fds; j++)
{
int from_fd = fd_map[j].from;
if (from_fd == to_fd)
{
conflict = TRUE;
break;
}
}
if (conflict)
fd_map[i].to = ++max_fd;
}
if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)
{
char *empty[] = { NULL };
env = g_strdupv (empty);
}
else
env = g_get_environ ();
n_envs = g_variant_n_children (arg_envs);
for (i = 0; i < n_envs; i++)
{
const char *var = NULL;
const char *val = NULL;
g_variant_get_child (arg_envs, i, "{&s&s}", &var, &val);
env = g_environ_setenv (env, var, val, TRUE);
}
g_ptr_array_add (flatpak_argv, g_strdup ("flatpak"));
g_ptr_array_add (flatpak_argv, g_strdup ("run"));
sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;
if (sandboxed)
{
g_ptr_array_add (flatpak_argv, g_strdup ("--sandbox"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "wayland"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=wayland"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "fallback-x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=fallback-x11"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=x11"));
if (shares != NULL && g_strv_contains ((const char * const *) shares, "ipc") &&
sockets != NULL && (g_strv_contains ((const char * const *) sockets, "fallback-x11") ||
g_strv_contains ((const char * const *) sockets, "x11")))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=ipc"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "pulseaudio"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=pulseaudio"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)
{
if (devices != NULL &&
(g_strv_contains ((const char * const *) devices, "dri") ||
g_strv_contains ((const char * const *) devices, "all")))
g_ptr_array_add (flatpak_argv, g_strdup ("--device=dri"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)
g_ptr_array_add (flatpak_argv, g_strdup ("--session-bus"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)
g_ptr_array_add (flatpak_argv, g_strdup ("--a11y-bus"));
}
else
{
for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)
{
if (g_str_has_prefix (extra_args[i], "--env="))
{
const char *var_val = extra_args[i] + strlen ("--env=");
if (var_val[0] == '\0' || var_val[0] == '=')
{
g_warning ("Environment variable in extra-args has empty name");
continue;
}
if (strchr (var_val, '=') == NULL)
{
g_warning ("Environment variable in extra-args has no value");
continue;
}
g_string_append (env_string, var_val);
g_string_append_c (env_string, '\0');
}
else
{
g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));
}
}
}
if (env_string->len > 0)
{
g_auto(GLnxTmpfile) env_tmpf = { 0, };
if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&env_tmpf, "environ",
env_string->str,
env_string->len, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
child_setup_data.env_fd = glnx_steal_fd (&env_tmpf.fd);
g_ptr_array_add (flatpak_argv,
g_strdup_printf ("--env-fd=%d",
child_setup_data.env_fd));
}
expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;
share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;
if (expose_pids || share_pids)
{
g_autofree char *instance_id = NULL;
int sender_pid1 = 0;
if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_NOT_SUPPORTED,
"Expose pids not supported with setuid bwrap");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
instance_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);
if (instance_id)
{
g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);
sender_pid1 = flatpak_instance_get_child_pid (instance);
}
if (sender_pid1 == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Could not find requesting pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--parent-pid=%d", sender_pid1));
if (share_pids)
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-share-pids"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-expose-pids"));
}
notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;
if (notify_start)
{
int pipe_fds[2];
if (pipe (pipe_fds) == -1)
{
int errsv = errno;
g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,
g_io_error_from_errno (errsv),
"Failed to create instance ID pipe: %s",
g_strerror (errsv));
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));
/* This is saved to ensure the portal's end gets closed after the exec. */
instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));
instance_id_read_data = g_new0 (InstanceIdReadData, 1);
g_input_stream_read_async (in_stream, instance_id_read_data->buffer,
INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,
instance_id_read_finish, instance_id_read_data);
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--instance-id-fd=%d", pipe_fds[1]));
child_setup_data.instance_id_fd = pipe_fds[1];
}
if (devel)
g_ptr_array_add (flatpak_argv, g_strdup ("--devel"));
/* Inherit launcher network access from launcher, unless
NO_NETWORK set. */
if (shares != NULL && g_strv_contains ((const char * const *) shares, "network") &&
!(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=network"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--unshare=network"));
if (instance_path)
{
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
}
if (sandbox_expose_fd != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
if (sandbox_expose_fd_ro != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd_ro);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd_ro, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime=%s", runtime_parts[1]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-version=%s", runtime_parts[3]));
if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)
{
if (app_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--commit=%s", app_commit));
if (runtime_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-commit=%s", runtime_commit));
}
if (arg_cwd_path != NULL)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--cwd=%s", arg_cwd_path));
if (arg_argv[0][0] != 0)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--command=%s", arg_argv[0]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("%s/%s/%s", app_id, arch ? arch : "", branch ? branch : ""));
for (i = 1; arg_argv[i] != NULL; i++)
g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));
g_ptr_array_add (flatpak_argv, NULL);
if (opt_verbose)
{
g_autoptr(GString) cmd = g_string_new ("");
for (i = 0; flatpak_argv->pdata[i] != NULL; i++)
{
if (i > 0)
g_string_append (cmd, " ");
g_string_append (cmd, flatpak_argv->pdata[i]);
}
g_debug ("Starting: %s\n", cmd->str);
}
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_async_with_pipes (NULL,
(char **) flatpak_argv->pdata,
env,
G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
child_setup_func, &child_setup_data,
&pid,
NULL,
NULL,
NULL,
&error))
{
gint code = G_DBUS_ERROR_FAILED;
if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))
code = G_DBUS_ERROR_ACCESS_DENIED;
else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))
code = G_DBUS_ERROR_FILE_NOT_FOUND;
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,
"Failed to start command: %s",
error->message);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_id_read_data)
instance_id_read_data->pid = pid;
pid_data = g_new0 (PidData, 1);
pid_data->pid = pid;
pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));
pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;
pid_data->expose_or_share_pids = (expose_pids || share_pids);
pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,
pid,
child_watch_died,
pid_data,
NULL);
g_debug ("Client Pid is %d", pid_data->pid);
g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),
pid_data);
portal_flatpak_complete_spawn (object, invocation, NULL, pid);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
handle_spawn_signal (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
guint arg_pid,
guint arg_signal,
gboolean arg_to_process_group)
{
PidData *pid_data = NULL;
g_debug ("spawn_signal(%d %d)", arg_pid, arg_signal);
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (arg_pid));
if (pid_data == NULL ||
strcmp (pid_data->client, g_dbus_method_invocation_get_sender (invocation)) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,
"No such pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_debug ("Sending signal %d to client pid %d", arg_signal, arg_pid);
if (arg_to_process_group)
killpg (pid_data->pid, arg_signal);
else
kill (pid_data->pid, arg_signal);
portal_flatpak_complete_spawn_signal (portal, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
authorize_method_handler (GDBusInterfaceSkeleton *interface,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
g_autoptr(GError) error = NULL;
g_autoptr(GKeyFile) keyfile = NULL;
g_autofree char *app_id = NULL;
const char *required_sender;
/* Ensure we don't idle exit */
schedule_idle_callback ();
required_sender = g_object_get_data (G_OBJECT (interface), "required-sender");
if (required_sender)
{
const char *sender = g_dbus_method_invocation_get_sender (invocation);
if (g_strcmp0 (required_sender, sender) != 0)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
"Client not allowed to access object");
return FALSE;
}
}
keyfile = flatpak_invocation_lookup_app_info (invocation, NULL, &error);
if (keyfile == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
app_id = g_key_file_get_string (keyfile,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, &error);
if (app_id == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
g_object_set_data_full (G_OBJECT (invocation), "app-info", g_steal_pointer (&keyfile), (GDestroyNotify) g_key_file_unref);
return TRUE;
}
static void
register_update_monitor (PortalFlatpakUpdateMonitor *monitor,
const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_insert (update_monitors, g_strdup (obj_path), g_object_ref (monitor));
/* Trigger update timeout if needed */
if (update_monitors_timeout == 0 && !update_monitors_timeout_running_thread)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
static void
unregister_update_monitor (const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_remove (update_monitors, obj_path);
G_UNLOCK (update_monitors);
}
static gboolean
has_update_monitors (void)
{
gboolean res;
G_LOCK (update_monitors);
res = g_hash_table_size (update_monitors) > 0;
G_UNLOCK (update_monitors);
return res;
}
static GList *
update_monitors_get_all (const char *optional_sender)
{
GList *list = NULL;
G_LOCK (update_monitors);
if (update_monitors)
{
GLNX_HASH_TABLE_FOREACH_V (update_monitors, PortalFlatpakUpdateMonitor *, monitor)
{
UpdateMonitorData *data = update_monitor_get_data (monitor);
if (optional_sender == NULL ||
strcmp (data->sender, optional_sender) == 0)
list = g_list_prepend (list, g_object_ref (monitor));
}
}
G_UNLOCK (update_monitors);
return list;
}
static void
update_monitor_data_free (gpointer data)
{
UpdateMonitorData *m = data;
g_mutex_clear (&m->lock);
g_free (m->sender);
g_free (m->obj_path);
g_object_unref (m->cancellable);
g_free (m->name);
g_free (m->arch);
g_free (m->branch);
g_free (m->commit);
g_free (m->app_path);
g_free (m->reported_local_commit);
g_free (m->reported_remote_commit);
g_free (m);
}
static UpdateMonitorData *
update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor)
{
return (UpdateMonitorData *)g_object_get_data (G_OBJECT (monitor), "update-monitor-data");
}
static PortalFlatpakUpdateMonitor *
create_update_monitor (GDBusMethodInvocation *invocation,
const char *obj_path,
GError **error)
{
PortalFlatpakUpdateMonitor *monitor;
UpdateMonitorData *m;
g_autoptr(GKeyFile) app_info = NULL;
g_autofree char *name = NULL;
app_info = flatpak_invocation_lookup_app_info (invocation, NULL, error);
if (app_info == NULL)
return NULL;
name = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
"name", NULL);
if (name == NULL || *name == 0)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
"Updates only supported by flatpak apps");
return NULL;
}
m = g_new0 (UpdateMonitorData, 1);
g_mutex_init (&m->lock);
m->obj_path = g_strdup (obj_path);
m->sender = g_strdup (g_dbus_method_invocation_get_sender (invocation));
m->cancellable = g_cancellable_new ();
m->name = g_steal_pointer (&name);
m->arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"arch", NULL);
m->branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"branch", NULL);
m->commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-commit", NULL);
m->app_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-path", NULL);
m->reported_local_commit = g_strdup (m->commit);
m->reported_remote_commit = g_strdup (m->commit);
monitor = portal_flatpak_update_monitor_skeleton_new ();
g_object_set_data_full (G_OBJECT (monitor), "update-monitor-data", m, update_monitor_data_free);
g_object_set_data_full (G_OBJECT (monitor), "required-sender", g_strdup (m->sender), g_free);
g_debug ("created UpdateMonitor for %s/%s at %s", m->name, m->branch, obj_path);
return monitor;
}
static void
update_monitor_do_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_dbus_interface_skeleton_unexport (G_DBUS_INTERFACE_SKELETON (monitor));
unregister_update_monitor (m->obj_path);
}
/* Always called in worker thread */
static void
update_monitor_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean do_close;
g_mutex_lock (&m->lock);
/* Close at most once, but not if running, if running it will be closed when that is done */
do_close = !m->closed && !m->running;
m->closed = TRUE;
g_mutex_unlock (&m->lock);
/* Always cancel though, so we can exit any running code early */
g_cancellable_cancel (m->cancellable);
if (do_close)
update_monitor_do_close (monitor);
}
static GDBusConnection *
update_monitor_get_connection (PortalFlatpakUpdateMonitor *monitor)
{
return g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (monitor));
}
static GHashTable *installation_cache = NULL;
static void
clear_installation_cache (void)
{
if (installation_cache != NULL)
g_hash_table_remove_all (installation_cache);
}
/* Caching lookup of Installation for a path */
static FlatpakInstallation *
lookup_installation_for_path (GFile *path, GError **error)
{
FlatpakInstallation *installation;
if (installation_cache == NULL)
installation_cache = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal, g_object_unref, g_object_unref);
installation = g_hash_table_lookup (installation_cache, path);
if (installation == NULL)
{
g_autoptr(FlatpakDir) dir = NULL;
dir = flatpak_dir_get_by_path (path);
installation = flatpak_installation_new_for_dir (dir, NULL, error);
if (installation == NULL)
return NULL;
flatpak_installation_set_no_interaction (installation, TRUE);
g_hash_table_insert (installation_cache, g_object_ref (path), installation);
}
return g_object_ref (installation);
}
static GFile *
update_monitor_get_installation_path (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) app_path = NULL;
app_path = g_file_new_for_path (m->app_path);
/* The app path is always 6 level deep inside the installation dir,
* like $dir/app/org.the.app/x86_64/stable/$commit/files, so we find
* the installation by just going up 6 parents. */
return g_file_resolve_relative_path (app_path, "../../../../../..");
}
static void
check_for_updates (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) installation_path = NULL;
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakInstalledRef) installed_ref = NULL;
g_autoptr(FlatpakRemoteRef) remote_ref = NULL;
const char *origin = NULL;
const char *local_commit = NULL;
const char *remote_commit;
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
const char *ref;
installation_path = update_monitor_get_installation_path (monitor);
g_debug ("Checking for updates for %s/%s/%s in %s", m->name, m->arch, m->branch, flatpak_file_get_path_cached (installation_path));
installation = lookup_installation_for_path (installation_path, &error);
if (installation == NULL)
{
g_debug ("Unable to find installation for path %s: %s", flatpak_file_get_path_cached (installation_path), error->message);
return;
}
installed_ref = flatpak_installation_get_installed_ref (installation,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (installed_ref == NULL)
{
g_debug ("getting installed ref failed: %s", error->message);
return; /* Never report updates for uninstalled refs */
}
dir = flatpak_installation_get_dir (installation, NULL);
if (dir == NULL)
return;
ref = flatpak_ref_format_ref_cached (FLATPAK_REF (installed_ref));
if (flatpak_dir_ref_is_masked (dir, ref))
return; /* Never report updates for masked refs */
local_commit = flatpak_ref_get_commit (FLATPAK_REF (installed_ref));
origin = flatpak_installed_ref_get_origin (installed_ref);
remote_ref = flatpak_installation_fetch_remote_ref_sync (installation, origin,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (remote_ref == NULL)
{
/* Probably some network issue.
* Fall back to the local_commit to at least be able to pick up already installed updates.
*/
g_debug ("getting remote ref failed: %s", error->message);
g_clear_error (&error);
remote_commit = local_commit;
}
else
{
remote_commit = flatpak_ref_get_commit (FLATPAK_REF (remote_ref));
if (remote_commit == NULL)
{
/* This can happen if we're offline and there is an update from an usb drive.
* Not much we can do in terms of reporting it, but at least handle the case
*/
g_debug ("Unknown remote commit, setting to local_commit");
remote_commit = local_commit;
}
}
if (g_strcmp0 (m->reported_local_commit, local_commit) != 0 ||
g_strcmp0 (m->reported_remote_commit, remote_commit) != 0)
{
GVariantBuilder builder;
gboolean is_closed;
g_free (m->reported_local_commit);
m->reported_local_commit = g_strdup (local_commit);
g_free (m->reported_remote_commit);
m->reported_remote_commit = g_strdup (remote_commit);
g_debug ("Found update for %s/%s/%s, local: %s, remote: %s", m->name, m->arch, m->branch, local_commit, remote_commit);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&builder, "{sv}", "running-commit", g_variant_new_string (m->commit));
g_variant_builder_add (&builder, "{sv}", "local-commit", g_variant_new_string (local_commit));
g_variant_builder_add (&builder, "{sv}", "remote-commit", g_variant_new_string (remote_commit));
/* Maybe someone closed the monitor while we were checking for updates, then drop the signal.
* There is still a minimal race between this check and the emit where a client could call close()
* and still see the signal though. */
g_mutex_lock (&m->lock);
is_closed = m->closed;
g_mutex_unlock (&m->lock);
if (!is_closed &&
!g_dbus_connection_emit_signal (update_monitor_get_connection (monitor),
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"UpdateAvailable",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit UpdateAvailable: %s", error->message);
g_clear_error (&error);
}
}
}
static void
check_all_for_updates_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *monitors, *l;
monitors = update_monitors_get_all (NULL);
for (l = monitors; l != NULL; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean was_closed = FALSE;
g_mutex_lock (&m->lock);
if (m->closed)
was_closed = TRUE;
else
m->running = TRUE;
g_mutex_unlock (&m->lock);
if (!was_closed)
{
check_for_updates (monitor);
g_mutex_lock (&m->lock);
m->running = FALSE;
if (m->closed) /* Was closed during running, do delayed close */
update_monitor_do_close (monitor);
g_mutex_unlock (&m->lock);
}
}
g_list_free_full (monitors, g_object_unref);
/* We want to cache stuff between multiple monitors
when a poll is scheduled, but there is no need to keep it
long term to the next poll, the in-memory is just
a waste of space then. */
clear_installation_cache ();
G_LOCK (update_monitors);
update_monitors_timeout_running_thread = FALSE;
if (g_hash_table_size (update_monitors) > 0)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
/* Runs on main thread */
static gboolean
check_all_for_updates_cb (void *data)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
if (!opt_poll_when_metered &&
g_network_monitor_get_network_metered (network_monitor))
{
g_debug ("Skipping update check on metered network");
return G_SOURCE_CONTINUE;
}
g_debug ("Checking all update monitors");
G_LOCK (update_monitors);
update_monitors_timeout = 0;
update_monitors_timeout_running_thread = TRUE;
G_UNLOCK (update_monitors);
g_task_run_in_thread (task, check_all_for_updates_in_thread_func);
return G_SOURCE_REMOVE; /* This will be re-added by the thread when done */
}
/* Runs in worker thread */
static gboolean
handle_create_update_monitor (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GVariant *options)
{
GDBusConnection *connection = g_dbus_method_invocation_get_connection (invocation);
g_autoptr(PortalFlatpakUpdateMonitorSkeleton) monitor = NULL;
const char *sender;
g_autofree char *sender_escaped = NULL;
g_autofree char *obj_path = NULL;
g_autofree char *token = NULL;
g_autoptr(GError) error = NULL;
int i;
if (!g_variant_lookup (options, "handle_token", "s", &token))
token = g_strdup_printf ("%d", g_random_int_range (0, 1000));
sender = g_dbus_method_invocation_get_sender (invocation);
g_debug ("handle CreateUpdateMonitor from %s", sender);
sender_escaped = g_strdup (sender + 1);
for (i = 0; sender_escaped[i]; i++)
{
if (sender_escaped[i] == '.')
sender_escaped[i] = '_';
}
obj_path = g_strdup_printf ("/org/freedesktop/portal/Flatpak/update_monitor/%s/%s",
sender_escaped,
token);
monitor = (PortalFlatpakUpdateMonitorSkeleton *) create_update_monitor (invocation, obj_path, &error);
if (monitor == NULL)
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_signal_connect (monitor, "handle-close", G_CALLBACK (handle_close), NULL);
g_signal_connect (monitor, "handle-update", G_CALLBACK (handle_update), NULL);
g_signal_connect (monitor, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (monitor),
connection,
obj_path,
&error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
register_update_monitor ((PortalFlatpakUpdateMonitor*)monitor, obj_path);
portal_flatpak_complete_create_update_monitor (portal, invocation, obj_path);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
/* Runs in worker thread */
static gboolean
handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation)
{
update_monitor_close (monitor);
g_debug ("handle UpdateMonitor.Close");
portal_flatpak_update_monitor_complete_close (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
deep_free_object_list (gpointer data)
{
g_list_free_full ((GList *)data, g_object_unref);
}
static void
close_update_monitors_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *list = task_data;
GList *l;
for (l = list; l; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_debug ("closing monitor %s", m->obj_path);
update_monitor_close (monitor);
}
}
static void
close_update_monitors_for_sender (const char *sender)
{
GList *list = update_monitors_get_all (sender);
if (list)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
g_task_set_task_data (task, list, deep_free_object_list);
g_debug ("%s dropped off the bus, closing monitors", sender);
g_task_run_in_thread (task, close_update_monitors_in_thread_func);
}
}
static guint32
get_update_permission (const char *app_id)
{
g_autoptr(GVariant) out_perms = NULL;
g_autoptr(GVariant) out_data = NULL;
g_autoptr(GError) error = NULL;
guint32 ret = UNSET;
if (permission_store == NULL)
{
g_debug ("No portals installed, assume no permissions");
return NO;
}
if (!xdp_dbus_permission_store_call_lookup_sync (permission_store,
PERMISSION_TABLE,
PERMISSION_ID,
&out_perms,
&out_data,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_debug ("No updates permissions found: %s", error->message);
g_clear_error (&error);
}
if (out_perms != NULL)
{
const char **perms;
if (g_variant_lookup (out_perms, app_id, "^a&s", &perms))
{
if (strcmp (perms[0], "ask") == 0)
ret = ASK;
else if (strcmp (perms[0], "yes") == 0)
ret = YES;
else
ret = NO;
}
}
g_debug ("Updates permissions for %s: %d", app_id, ret);
return ret;
}
static void
set_update_permission (const char *app_id,
Permission permission)
{
g_autoptr(GError) error = NULL;
const char *permissions[2];
if (permission == ASK)
permissions[0] = "ask";
else if (permission == YES)
permissions[0] = "yes";
else if (permission == NO)
permissions[0] = "no";
else
{
g_warning ("Wrong permission format, ignoring");
return;
}
permissions[1] = NULL;
if (!xdp_dbus_permission_store_call_set_permission_sync (permission_store,
PERMISSION_TABLE,
TRUE,
PERMISSION_ID,
app_id,
(const char * const*)permissions,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_info ("Error updating permission store: %s", error->message);
}
}
static char *
get_app_display_name (const char *app_id)
{
g_autofree char *id = NULL;
g_autoptr(GDesktopAppInfo) info = NULL;
const char *name = NULL;
id = g_strconcat (app_id, ".desktop", NULL);
info = g_desktop_app_info_new (id);
if (info)
{
name = g_app_info_get_display_name (G_APP_INFO (info));
if (name)
return g_strdup (name);
}
return g_strdup (app_id);
}
static gboolean
request_update_permissions_sync (PortalFlatpakUpdateMonitor *monitor,
const char *app_id,
const char *window,
GError **error)
{
Permission permission;
permission = get_update_permission (app_id);
if (permission == UNSET || permission == ASK)
{
guint access_response = 2;
PortalImplementation *access_impl;
GVariantBuilder access_opt_builder;
g_autofree char *app_name = NULL;
g_autofree char *title = NULL;
g_autoptr(GVariant) ret = NULL;
access_impl = find_portal_implementation ("org.freedesktop.impl.portal.Access");
if (access_impl == NULL)
{
g_warning ("No Access portal implementation found");
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED, _("No portal support found"));
return FALSE;
}
g_variant_builder_init (&access_opt_builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&access_opt_builder, "{sv}",
"deny_label", g_variant_new_string (_("Deny")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"grant_label", g_variant_new_string (_("Update")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"icon", g_variant_new_string ("package-x-generic-symbolic"));
app_name = get_app_display_name (app_id);
title = g_strdup_printf (_("Update %s?"), app_name);
ret = g_dbus_connection_call_sync (update_monitor_get_connection (monitor),
access_impl->dbus_name,
"/org/freedesktop/portal/desktop",
"org.freedesktop.impl.portal.Access",
"AccessDialog",
g_variant_new ("(osssssa{sv})",
"/request/path",
app_id,
window,
title,
_("The application wants to update itself."),
_("Update access can be changed any time from the privacy settings."),
&access_opt_builder),
G_VARIANT_TYPE ("(ua{sv})"),
G_DBUS_CALL_FLAGS_NONE,
G_MAXINT,
NULL,
error);
if (ret == NULL)
{
g_dbus_error_strip_remote_error (*error);
g_warning ("Failed to show access dialog: %s", (*error)->message);
return FALSE;
}
g_variant_get (ret, "(ua{sv})", &access_response, NULL);
if (permission == UNSET)
set_update_permission (app_id, (access_response == 0) ? YES : NO);
permission = (access_response == 0) ? YES : NO;
}
if (permission == NO)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
_("Application update not allowed"));
return FALSE;
}
return TRUE;
}
static void
emit_progress (PortalFlatpakUpdateMonitor *monitor,
int op,
int n_ops,
int progress,
int status,
const char *error_name,
const char *error_message)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
GDBusConnection *connection;
GVariantBuilder builder;
g_autoptr(GError) error = NULL;
g_debug ("%d/%d ops, progress %d, status: %d", op, n_ops, progress, status);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
if (n_ops > 0)
{
g_variant_builder_add (&builder, "{sv}", "op", g_variant_new_uint32 (op));
g_variant_builder_add (&builder, "{sv}", "n_ops", g_variant_new_uint32 (n_ops));
g_variant_builder_add (&builder, "{sv}", "progress", g_variant_new_uint32 (progress));
}
g_variant_builder_add (&builder, "{sv}", "status", g_variant_new_uint32 (status));
if (error_name)
{
g_variant_builder_add (&builder, "{sv}", "error", g_variant_new_string (error_name));
g_variant_builder_add (&builder, "{sv}", "error_message", g_variant_new_string (error_message));
}
connection = update_monitor_get_connection (monitor);
if (!g_dbus_connection_emit_signal (connection,
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"Progress",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit ::progress: %s", error->message);
}
}
static char *
get_progress_error (const GError *update_error)
{
g_autofree gchar *name = NULL;
name = g_dbus_error_encode_gerror (update_error);
/* Don't return weird dbus wrapped things from the portal */
if (g_str_has_prefix (name, "org.gtk.GDBus.UnmappedGError.Quark"))
return g_strdup ("org.freedesktop.DBus.Error.Failed");
return g_steal_pointer (&name);
}
static void
emit_progress_error (PortalFlatpakUpdateMonitor *monitor,
GError *update_error)
{
g_autofree gchar *error_name = get_progress_error (update_error);
emit_progress (monitor, 0, 0, 0,
PROGRESS_STATUS_ERROR,
error_name, update_error->message);
}
static void
send_variant (GVariant *v, GOutputStream *out)
{
g_autoptr(GError) error = NULL;
const guchar *data;
gsize size;
guint32 size32;
data = g_variant_get_data (v);
size = g_variant_get_size (v);
size32 = size;
if (!g_output_stream_write_all (out, &size32, 4, NULL, NULL, &error) ||
!g_output_stream_write_all (out, data, size, NULL, NULL, &error))
{
g_warning ("sending to parent failed: %s", error->message);
exit (1); // This will exit the child process and cause the parent to report an error
}
}
static void
send_progress (GOutputStream *out,
int op,
int n_ops,
int progress,
int status,
const GError *update_error)
{
g_autoptr(GVariant) v = NULL;
g_autofree gchar *error_name = NULL;
if (update_error)
error_name = get_progress_error (update_error);
v = g_variant_ref_sink (g_variant_new ("(uuuuss)",
op, n_ops, progress, status,
error_name ? error_name : "",
update_error ? update_error->message : ""));
send_variant (v, out);
}
typedef struct {
GOutputStream *out;
int n_ops;
int op;
int progress;
gboolean saw_first_operation;
} TransactionData;
static gboolean
transaction_ready (FlatpakTransaction *transaction,
TransactionData *d)
{
GList *ops = flatpak_transaction_get_operations (transaction);
int status;
GList *l;
d->n_ops = g_list_length (ops);
d->op = 0;
d->progress = 0;
for (l = ops; l != NULL; l = l->next)
{
FlatpakTransactionOperation *op = l->data;
const char *ref = flatpak_transaction_operation_get_ref (op);
FlatpakTransactionOperationType type = flatpak_transaction_operation_get_operation_type (op);
/* Actual app updates need to not increase premission requirements */
if (type == FLATPAK_TRANSACTION_OPERATION_UPDATE && g_str_has_prefix (ref, "app/"))
{
GKeyFile *new_metadata = flatpak_transaction_operation_get_metadata (op);
GKeyFile *old_metadata = flatpak_transaction_operation_get_old_metadata (op);
g_autoptr(FlatpakContext) new_context = flatpak_context_new ();
g_autoptr(FlatpakContext) old_context = flatpak_context_new ();
if (!flatpak_context_load_metadata (new_context, new_metadata, NULL) ||
!flatpak_context_load_metadata (old_context, old_metadata, NULL) ||
flatpak_context_adds_permissions (old_context, new_context))
{
g_autoptr(GError) error = NULL;
g_set_error (&error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
_("Self update not supported, new version requires new permissions"));
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE;
}
}
}
if (flatpak_transaction_is_empty (transaction))
status = PROGRESS_STATUS_EMPTY;
else
status = PROGRESS_STATUS_RUNNING;
send_progress (d->out,
d->op, d->n_ops,
d->progress, status,
NULL);
if (status == PROGRESS_STATUS_EMPTY)
return FALSE; /* This will cause us to return an ABORTED error */
return TRUE;
}
static void
transaction_progress_changed (FlatpakTransactionProgress *progress,
TransactionData *d)
{
/* Only report 100 when really done */
d->progress = MIN (flatpak_transaction_progress_get_progress (progress), 99);
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
transaction_new_operation (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
FlatpakTransactionProgress *progress,
TransactionData *d)
{
d->progress = 0;
if (d->saw_first_operation)
d->op++;
else
d->saw_first_operation = TRUE;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
g_signal_connect (progress, "changed", G_CALLBACK (transaction_progress_changed), d);
}
static gboolean
transaction_operation_error (FlatpakTransaction *transaction,
FlatpakTransactionOperation *operation,
const GError *error,
FlatpakTransactionErrorDetails detail,
TransactionData *d)
{
gboolean non_fatal = (detail & FLATPAK_TRANSACTION_ERROR_DETAILS_NON_FATAL) != 0;
if (non_fatal)
return TRUE; /* Continue */
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE; /* This will cause us to return an ABORTED error */
}
static void
transaction_operation_done (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
const char *commit,
FlatpakTransactionResult result,
TransactionData *d)
{
d->progress = 100;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
update_child_setup_func (gpointer user_data)
{
int *socket = user_data;
dup2 (*socket, 3);
flatpak_close_fds_workaround (4);
}
/* This is the meat of the update process, its run out of process (via
spawn) to avoid running lots of complicated code in the portal
process and possibly long-term leaks in a long-running process. */
static int
do_update_child_process (const char *installation_path, const char *ref, int socket_fd)
{
g_autoptr(GOutputStream) out = g_unix_output_stream_new (socket_fd, TRUE);
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakTransaction) transaction = NULL;
g_autoptr(GFile) f = g_file_new_for_path (installation_path);
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
TransactionData transaction_data = { NULL };
dir = flatpak_dir_get_by_path (f);
if (!flatpak_dir_maybe_ensure_repo (dir, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
installation = flatpak_installation_new_for_dir (dir, NULL, &error);
if (installation)
transaction = flatpak_transaction_new_for_installation (installation, NULL, &error);
if (transaction == NULL)
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
flatpak_transaction_add_default_dependency_sources (transaction);
if (!flatpak_transaction_add_update (transaction, ref, NULL, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
transaction_data.out = out;
g_signal_connect (transaction, "ready", G_CALLBACK (transaction_ready), &transaction_data);
g_signal_connect (transaction, "new-operation", G_CALLBACK (transaction_new_operation), &transaction_data);
g_signal_connect (transaction, "operation-done", G_CALLBACK (transaction_operation_done), &transaction_data);
g_signal_connect (transaction, "operation-error", G_CALLBACK (transaction_operation_error), &transaction_data);
if (!flatpak_transaction_run (transaction, NULL, &error))
{
if (!g_error_matches (error, FLATPAK_ERROR, FLATPAK_ERROR_ABORTED)) /* If aborted we already sent error */
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_ERROR, error);
return 0;
}
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_DONE, error);
return 0;
}
static GVariant *
read_variant (GInputStream *in,
GCancellable *cancellable,
GError **error)
{
guint32 size;
guchar *data;
gsize bytes_read;
if (!g_input_stream_read_all (in, &size, 4, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != 4)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
data = g_try_malloc (size);
if (data == NULL)
{
flatpak_fail (error, "Out of memory");
return NULL;
}
if (!g_input_stream_read_all (in, data, size, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != size)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
return g_variant_ref_sink (g_variant_new_from_data (G_VARIANT_TYPE("(uuuuss)"),
data, size, FALSE, g_free, data));
}
/* We do the actual update out of process (in do_update_child_process,
via spawn) and just proxy the feedback here */
static gboolean
handle_update_responses (PortalFlatpakUpdateMonitor *monitor,
int socket_fd,
GError **error)
{
g_autoptr(GInputStream) in = g_unix_input_stream_new (socket_fd, FALSE); /* Closed by parent */
UpdateMonitorData *m = update_monitor_get_data (monitor);
guint32 status;
do
{
g_autoptr(GVariant) v = NULL;
guint32 op;
guint32 n_ops;
guint32 progress;
const char *error_name;
const char *error_message;
v = read_variant (in, m->cancellable, error);
if (v == NULL)
{
g_debug ("Reading message from child update process failed %s", (*error)->message);
return FALSE;
}
g_variant_get (v, "(uuuu&s&s)",
&op, &n_ops, &progress, &status, &error_name, &error_message);
emit_progress (monitor, op, n_ops, progress, status,
*error_name != 0 ? error_name : NULL,
*error_message != 0 ? error_message : NULL);
}
while (status == PROGRESS_STATUS_RUNNING);
/* Don't return an received error as we emited it already, that would cause it to be emitted twice */
return TRUE;
}
static void
handle_update_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
PortalFlatpakUpdateMonitor *monitor = source_object;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GError) error = NULL;
const char *window;
window = (const char *)g_object_get_data (G_OBJECT (task), "window");
if (request_update_permissions_sync (monitor, m->name, window, &error))
{
g_autoptr(GFile) installation_path = update_monitor_get_installation_path (monitor);
g_autofree char *ref = flatpak_build_app_ref (m->name, m->branch, m->arch);
const char *argv[] = { "/proc/self/exe", "flatpak-portal", "--update", flatpak_file_get_path_cached (installation_path), ref, NULL };
int sockets[2];
GPid pid;
if (socketpair (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sockets) != 0)
{
glnx_throw_errno (&error);
}
else
{
gboolean spawn_ok;
spawn_ok = g_spawn_async (NULL, (char **)argv, NULL,
G_SPAWN_FILE_AND_ARGV_ZERO |
G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
update_child_setup_func, &sockets[1],
&pid, &error);
close (sockets[1]); // Close remote side
if (spawn_ok)
{
if (!handle_update_responses (monitor, sockets[0], &error))
{
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
kill (pid, SIGINT);
}
}
close (sockets[0]); // Close local side
}
}
if (error)
emit_progress_error (monitor, error);
g_mutex_lock (&m->lock);
m->installing = FALSE;
g_mutex_unlock (&m->lock);
}
static gboolean
handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GTask) task = NULL;
gboolean already_installing = FALSE;
g_debug ("handle UpdateMonitor.Update");
g_mutex_lock (&m->lock);
if (m->installing)
already_installing = TRUE;
else
m->installing = TRUE;
g_mutex_unlock (&m->lock);
if (already_installing)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR,
G_DBUS_ERROR_FAILED,
"Already installing");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
task = g_task_new (monitor, NULL, NULL, NULL);
g_object_set_data_full (G_OBJECT (task), "window", g_strdup (arg_window), g_free);
g_task_run_in_thread (task, handle_update_in_thread_func);
portal_flatpak_update_monitor_complete_update (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
name_owner_changed (GDBusConnection *connection,
const gchar *sender_name,
const gchar *object_path,
const gchar *interface_name,
const gchar *signal_name,
GVariant *parameters,
gpointer user_data)
{
const char *name, *from, *to;
g_variant_get (parameters, "(&s&s&s)", &name, &from, &to);
if (name[0] == ':' &&
strcmp (name, from) == 0 &&
strcmp (to, "") == 0)
{
GHashTableIter iter;
PidData *pid_data = NULL;
gpointer value = NULL;
GList *list = NULL, *l;
g_hash_table_iter_init (&iter, client_pid_data_hash);
while (g_hash_table_iter_next (&iter, NULL, &value))
{
pid_data = value;
if (pid_data->watch_bus && g_str_equal (pid_data->client, name))
list = g_list_prepend (list, pid_data);
}
for (l = list; l; l = l->next)
{
pid_data = l->data;
g_debug ("%s dropped off the bus, killing %d", pid_data->client, pid_data->pid);
killpg (pid_data->pid, SIGINT);
}
g_list_free (list);
close_update_monitors_for_sender (name);
}
}
#define DBUS_NAME_DBUS "org.freedesktop.DBus"
#define DBUS_INTERFACE_DBUS DBUS_NAME_DBUS
#define DBUS_PATH_DBUS "/org/freedesktop/DBus"
static gboolean
supports_expose_pids (void)
{
const char *path = g_find_program_in_path (flatpak_get_bwrap ());
struct stat st;
/* This is supported only if bwrap exists and is not setuid */
return
path != NULL &&
stat (path, &st) == 0 &&
(st.st_mode & S_ISUID) == 0;
}
static void
on_bus_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
GError *error = NULL;
g_debug ("Bus acquired, creating skeleton");
g_dbus_connection_set_exit_on_close (connection, FALSE);
update_monitors = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
permission_store = xdp_dbus_permission_store_proxy_new_sync (connection,
G_DBUS_PROXY_FLAGS_NONE,
"org.freedesktop.impl.portal.PermissionStore",
"/org/freedesktop/impl/portal/PermissionStore",
NULL, NULL);
portal = portal_flatpak_skeleton_new ();
g_dbus_connection_signal_subscribe (connection,
DBUS_NAME_DBUS,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged",
DBUS_PATH_DBUS,
NULL,
G_DBUS_SIGNAL_FLAGS_NONE,
name_owner_changed,
NULL, NULL);
g_object_set_data_full (G_OBJECT (portal), "track-alive", GINT_TO_POINTER (42), skeleton_died_cb);
g_dbus_interface_skeleton_set_flags (G_DBUS_INTERFACE_SKELETON (portal),
G_DBUS_INTERFACE_SKELETON_FLAGS_HANDLE_METHOD_INVOCATIONS_IN_THREAD);
portal_flatpak_set_version (PORTAL_FLATPAK (portal), 5);
portal_flatpak_set_supports (PORTAL_FLATPAK (portal), supports);
g_signal_connect (portal, "handle-spawn", G_CALLBACK (handle_spawn), NULL);
g_signal_connect (portal, "handle-spawn-signal", G_CALLBACK (handle_spawn_signal), NULL);
g_signal_connect (portal, "handle-create-update-monitor", G_CALLBACK (handle_create_update_monitor), NULL);
g_signal_connect (portal, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (portal),
connection,
"/org/freedesktop/portal/Flatpak",
&error))
{
g_warning ("error: %s", error->message);
g_error_free (error);
}
}
static void
on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name acquired");
}
static void
on_name_lost (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name lost");
unref_skeleton_in_timeout ();
}
static void
binary_file_changed_cb (GFileMonitor *file_monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
gpointer data)
{
static gboolean got_it = FALSE;
if (!got_it)
{
g_debug ("binary file changed");
unref_skeleton_in_timeout ();
}
got_it = TRUE;
}
static void
message_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data)
{
/* Make this look like normal console output */
if (log_level & G_LOG_LEVEL_DEBUG)
g_printerr ("F: %s\n", message);
else
g_printerr ("%s: %s\n", g_get_prgname (), message);
}
int
main (int argc,
char **argv)
{
gchar exe_path[PATH_MAX + 1];
ssize_t exe_path_len;
gboolean replace;
gboolean show_version;
GOptionContext *context;
GBusNameOwnerFlags flags;
g_autoptr(GError) error = NULL;
const GOptionEntry options[] = {
{ "replace", 'r', 0, G_OPTION_ARG_NONE, &replace, "Replace old daemon.", NULL },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &opt_verbose, "Enable debug output.", NULL },
{ "version", 0, 0, G_OPTION_ARG_NONE, &show_version, "Show program version.", NULL},
{ "no-idle-exit", 0, 0, G_OPTION_ARG_NONE, &no_idle_exit, "Don't exit when idle.", NULL },
{ "poll-timeout", 0, 0, G_OPTION_ARG_INT, &opt_poll_timeout, "Delay in seconds between polls for updates.", NULL },
{ "poll-when-metered", 0, 0, G_OPTION_ARG_NONE, &opt_poll_when_metered, "Whether to check for updates on metered networks", NULL },
{ NULL }
};
setlocale (LC_ALL, "");
g_setenv ("GIO_USE_VFS", "local", TRUE);
g_set_prgname (argv[0]);
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, message_handler, NULL);
if (argc >= 4 && strcmp (argv[1], "--update") == 0)
{
return do_update_child_process (argv[2], argv[3], 3);
}
context = g_option_context_new ("");
replace = FALSE;
opt_verbose = FALSE;
show_version = FALSE;
g_option_context_set_summary (context, "Flatpak portal");
g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
if (!g_option_context_parse (context, &argc, &argv, &error))
{
g_printerr ("%s: %s", g_get_application_name (), error->message);
g_printerr ("\n");
g_printerr ("Try \"%s --help\" for more information.",
g_get_prgname ());
g_printerr ("\n");
g_option_context_free (context);
return 1;
}
if (opt_poll_timeout == 0)
opt_poll_timeout = DEFAULT_UPDATE_POLL_TIMEOUT_SEC;
if (show_version)
{
g_print (PACKAGE_STRING "\n");
return 0;
}
if (opt_verbose)
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, message_handler, NULL);
client_pid_data_hash = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) pid_data_free);
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
if (session_bus == NULL)
{
g_printerr ("Can't find bus: %s\n", error->message);
return 1;
}
exe_path_len = readlink ("/proc/self/exe", exe_path, sizeof (exe_path) - 1);
if (exe_path_len > 0 && (size_t) exe_path_len < sizeof (exe_path))
{
exe_path[exe_path_len] = 0;
GFileMonitor *monitor;
g_autoptr(GFile) exe = NULL;
g_autoptr(GError) local_error = NULL;
exe = g_file_new_for_path (exe_path);
monitor = g_file_monitor_file (exe,
G_FILE_MONITOR_NONE,
NULL,
&local_error);
if (monitor == NULL)
g_warning ("Failed to set watch on %s: %s", exe_path, error->message);
else
g_signal_connect (monitor, "changed",
G_CALLBACK (binary_file_changed_cb), NULL);
}
flatpak_connection_track_name_owners (session_bus);
if (supports_expose_pids ())
supports |= FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS;
flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
if (replace)
flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
"org.freedesktop.portal.Flatpak",
flags,
on_bus_acquired,
on_name_acquired,
on_name_lost,
NULL,
NULL);
load_installed_portals (opt_verbose);
/* Ensure we don't idle exit */
schedule_idle_callback ();
network_monitor = g_network_monitor_get_default ();
main_loop = g_main_loop_new (NULL, FALSE);
g_main_loop_run (main_loop);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1909_0 |
crossvul-cpp_data_good_4069_2 | /**
* @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 (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "private.h"
#include "mutt/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "globals.h"
#include "init.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_logging.h"
#include "mutt_menu.h"
#include "mutt_socket.h"
#include "mx.h"
/* These Config Variables are only used in imap/command.c */
bool C_ImapServernoise; ///< Config: (imap) Display server warnings as error messages
#define IMAP_CMD_BUFSIZE 512
/**
* Capabilities - Server capabilities strings that we understand
*
* @note This must be kept in the same order as ImapCaps.
*/
static const char *const Capabilities[] = {
"IMAP4",
"IMAP4rev1",
"STATUS",
"ACL",
"NAMESPACE",
"AUTH=CRAM-MD5",
"AUTH=GSSAPI",
"AUTH=ANONYMOUS",
"AUTH=OAUTHBEARER",
"STARTTLS",
"LOGINDISABLED",
"IDLE",
"SASL-IR",
"ENABLE",
"CONDSTORE",
"QRESYNC",
"LIST-EXTENDED",
"COMPRESS=DEFLATE",
"X-GM-EXT-1",
NULL,
};
/**
* cmd_queue_full - Is the IMAP command queue full?
* @param adata Imap Account data
* @retval true Queue is full
*/
static bool cmd_queue_full(struct ImapAccountData *adata)
{
if (((adata->nextcmd + 1) % adata->cmdslots) == adata->lastcmd)
return true;
return false;
}
/**
* cmd_new - Create and queue a new command control block
* @param adata Imap Account data
* @retval NULL if the pipeline is full
* @retval ptr New command
*/
static struct ImapCommand *cmd_new(struct ImapAccountData *adata)
{
struct ImapCommand *cmd = NULL;
if (cmd_queue_full(adata))
{
mutt_debug(LL_DEBUG3, "IMAP command queue full\n");
return NULL;
}
cmd = adata->cmds + adata->nextcmd;
adata->nextcmd = (adata->nextcmd + 1) % adata->cmdslots;
snprintf(cmd->seq, sizeof(cmd->seq), "%c%04u", adata->seqid, adata->seqno++);
if (adata->seqno > 9999)
adata->seqno = 0;
cmd->state = IMAP_RES_NEW;
return cmd;
}
/**
* cmd_queue - Add a IMAP command to the queue
* @param adata Imap Account data
* @param cmdstr Command string
* @param flags Server flags, see #ImapCmdFlags
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*
* If the queue is full, attempts to drain it.
*/
static int cmd_queue(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)
{
if (cmd_queue_full(adata))
{
mutt_debug(LL_DEBUG3, "Draining IMAP command pipeline\n");
const int rc = imap_exec(adata, NULL, flags & IMAP_CMD_POLL);
if (rc == IMAP_EXEC_ERROR)
return IMAP_RES_BAD;
}
struct ImapCommand *cmd = cmd_new(adata);
if (!cmd)
return IMAP_RES_BAD;
if (mutt_buffer_add_printf(&adata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0)
return IMAP_RES_BAD;
return 0;
}
/**
* cmd_handle_fatal - When ImapAccountData is in fatal state, do what we can
* @param adata Imap Account data
*/
static void cmd_handle_fatal(struct ImapAccountData *adata)
{
adata->status = IMAP_FATAL;
if (!adata->mailbox)
return;
struct ImapMboxData *mdata = adata->mailbox->mdata;
if ((adata->state >= IMAP_SELECTED) && (mdata->reopen & IMAP_REOPEN_ALLOW))
{
mx_fastclose_mailbox(adata->mailbox);
mutt_socket_close(adata->conn);
mutt_error(_("Mailbox %s@%s closed"), adata->conn->account.user,
adata->conn->account.host);
adata->state = IMAP_DISCONNECTED;
}
imap_close_connection(adata);
if (!adata->recovering)
{
adata->recovering = true;
if (imap_login(adata))
mutt_clear_error();
adata->recovering = false;
}
}
/**
* cmd_start - Start a new IMAP command
* @param adata Imap Account data
* @param cmdstr Command string
* @param flags Command flags, see #ImapCmdFlags
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*/
static int cmd_start(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)
{
int rc;
if (adata->status == IMAP_FATAL)
{
cmd_handle_fatal(adata);
return -1;
}
if (cmdstr && ((rc = cmd_queue(adata, cmdstr, flags)) < 0))
return rc;
if (flags & IMAP_CMD_QUEUE)
return 0;
if (mutt_buffer_is_empty(&adata->cmdbuf))
return IMAP_RES_BAD;
rc = mutt_socket_send_d(adata->conn, adata->cmdbuf.data,
(flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD);
mutt_buffer_reset(&adata->cmdbuf);
/* unidle when command queue is flushed */
if (adata->state == IMAP_IDLE)
adata->state = IMAP_SELECTED;
return (rc < 0) ? IMAP_RES_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_RES_BAD
*/
static int cmd_status(const char *s)
{
s = imap_next_word((char *) s);
if (mutt_str_startswith(s, "OK", CASE_IGNORE))
return IMAP_RES_OK;
if (mutt_str_startswith(s, "NO", CASE_IGNORE))
return IMAP_RES_NO;
return IMAP_RES_BAD;
}
/**
* cmd_parse_expunge - Parse expunge command
* @param adata Imap Account data
* @param s String containing MSN of message to expunge
*
* cmd_parse_expunge: mark headers with new sequence ID and mark adata to be
* reopened at our earliest convenience
*/
static void cmd_parse_expunge(struct ImapAccountData *adata, const char *s)
{
unsigned int exp_msn;
struct Email *e = NULL;
mutt_debug(LL_DEBUG2, "Handling EXPUNGE\n");
struct ImapMboxData *mdata = adata->mailbox->mdata;
if ((mutt_str_atoui(s, &exp_msn) < 0) || (exp_msn < 1) || (exp_msn > mdata->max_msn))
return;
e = mdata->msn_index[exp_msn - 1];
if (e)
{
/* imap_expunge_mailbox() will rewrite e->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
e->index = INT_MAX;
imap_edata_get(e)->msn = 0;
}
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < mdata->max_msn; cur++)
{
e = mdata->msn_index[cur];
if (e)
imap_edata_get(e)->msn--;
mdata->msn_index[cur - 1] = e;
}
mdata->msn_index[mdata->max_msn - 1] = NULL;
mdata->max_msn--;
mdata->reopen |= IMAP_EXPUNGE_PENDING;
}
/**
* cmd_parse_vanished - Parse vanished command
* @param adata Imap Account data
* @param s String containing MSN of message to expunge
*
* Handle VANISHED (RFC7162), which is like expunge, but passes a seqset of UIDs.
* An optional (EARLIER) argument specifies not to decrement subsequent MSNs.
*/
static void cmd_parse_vanished(struct ImapAccountData *adata, char *s)
{
bool earlier = false;
int rc;
unsigned int uid = 0;
struct ImapMboxData *mdata = adata->mailbox->mdata;
mutt_debug(LL_DEBUG2, "Handling VANISHED\n");
if (mutt_str_startswith(s, "(EARLIER)", CASE_IGNORE))
{
/* The RFC says we should not decrement msns with the VANISHED EARLIER tag.
* My experimentation says that's crap. */
earlier = true;
s = imap_next_word(s);
}
char *end_of_seqset = s;
while (*end_of_seqset)
{
if (!strchr("0123456789:,", *end_of_seqset))
*end_of_seqset = '\0';
else
end_of_seqset++;
}
struct SeqsetIterator *iter = mutt_seqset_iterator_new(s);
if (!iter)
{
mutt_debug(LL_DEBUG2, "VANISHED: empty seqset [%s]?\n", s);
return;
}
while ((rc = mutt_seqset_iterator_next(iter, &uid)) == 0)
{
struct Email *e = mutt_hash_int_find(mdata->uid_hash, uid);
if (!e)
continue;
unsigned int exp_msn = imap_edata_get(e)->msn;
/* imap_expunge_mailbox() will rewrite e->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
e->index = INT_MAX;
imap_edata_get(e)->msn = 0;
if ((exp_msn < 1) || (exp_msn > mdata->max_msn))
{
mutt_debug(LL_DEBUG1, "VANISHED: msn for UID %u is incorrect\n", uid);
continue;
}
if (mdata->msn_index[exp_msn - 1] != e)
{
mutt_debug(LL_DEBUG1, "VANISHED: msn_index for UID %u is incorrect\n", uid);
continue;
}
mdata->msn_index[exp_msn - 1] = NULL;
if (!earlier)
{
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < mdata->max_msn; cur++)
{
e = mdata->msn_index[cur];
if (e)
imap_edata_get(e)->msn--;
mdata->msn_index[cur - 1] = e;
}
mdata->msn_index[mdata->max_msn - 1] = NULL;
mdata->max_msn--;
}
}
if (rc < 0)
mutt_debug(LL_DEBUG1, "VANISHED: illegal seqset %s\n", s);
mdata->reopen |= IMAP_EXPUNGE_PENDING;
mutt_seqset_iterator_free(&iter);
}
/**
* cmd_parse_fetch - Load fetch response into ImapAccountData
* @param adata Imap Account 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 ImapAccountData *adata, char *s)
{
unsigned int msn, uid;
struct Email *e = NULL;
char *flags = NULL;
int uid_checked = 0;
bool server_changes = false;
struct ImapMboxData *mdata = imap_mdata_get(adata->mailbox);
mutt_debug(LL_DEBUG3, "Handling FETCH\n");
if (mutt_str_atoui(s, &msn) < 0)
{
mutt_debug(LL_DEBUG3, "Skipping FETCH response - illegal MSN\n");
return;
}
if ((msn < 1) || (msn > mdata->max_msn))
{
mutt_debug(LL_DEBUG3, "Skipping FETCH response - MSN %u out of range\n", msn);
return;
}
e = mdata->msn_index[msn - 1];
if (!e || !e->active)
{
mutt_debug(LL_DEBUG3, "Skipping FETCH response - MSN %u not in msn_index\n", msn);
return;
}
mutt_debug(LL_DEBUG2, "Message UID %u updated\n", imap_edata_get(e)->uid);
/* skip FETCH */
s = imap_next_word(s);
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "Malformed FETCH response\n");
return;
}
s++;
while (*s)
{
SKIPWS(s);
size_t plen = mutt_str_startswith(s, "FLAGS", CASE_IGNORE);
if (plen != 0)
{
flags = s;
if (uid_checked)
break;
s += plen;
SKIPWS(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "bogus FLAGS response: %s\n", s);
return;
}
s++;
while (*s && (*s != ')'))
s++;
if (*s == ')')
s++;
else
{
mutt_debug(LL_DEBUG1, "Unterminated FLAGS response: %s\n", s);
return;
}
}
else if ((plen = mutt_str_startswith(s, "UID", CASE_IGNORE)))
{
s += plen;
SKIPWS(s);
if (mutt_str_atoui(s, &uid) < 0)
{
mutt_debug(LL_DEBUG1, "Illegal UID. Skipping update\n");
return;
}
if (uid != imap_edata_get(e)->uid)
{
mutt_debug(LL_DEBUG1, "UID vs MSN mismatch. Skipping update\n");
return;
}
uid_checked = 1;
if (flags)
break;
s = imap_next_word(s);
}
else if ((plen = mutt_str_startswith(s, "MODSEQ", CASE_IGNORE)))
{
s += plen;
SKIPWS(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "bogus MODSEQ response: %s\n", s);
return;
}
s++;
while (*s && (*s != ')'))
s++;
if (*s == ')')
s++;
else
{
mutt_debug(LL_DEBUG1, "Unterminated MODSEQ response: %s\n", s);
return;
}
}
else if (*s == ')')
break; /* end of request */
else if (*s)
{
mutt_debug(LL_DEBUG2, "Only handle FLAGS updates\n");
break;
}
}
if (flags)
{
imap_set_flags(adata->mailbox, e, flags, &server_changes);
if (server_changes)
{
/* If server flags could conflict with NeoMutt's flags, reopen the mailbox. */
if (e->changed)
mdata->reopen |= IMAP_EXPUNGE_PENDING;
else
mdata->check_status |= IMAP_FLAGS_PENDING;
}
}
}
/**
* cmd_parse_capability - set capability bits according to CAPABILITY response
* @param adata Imap Account data
* @param s Command string with capabilities
*/
static void cmd_parse_capability(struct ImapAccountData *adata, char *s)
{
mutt_debug(LL_DEBUG3, "Handling CAPABILITY\n");
s = imap_next_word(s);
char *bracket = strchr(s, ']');
if (bracket)
*bracket = '\0';
FREE(&adata->capstr);
adata->capstr = mutt_str_strdup(s);
adata->capabilities = 0;
while (*s)
{
for (size_t i = 0; Capabilities[i]; i++)
{
if (mutt_str_word_casecmp(Capabilities[i], s) == 0)
{
adata->capabilities |= (1 << i);
mutt_debug(LL_DEBUG3, " Found capability \"%s\": %lu\n", Capabilities[i], i);
break;
}
}
s = imap_next_word(s);
}
}
/**
* cmd_parse_list - Parse a server LIST command (list mailboxes)
* @param adata Imap Account data
* @param s Command string with folder list
*/
static void cmd_parse_list(struct ImapAccountData *adata, char *s)
{
struct ImapList *list = NULL;
struct ImapList lb = { 0 };
char delimbuf[5]; /* worst case: "\\"\0 */
unsigned int litlen;
if (adata->cmdresult)
list = adata->cmdresult;
else
list = &lb;
memset(list, 0, sizeof(struct ImapList));
/* flags */
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "Bad LIST response\n");
return;
}
s++;
while (*s)
{
if (mutt_str_startswith(s, "\\NoSelect", CASE_IGNORE))
list->noselect = true;
else if (mutt_str_startswith(s, "\\NonExistent", CASE_IGNORE)) /* rfc5258 */
list->noselect = true;
else if (mutt_str_startswith(s, "\\NoInferiors", CASE_IGNORE))
list->noinferiors = true;
else if (mutt_str_startswith(s, "\\HasNoChildren", CASE_IGNORE)) /* rfc5258*/
list->noinferiors = true;
s = imap_next_word(s);
if (*(s - 2) == ')')
break;
}
/* Delimiter */
if (!mutt_str_startswith(s, "NIL", CASE_IGNORE))
{
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(adata) != IMAP_RES_CONTINUE)
{
adata->status = IMAP_FATAL;
return;
}
if (strlen(adata->buf) < litlen)
{
mutt_debug(LL_DEBUG1, "Error parsing LIST mailbox\n");
return;
}
list->name = adata->buf;
s = list->name + litlen;
if (s[0] != '\0')
{
s[0] = '\0';
s++;
SKIPWS(s);
}
}
else
{
list->name = s;
/* Exclude rfc5258 RECURSIVEMATCH CHILDINFO suffix */
s = imap_next_word(s);
if (s[0] != '\0')
s[-1] = '\0';
imap_unmunge_mbox_name(adata->unicode, list->name);
}
if (list->name[0] == '\0')
{
adata->delim = list->delim;
mutt_debug(LL_DEBUG3, "Root delimiter: %c\n", adata->delim);
}
}
/**
* cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes)
* @param adata Imap Account data
* @param s Command string with folder list
*/
static void cmd_parse_lsub(struct ImapAccountData *adata, char *s)
{
char buf[256];
char quoted_name[256];
struct Buffer err;
struct Url url = { 0 };
struct ImapList list = { 0 };
if (adata->cmdresult)
{
/* caller will handle response itself */
cmd_parse_list(adata, s);
return;
}
if (!C_ImapCheckSubscribed)
return;
adata->cmdresult = &list;
cmd_parse_list(adata, s);
adata->cmdresult = NULL;
/* noselect is for a gmail quirk */
if (!list.name || list.noselect)
return;
mutt_debug(LL_DEBUG3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&adata->conn->account, &url);
/* escape \ and " */
imap_quote_string(quoted_name, sizeof(quoted_name), list.name, true);
url.path = quoted_name + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, C_ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&err);
err.dsize = 256;
err.data = mutt_mem_malloc(err.dsize);
if (mutt_parse_rc_line(buf, &err))
mutt_debug(LL_DEBUG1, "Error adding subscribed mailbox: %s\n", err.data);
FREE(&err.data);
}
/**
* cmd_parse_myrights - Set rights bits according to MYRIGHTS response
* @param adata Imap Account data
* @param s Command string with rights info
*/
static void cmd_parse_myrights(struct ImapAccountData *adata, const char *s)
{
mutt_debug(LL_DEBUG2, "Handling MYRIGHTS\n");
s = imap_next_word((char *) s);
s = imap_next_word((char *) s);
/* zero out current rights set */
adata->mailbox->rights = 0;
while (*s && !isspace((unsigned char) *s))
{
switch (*s)
{
case 'a':
adata->mailbox->rights |= MUTT_ACL_ADMIN;
break;
case 'e':
adata->mailbox->rights |= MUTT_ACL_EXPUNGE;
break;
case 'i':
adata->mailbox->rights |= MUTT_ACL_INSERT;
break;
case 'k':
adata->mailbox->rights |= MUTT_ACL_CREATE;
break;
case 'l':
adata->mailbox->rights |= MUTT_ACL_LOOKUP;
break;
case 'p':
adata->mailbox->rights |= MUTT_ACL_POST;
break;
case 'r':
adata->mailbox->rights |= MUTT_ACL_READ;
break;
case 's':
adata->mailbox->rights |= MUTT_ACL_SEEN;
break;
case 't':
adata->mailbox->rights |= MUTT_ACL_DELETE;
break;
case 'w':
adata->mailbox->rights |= MUTT_ACL_WRITE;
break;
case 'x':
adata->mailbox->rights |= MUTT_ACL_DELMX;
break;
/* obsolete rights */
case 'c':
adata->mailbox->rights |= MUTT_ACL_CREATE | MUTT_ACL_DELMX;
break;
case 'd':
adata->mailbox->rights |= MUTT_ACL_DELETE | MUTT_ACL_EXPUNGE;
break;
default:
mutt_debug(LL_DEBUG1, "Unknown right: %c\n", *s);
}
s++;
}
}
/**
* find_mailbox - Find a Mailbox by its name
* @param adata Imap Account data
* @param name Mailbox to find
* @retval ptr Mailbox
*/
static struct Mailbox *find_mailbox(struct ImapAccountData *adata, const char *name)
{
if (!adata || !adata->account || !name)
return NULL;
struct MailboxNode *np = NULL;
STAILQ_FOREACH(np, &adata->account->mailboxes, entries)
{
struct ImapMboxData *mdata = imap_mdata_get(np->mailbox);
if (mutt_str_strcmp(name, mdata->name) == 0)
return np->mailbox;
}
return NULL;
}
/**
* cmd_parse_status - Parse status from server
* @param adata Imap Account data
* @param s Command string with status info
*
* first cut: just do mailbox update. Later we may wish to cache all mailbox
* information, even that not desired by mailbox
*/
static void cmd_parse_status(struct ImapAccountData *adata, char *s)
{
unsigned int litlen = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(adata) != IMAP_RES_CONTINUE)
{
adata->status = IMAP_FATAL;
return;
}
if (strlen(adata->buf) < litlen)
{
mutt_debug(LL_DEBUG1, "Error parsing STATUS mailbox\n");
return;
}
mailbox = adata->buf;
s = mailbox + litlen;
s[0] = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
s[-1] = '\0';
imap_unmunge_mbox_name(adata->unicode, mailbox);
}
struct Mailbox *m = find_mailbox(adata, mailbox);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!mdata)
{
mutt_debug(LL_DEBUG3, "Received status for an unexpected mailbox: %s\n", mailbox);
return;
}
uint32_t olduv = mdata->uidvalidity;
unsigned int oldun = mdata->uid_next;
if (*s++ != '(')
{
mutt_debug(LL_DEBUG1, "Error parsing STATUS\n");
return;
}
while ((s[0] != '\0') && (s[0] != ')'))
{
char *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(LL_DEBUG1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_startswith(s, "MESSAGES", CASE_MATCH))
mdata->messages = count;
else if (mutt_str_startswith(s, "RECENT", CASE_MATCH))
mdata->recent = count;
else if (mutt_str_startswith(s, "UIDNEXT", CASE_MATCH))
mdata->uid_next = count;
else if (mutt_str_startswith(s, "UIDVALIDITY", CASE_MATCH))
mdata->uidvalidity = count;
else if (mutt_str_startswith(s, "UNSEEN", CASE_MATCH))
mdata->unseen = count;
s = value;
if ((s[0] != '\0') && (*s != ')'))
s = imap_next_word(s);
}
mutt_debug(LL_DEBUG3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
mdata->name, mdata->uidvalidity, mdata->uid_next, mdata->messages,
mdata->recent, mdata->unseen);
mutt_debug(LL_DEBUG3, "Running default STATUS handler\n");
mutt_debug(LL_DEBUG3, "Found %s in mailbox list (OV: %u ON: %u U: %d)\n",
mailbox, olduv, oldun, mdata->unseen);
bool new_mail = false;
if (C_MailCheckRecent)
{
if ((olduv != 0) && (olduv == mdata->uidvalidity))
{
if (oldun < mdata->uid_next)
new_mail = (mdata->unseen > 0);
}
else if ((olduv == 0) && (oldun == 0))
{
/* first check per session, use recent. might need a flag for this. */
new_mail = (mdata->recent > 0);
}
else
new_mail = (mdata->unseen > 0);
}
else
new_mail = (mdata->unseen > 0);
#ifdef USE_SIDEBAR
if ((m->has_new != new_mail) || (m->msg_count != mdata->messages) ||
(m->msg_unread != mdata->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
m->has_new = new_mail;
m->msg_count = mdata->messages;
m->msg_unread = mdata->unseen;
// force back to keep detecting new mail until the mailbox is opened
if (m->has_new)
mdata->uid_next = oldun;
}
/**
* cmd_parse_enabled - Record what the server has enabled
* @param adata Imap Account data
* @param s Command string containing acceptable encodings
*/
static void cmd_parse_enabled(struct ImapAccountData *adata, const char *s)
{
mutt_debug(LL_DEBUG2, "Handling ENABLED\n");
while ((s = imap_next_word((char *) s)) && (*s != '\0'))
{
if (mutt_str_startswith(s, "UTF8=ACCEPT", CASE_IGNORE) ||
mutt_str_startswith(s, "UTF8=ONLY", CASE_IGNORE))
{
adata->unicode = true;
}
if (mutt_str_startswith(s, "QRESYNC", CASE_IGNORE))
adata->qresync = true;
}
}
/**
* cmd_parse_exists - Parse EXISTS message from serer
* @param adata Imap Account data
* @param pn String containing the total number of messages for the selected mailbox
*/
static void cmd_parse_exists(struct ImapAccountData *adata, const char *pn)
{
unsigned int count = 0;
mutt_debug(LL_DEBUG2, "Handling EXISTS\n");
if (mutt_str_atoui(pn, &count) < 0)
{
mutt_debug(LL_DEBUG1, "Malformed EXISTS: '%s'\n", pn);
return;
}
struct ImapMboxData *mdata = adata->mailbox->mdata;
/* new mail arrived */
if (count < mdata->max_msn)
{
/* Notes 6.0.3 has a tendency to report fewer messages exist than
* it should. */
mutt_debug(LL_DEBUG1, "Message count is out of sync\n");
}
/* at least the InterChange server sends EXISTS messages freely,
* even when there is no new mail */
else if (count == mdata->max_msn)
mutt_debug(LL_DEBUG3, "superfluous EXISTS message\n");
else
{
mutt_debug(LL_DEBUG2, "New mail in %s - %d messages total\n", mdata->name, count);
mdata->reopen |= IMAP_NEWMAIL_PENDING;
mdata->new_mail_count = count;
}
}
/**
* cmd_handle_untagged - fallback parser for otherwise unhandled messages
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*/
static int cmd_handle_untagged(struct ImapAccountData *adata)
{
char *s = imap_next_word(adata->buf);
char *pn = imap_next_word(s);
if ((adata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s))
{
/* pn vs. s: need initial seqno */
pn = s;
s = imap_next_word(s);
/* EXISTS, EXPUNGE, FETCH are always related to the SELECTED mailbox */
if (mutt_str_startswith(s, "EXISTS", CASE_IGNORE))
cmd_parse_exists(adata, pn);
else if (mutt_str_startswith(s, "EXPUNGE", CASE_IGNORE))
cmd_parse_expunge(adata, pn);
else if (mutt_str_startswith(s, "FETCH", CASE_IGNORE))
cmd_parse_fetch(adata, pn);
}
else if ((adata->state >= IMAP_SELECTED) && mutt_str_startswith(s, "VANISHED", CASE_IGNORE))
cmd_parse_vanished(adata, pn);
else if (mutt_str_startswith(s, "CAPABILITY", CASE_IGNORE))
cmd_parse_capability(adata, s);
else if (mutt_str_startswith(s, "OK [CAPABILITY", CASE_IGNORE))
cmd_parse_capability(adata, pn);
else if (mutt_str_startswith(pn, "OK [CAPABILITY", CASE_IGNORE))
cmd_parse_capability(adata, imap_next_word(pn));
else if (mutt_str_startswith(s, "LIST", CASE_IGNORE))
cmd_parse_list(adata, s);
else if (mutt_str_startswith(s, "LSUB", CASE_IGNORE))
cmd_parse_lsub(adata, s);
else if (mutt_str_startswith(s, "MYRIGHTS", CASE_IGNORE))
cmd_parse_myrights(adata, s);
else if (mutt_str_startswith(s, "SEARCH", CASE_IGNORE))
cmd_parse_search(adata, s);
else if (mutt_str_startswith(s, "STATUS", CASE_IGNORE))
cmd_parse_status(adata, s);
else if (mutt_str_startswith(s, "ENABLED", CASE_IGNORE))
cmd_parse_enabled(adata, s);
else if (mutt_str_startswith(s, "BYE", CASE_IGNORE))
{
mutt_debug(LL_DEBUG2, "Handling BYE\n");
/* check if we're logging out */
if (adata->status == IMAP_BYE)
return 0;
/* server shut down our connection */
s += 3;
SKIPWS(s);
mutt_error("%s", s);
cmd_handle_fatal(adata);
return -1;
}
else if (C_ImapServernoise && mutt_str_startswith(s, "NO", CASE_IGNORE))
{
mutt_debug(LL_DEBUG2, "Handling untagged NO\n");
/* Display the warning message from the server */
mutt_error("%s", s + 2);
}
return 0;
}
/**
* imap_cmd_start - Given an IMAP command, send it to the server
* @param adata Imap Account data
* @param cmdstr Command string to send
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*
* If cmdstr is NULL, sends queued commands.
*/
int imap_cmd_start(struct ImapAccountData *adata, const char *cmdstr)
{
return cmd_start(adata, cmdstr, IMAP_CMD_NO_FLAGS);
}
/**
* imap_cmd_step - Reads server responses from an IMAP command
* @param adata Imap Account data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_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 ImapAccountData *adata)
{
if (!adata)
return -1;
size_t len = 0;
int c;
int rc;
int stillrunning = 0;
struct ImapCommand *cmd = NULL;
if (adata->status == IMAP_FATAL)
{
cmd_handle_fatal(adata);
return IMAP_RES_BAD;
}
/* read into buffer, expanding buffer as necessary until we have a full
* line */
do
{
if (len == adata->blen)
{
mutt_mem_realloc(&adata->buf, adata->blen + IMAP_CMD_BUFSIZE);
adata->blen = adata->blen + IMAP_CMD_BUFSIZE;
mutt_debug(LL_DEBUG3, "grew buffer to %lu bytes\n", adata->blen);
}
/* back up over '\0' */
if (len)
len--;
c = mutt_socket_readln_d(adata->buf + len, adata->blen - len, adata->conn, MUTT_SOCK_LOG_FULL);
if (c <= 0)
{
mutt_debug(LL_DEBUG1, "Error reading server response\n");
cmd_handle_fatal(adata);
return IMAP_RES_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 == adata->blen);
/* don't let one large string make cmd->buf hog memory forever */
if ((adata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE))
{
mutt_mem_realloc(&adata->buf, IMAP_CMD_BUFSIZE);
adata->blen = IMAP_CMD_BUFSIZE;
mutt_debug(LL_DEBUG3, "shrank buffer to %lu bytes\n", adata->blen);
}
adata->lastread = mutt_date_epoch();
/* handle untagged messages. The caller still gets its shot afterwards. */
if ((mutt_str_startswith(adata->buf, "* ", CASE_MATCH) ||
mutt_str_startswith(imap_next_word(adata->buf), "OK [", CASE_MATCH)) &&
cmd_handle_untagged(adata))
{
return IMAP_RES_BAD;
}
/* server demands a continuation response from us */
if (adata->buf[0] == '+')
return IMAP_RES_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 adata->cmds entry.
*
* For both these cases, we default to returning OK */
rc = IMAP_RES_OK;
c = adata->lastcmd;
do
{
cmd = &adata->cmds[c];
if (cmd->state == IMAP_RES_NEW)
{
if (mutt_str_startswith(adata->buf, cmd->seq, CASE_MATCH))
{
if (!stillrunning)
{
/* first command in queue has finished - move queue pointer up */
adata->lastcmd = (adata->lastcmd + 1) % adata->cmdslots;
}
cmd->state = cmd_status(adata->buf);
rc = cmd->state;
if (cmd->state == IMAP_RES_NO || cmd->state == IMAP_RES_BAD)
{
mutt_message(_("IMAP command failed: %s"), adata->buf);
}
}
else
stillrunning++;
}
c = (c + 1) % adata->cmdslots;
} while (c != adata->nextcmd);
if (stillrunning)
rc = IMAP_RES_CONTINUE;
else
{
mutt_debug(LL_DEBUG3, "IMAP queue drained\n");
imap_cmd_finish(adata);
}
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_RES_OK;
}
/**
* imap_cmd_trailer - Extra information after tagged command response if any
* @param adata Imap Account data
* @retval ptr Extra command information (pointer into adata->buf)
* @retval "" Error (static string)
*/
const char *imap_cmd_trailer(struct ImapAccountData *adata)
{
static const char *notrailer = "";
const char *s = adata->buf;
if (!s)
{
mutt_debug(LL_DEBUG2, "not a tagged response\n");
return notrailer;
}
s = imap_next_word((char *) s);
if (!s || (!mutt_str_startswith(s, "OK", CASE_IGNORE) &&
!mutt_str_startswith(s, "NO", CASE_IGNORE) &&
!mutt_str_startswith(s, "BAD", CASE_IGNORE)))
{
mutt_debug(LL_DEBUG2, "not a command completion: %s\n", adata->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 adata Imap Account data
* @param cmdstr Command to execute
* @param flags Flags, see #ImapCmdFlags
* @retval #IMAP_EXEC_SUCCESS Command successful or queued
* @retval #IMAP_EXEC_ERROR Command returned an error
* @retval #IMAP_EXEC_FATAL Imap connection failure
*
* Also, handle untagged responses.
*/
int imap_exec(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)
{
int rc;
if (flags & IMAP_CMD_SINGLE)
{
// Process any existing commands
if (adata->nextcmd != adata->lastcmd)
imap_exec(adata, NULL, IMAP_CMD_POLL);
}
rc = cmd_start(adata, cmdstr, flags);
if (rc < 0)
{
cmd_handle_fatal(adata);
return IMAP_EXEC_FATAL;
}
if (flags & IMAP_CMD_QUEUE)
return IMAP_EXEC_SUCCESS;
if ((flags & IMAP_CMD_POLL) && (C_ImapPollTimeout > 0) &&
((mutt_socket_poll(adata->conn, C_ImapPollTimeout)) == 0))
{
mutt_error(_("Connection to %s timed out"), adata->conn->account.host);
cmd_handle_fatal(adata);
return IMAP_EXEC_FATAL;
}
/* Allow interruptions, particularly useful if there are network problems. */
mutt_sig_allow_interrupt(true);
do
{
rc = imap_cmd_step(adata);
// The queue is empty, so the single command has been processed
if ((flags & IMAP_CMD_SINGLE) && (adata->nextcmd == adata->lastcmd))
break;
} while (rc == IMAP_RES_CONTINUE);
mutt_sig_allow_interrupt(false);
if (rc == IMAP_RES_NO)
return IMAP_EXEC_ERROR;
if (rc != IMAP_RES_OK)
{
if (adata->status != IMAP_FATAL)
return IMAP_EXEC_ERROR;
mutt_debug(LL_DEBUG1, "command failed: %s\n", adata->buf);
return IMAP_EXEC_FATAL;
}
return IMAP_EXEC_SUCCESS;
}
/**
* imap_cmd_finish - Attempt to perform cleanup
* @param adata Imap Account data
*
* If a reopen is allowed, it 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.
*
* mdata->check_status is set and will be used later by imap_check_mailbox().
*/
void imap_cmd_finish(struct ImapAccountData *adata)
{
if (!adata)
return;
if (adata->status == IMAP_FATAL)
{
adata->closing = false;
cmd_handle_fatal(adata);
return;
}
if (!(adata->state >= IMAP_SELECTED) || (adata->mailbox && adata->closing))
{
adata->closing = false;
return;
}
adata->closing = false;
struct ImapMboxData *mdata = imap_mdata_get(adata->mailbox);
if (mdata && mdata->reopen & IMAP_REOPEN_ALLOW)
{
// First remove expunged emails from the msn_index
if (mdata->reopen & IMAP_EXPUNGE_PENDING)
{
mutt_debug(LL_DEBUG2, "Expunging mailbox\n");
imap_expunge_mailbox(adata->mailbox);
/* Detect whether we've gotten unexpected EXPUNGE messages */
if (!(mdata->reopen & IMAP_EXPUNGE_EXPECTED))
mdata->check_status |= IMAP_EXPUNGE_PENDING;
mdata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_EXPUNGE_EXPECTED);
}
// Then add new emails to it
if (mdata->reopen & IMAP_NEWMAIL_PENDING && (mdata->new_mail_count > mdata->max_msn))
{
if (!(mdata->reopen & IMAP_EXPUNGE_PENDING))
mdata->check_status |= IMAP_NEWMAIL_PENDING;
mutt_debug(LL_DEBUG2, "Fetching new mails from %d to %d\n",
mdata->max_msn + 1, mdata->new_mail_count);
imap_read_headers(adata->mailbox, mdata->max_msn + 1, mdata->new_mail_count, false);
}
// And to finish inform about MUTT_REOPEN if needed
if (mdata->reopen & IMAP_EXPUNGE_PENDING && !(mdata->reopen & IMAP_EXPUNGE_EXPECTED))
mdata->check_status |= IMAP_EXPUNGE_PENDING;
if (mdata->reopen & IMAP_EXPUNGE_PENDING)
mdata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_EXPUNGE_EXPECTED);
}
adata->status = 0;
}
/**
* imap_cmd_idle - Enter the IDLE state
* @param adata Imap Account data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*/
int imap_cmd_idle(struct ImapAccountData *adata)
{
int rc;
if (cmd_start(adata, "IDLE", IMAP_CMD_POLL) < 0)
{
cmd_handle_fatal(adata);
return -1;
}
if ((C_ImapPollTimeout > 0) && ((mutt_socket_poll(adata->conn, C_ImapPollTimeout)) == 0))
{
mutt_error(_("Connection to %s timed out"), adata->conn->account.host);
cmd_handle_fatal(adata);
return -1;
}
do
{
rc = imap_cmd_step(adata);
} while (rc == IMAP_RES_CONTINUE);
if (rc == IMAP_RES_RESPOND)
{
/* successfully entered IDLE state */
adata->state = IMAP_IDLE;
/* queue automatic exit when next command is issued */
mutt_buffer_addstr(&adata->cmdbuf, "DONE\r\n");
rc = IMAP_RES_OK;
}
if (rc != IMAP_RES_OK)
{
mutt_debug(LL_DEBUG1, "error starting IDLE\n");
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_4069_2 |
crossvul-cpp_data_bad_1907_0 | /*
* Copyright © 2014-2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/personality.h>
#include <grp.h>
#include <unistd.h>
#include <gio/gunixfdlist.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include "libglnx/libglnx.h"
#include "flatpak-run-private.h"
#include "flatpak-proxy.h"
#include "flatpak-utils-private.h"
#include "flatpak-dir-private.h"
#include "flatpak-systemd-dbus-generated.h"
#include "flatpak-error.h"
/* Same order as enum */
const char *flatpak_context_shares[] = {
"network",
"ipc",
NULL
};
/* Same order as enum */
const char *flatpak_context_sockets[] = {
"x11",
"wayland",
"pulseaudio",
"session-bus",
"system-bus",
"fallback-x11",
"ssh-auth",
"pcsc",
"cups",
NULL
};
const char *flatpak_context_devices[] = {
"dri",
"all",
"kvm",
"shm",
NULL
};
const char *flatpak_context_features[] = {
"devel",
"multiarch",
"bluetooth",
"canbus",
NULL
};
const char *flatpak_context_special_filesystems[] = {
"home",
"host",
"host-etc",
"host-os",
NULL
};
FlatpakContext *
flatpak_context_new (void)
{
FlatpakContext *context;
context = g_slice_new0 (FlatpakContext);
context->env_vars = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
context->persistent = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
/* filename or special filesystem name => FlatpakFilesystemMode */
context->filesystems = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
context->session_bus_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
context->system_bus_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
context->generic_policy = g_hash_table_new_full (g_str_hash, g_str_equal,
g_free, (GDestroyNotify) g_strfreev);
return context;
}
void
flatpak_context_free (FlatpakContext *context)
{
g_hash_table_destroy (context->env_vars);
g_hash_table_destroy (context->persistent);
g_hash_table_destroy (context->filesystems);
g_hash_table_destroy (context->session_bus_policy);
g_hash_table_destroy (context->system_bus_policy);
g_hash_table_destroy (context->generic_policy);
g_slice_free (FlatpakContext, context);
}
static guint32
flatpak_context_bitmask_from_string (const char *name, const char **names)
{
guint32 i;
for (i = 0; names[i] != NULL; i++)
{
if (strcmp (names[i], name) == 0)
return 1 << i;
}
return 0;
}
static char **
flatpak_context_bitmask_to_string (guint32 enabled, guint32 valid, const char **names)
{
guint32 i;
GPtrArray *array;
array = g_ptr_array_new ();
for (i = 0; names[i] != NULL; i++)
{
guint32 bitmask = 1 << i;
if (valid & bitmask)
{
if (enabled & bitmask)
g_ptr_array_add (array, g_strdup (names[i]));
else
g_ptr_array_add (array, g_strdup_printf ("!%s", names[i]));
}
}
g_ptr_array_add (array, NULL);
return (char **) g_ptr_array_free (array, FALSE);
}
static void
flatpak_context_bitmask_to_args (guint32 enabled, guint32 valid, const char **names,
const char *enable_arg, const char *disable_arg,
GPtrArray *args)
{
guint32 i;
for (i = 0; names[i] != NULL; i++)
{
guint32 bitmask = 1 << i;
if (valid & bitmask)
{
if (enabled & bitmask)
g_ptr_array_add (args, g_strdup_printf ("%s=%s", enable_arg, names[i]));
else
g_ptr_array_add (args, g_strdup_printf ("%s=%s", disable_arg, names[i]));
}
}
}
static FlatpakContextShares
flatpak_context_share_from_string (const char *string, GError **error)
{
FlatpakContextShares shares = flatpak_context_bitmask_from_string (string, flatpak_context_shares);
if (shares == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_shares);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown share type %s, valid types are: %s"), string, values);
}
return shares;
}
static char **
flatpak_context_shared_to_string (FlatpakContextShares shares, FlatpakContextShares valid)
{
return flatpak_context_bitmask_to_string (shares, valid, flatpak_context_shares);
}
static void
flatpak_context_shared_to_args (FlatpakContextShares shares,
FlatpakContextShares valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (shares, valid, flatpak_context_shares, "--share", "--unshare", args);
}
static FlatpakPolicy
flatpak_policy_from_string (const char *string, GError **error)
{
const char *policies[] = { "none", "see", "talk", "own", NULL };
int i;
g_autofree char *values = NULL;
for (i = 0; policies[i]; i++)
{
if (strcmp (string, policies[i]) == 0)
return i;
}
values = g_strjoinv (", ", (char **) policies);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown policy type %s, valid types are: %s"), string, values);
return -1;
}
static const char *
flatpak_policy_to_string (FlatpakPolicy policy)
{
if (policy == FLATPAK_POLICY_SEE)
return "see";
if (policy == FLATPAK_POLICY_TALK)
return "talk";
if (policy == FLATPAK_POLICY_OWN)
return "own";
return "none";
}
static gboolean
flatpak_verify_dbus_name (const char *name, GError **error)
{
const char *name_part;
g_autofree char *tmp = NULL;
if (g_str_has_suffix (name, ".*"))
{
tmp = g_strndup (name, strlen (name) - 2);
name_part = tmp;
}
else
{
name_part = name;
}
if (g_dbus_is_name (name_part) && !g_dbus_is_unique_name (name_part))
return TRUE;
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Invalid dbus name %s"), name);
return FALSE;
}
static FlatpakContextSockets
flatpak_context_socket_from_string (const char *string, GError **error)
{
FlatpakContextSockets sockets = flatpak_context_bitmask_from_string (string, flatpak_context_sockets);
if (sockets == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_sockets);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown socket type %s, valid types are: %s"), string, values);
}
return sockets;
}
static char **
flatpak_context_sockets_to_string (FlatpakContextSockets sockets, FlatpakContextSockets valid)
{
return flatpak_context_bitmask_to_string (sockets, valid, flatpak_context_sockets);
}
static void
flatpak_context_sockets_to_args (FlatpakContextSockets sockets,
FlatpakContextSockets valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (sockets, valid, flatpak_context_sockets, "--socket", "--nosocket", args);
}
static FlatpakContextDevices
flatpak_context_device_from_string (const char *string, GError **error)
{
FlatpakContextDevices devices = flatpak_context_bitmask_from_string (string, flatpak_context_devices);
if (devices == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_devices);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown device type %s, valid types are: %s"), string, values);
}
return devices;
}
static char **
flatpak_context_devices_to_string (FlatpakContextDevices devices, FlatpakContextDevices valid)
{
return flatpak_context_bitmask_to_string (devices, valid, flatpak_context_devices);
}
static void
flatpak_context_devices_to_args (FlatpakContextDevices devices,
FlatpakContextDevices valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (devices, valid, flatpak_context_devices, "--device", "--nodevice", args);
}
static FlatpakContextFeatures
flatpak_context_feature_from_string (const char *string, GError **error)
{
FlatpakContextFeatures feature = flatpak_context_bitmask_from_string (string, flatpak_context_features);
if (feature == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_features);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown feature type %s, valid types are: %s"), string, values);
}
return feature;
}
static char **
flatpak_context_features_to_string (FlatpakContextFeatures features, FlatpakContextFeatures valid)
{
return flatpak_context_bitmask_to_string (features, valid, flatpak_context_features);
}
static void
flatpak_context_features_to_args (FlatpakContextFeatures features,
FlatpakContextFeatures valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (features, valid, flatpak_context_features, "--allow", "--disallow", args);
}
static void
flatpak_context_add_shares (FlatpakContext *context,
FlatpakContextShares shares)
{
context->shares_valid |= shares;
context->shares |= shares;
}
static void
flatpak_context_remove_shares (FlatpakContext *context,
FlatpakContextShares shares)
{
context->shares_valid |= shares;
context->shares &= ~shares;
}
static void
flatpak_context_add_sockets (FlatpakContext *context,
FlatpakContextSockets sockets)
{
context->sockets_valid |= sockets;
context->sockets |= sockets;
}
static void
flatpak_context_remove_sockets (FlatpakContext *context,
FlatpakContextSockets sockets)
{
context->sockets_valid |= sockets;
context->sockets &= ~sockets;
}
static void
flatpak_context_add_devices (FlatpakContext *context,
FlatpakContextDevices devices)
{
context->devices_valid |= devices;
context->devices |= devices;
}
static void
flatpak_context_remove_devices (FlatpakContext *context,
FlatpakContextDevices devices)
{
context->devices_valid |= devices;
context->devices &= ~devices;
}
static void
flatpak_context_add_features (FlatpakContext *context,
FlatpakContextFeatures features)
{
context->features_valid |= features;
context->features |= features;
}
static void
flatpak_context_remove_features (FlatpakContext *context,
FlatpakContextFeatures features)
{
context->features_valid |= features;
context->features &= ~features;
}
static void
flatpak_context_set_env_var (FlatpakContext *context,
const char *name,
const char *value)
{
g_hash_table_insert (context->env_vars, g_strdup (name), g_strdup (value));
}
void
flatpak_context_set_session_bus_policy (FlatpakContext *context,
const char *name,
FlatpakPolicy policy)
{
g_hash_table_insert (context->session_bus_policy, g_strdup (name), GINT_TO_POINTER (policy));
}
GStrv
flatpak_context_get_session_bus_policy_allowed_own_names (FlatpakContext *context)
{
GHashTableIter iter;
gpointer key, value;
g_autoptr(GPtrArray) names = g_ptr_array_new_with_free_func (g_free);
g_hash_table_iter_init (&iter, context->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
if (GPOINTER_TO_INT (value) == FLATPAK_POLICY_OWN)
g_ptr_array_add (names, g_strdup (key));
g_ptr_array_add (names, NULL);
return (GStrv) g_ptr_array_free (g_steal_pointer (&names), FALSE);
}
void
flatpak_context_set_system_bus_policy (FlatpakContext *context,
const char *name,
FlatpakPolicy policy)
{
g_hash_table_insert (context->system_bus_policy, g_strdup (name), GINT_TO_POINTER (policy));
}
static void
flatpak_context_apply_generic_policy (FlatpakContext *context,
const char *key,
const char *value)
{
GPtrArray *new = g_ptr_array_new ();
const char **old_v;
int i;
g_assert (strchr (key, '.') != NULL);
old_v = g_hash_table_lookup (context->generic_policy, key);
for (i = 0; old_v != NULL && old_v[i] != NULL; i++)
{
const char *old = old_v[i];
const char *cmp1 = old;
const char *cmp2 = value;
if (*cmp1 == '!')
cmp1++;
if (*cmp2 == '!')
cmp2++;
if (strcmp (cmp1, cmp2) != 0)
g_ptr_array_add (new, g_strdup (old));
}
g_ptr_array_add (new, g_strdup (value));
g_ptr_array_add (new, NULL);
g_hash_table_insert (context->generic_policy, g_strdup (key),
g_ptr_array_free (new, FALSE));
}
static void
flatpak_context_set_persistent (FlatpakContext *context,
const char *path)
{
g_hash_table_insert (context->persistent, g_strdup (path), GINT_TO_POINTER (1));
}
static gboolean
get_xdg_dir_from_prefix (const char *prefix,
const char **where,
const char **dir)
{
if (strcmp (prefix, "xdg-data") == 0)
{
if (where)
*where = "data";
if (dir)
*dir = g_get_user_data_dir ();
return TRUE;
}
if (strcmp (prefix, "xdg-cache") == 0)
{
if (where)
*where = "cache";
if (dir)
*dir = g_get_user_cache_dir ();
return TRUE;
}
if (strcmp (prefix, "xdg-config") == 0)
{
if (where)
*where = "config";
if (dir)
*dir = g_get_user_config_dir ();
return TRUE;
}
return FALSE;
}
/* This looks only in the xdg dirs (config, cache, data), not the user
definable ones */
static char *
get_xdg_dir_from_string (const char *filesystem,
const char **suffix,
const char **where)
{
char *slash;
const char *rest;
g_autofree char *prefix = NULL;
const char *dir = NULL;
gsize len;
slash = strchr (filesystem, '/');
if (slash)
len = slash - filesystem;
else
len = strlen (filesystem);
rest = filesystem + len;
while (*rest == '/')
rest++;
if (suffix != NULL)
*suffix = rest;
prefix = g_strndup (filesystem, len);
if (get_xdg_dir_from_prefix (prefix, where, &dir))
return g_build_filename (dir, rest, NULL);
return NULL;
}
static gboolean
get_xdg_user_dir_from_string (const char *filesystem,
const char **config_key,
const char **suffix,
const char **dir)
{
char *slash;
const char *rest;
g_autofree char *prefix = NULL;
gsize len;
slash = strchr (filesystem, '/');
if (slash)
len = slash - filesystem;
else
len = strlen (filesystem);
rest = filesystem + len;
while (*rest == '/')
rest++;
if (suffix)
*suffix = rest;
prefix = g_strndup (filesystem, len);
if (strcmp (prefix, "xdg-desktop") == 0)
{
if (config_key)
*config_key = "XDG_DESKTOP_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP);
return TRUE;
}
if (strcmp (prefix, "xdg-documents") == 0)
{
if (config_key)
*config_key = "XDG_DOCUMENTS_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS);
return TRUE;
}
if (strcmp (prefix, "xdg-download") == 0)
{
if (config_key)
*config_key = "XDG_DOWNLOAD_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
return TRUE;
}
if (strcmp (prefix, "xdg-music") == 0)
{
if (config_key)
*config_key = "XDG_MUSIC_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_MUSIC);
return TRUE;
}
if (strcmp (prefix, "xdg-pictures") == 0)
{
if (config_key)
*config_key = "XDG_PICTURES_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
return TRUE;
}
if (strcmp (prefix, "xdg-public-share") == 0)
{
if (config_key)
*config_key = "XDG_PUBLICSHARE_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE);
return TRUE;
}
if (strcmp (prefix, "xdg-templates") == 0)
{
if (config_key)
*config_key = "XDG_TEMPLATES_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES);
return TRUE;
}
if (strcmp (prefix, "xdg-videos") == 0)
{
if (config_key)
*config_key = "XDG_VIDEOS_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS);
return TRUE;
}
if (get_xdg_dir_from_prefix (prefix, NULL, dir))
{
if (config_key)
*config_key = NULL;
return TRUE;
}
/* Don't support xdg-run without suffix, because that doesn't work */
if (strcmp (prefix, "xdg-run") == 0 &&
*rest != 0)
{
if (config_key)
*config_key = NULL;
if (dir)
*dir = flatpak_get_real_xdg_runtime_dir ();
return TRUE;
}
return FALSE;
}
static char *
unparse_filesystem_flags (const char *path,
FlatpakFilesystemMode mode)
{
g_autoptr(GString) s = g_string_new ("");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else if (*p == '\\')
g_string_append (s, "\\\\");
else
g_string_append_c (s, *p);
}
switch (mode)
{
case FLATPAK_FILESYSTEM_MODE_READ_ONLY:
g_string_append (s, ":ro");
break;
case FLATPAK_FILESYSTEM_MODE_CREATE:
g_string_append (s, ":create");
break;
case FLATPAK_FILESYSTEM_MODE_READ_WRITE:
break;
case FLATPAK_FILESYSTEM_MODE_NONE:
g_string_insert_c (s, 0, '!');
break;
default:
g_warning ("Unexpected filesystem mode %d", mode);
break;
}
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
parse_filesystem_flags (const char *filesystem,
FlatpakFilesystemMode *mode_out)
{
g_autoptr(GString) s = g_string_new ("");
const char *p, *suffix;
FlatpakFilesystemMode mode;
p = filesystem;
while (*p != 0 && *p != ':')
{
if (*p == '\\')
{
p++;
if (*p != 0)
g_string_append_c (s, *p++);
}
else
g_string_append_c (s, *p++);
}
mode = FLATPAK_FILESYSTEM_MODE_READ_WRITE;
if (*p == ':')
{
suffix = p + 1;
if (strcmp (suffix, "ro") == 0)
mode = FLATPAK_FILESYSTEM_MODE_READ_ONLY;
else if (strcmp (suffix, "rw") == 0)
mode = FLATPAK_FILESYSTEM_MODE_READ_WRITE;
else if (strcmp (suffix, "create") == 0)
mode = FLATPAK_FILESYSTEM_MODE_CREATE;
else if (*suffix != 0)
g_warning ("Unexpected filesystem suffix %s, ignoring", suffix);
}
if (mode_out)
*mode_out = mode;
return g_string_free (g_steal_pointer (&s), FALSE);
}
gboolean
flatpak_context_parse_filesystem (const char *filesystem_and_mode,
char **filesystem_out,
FlatpakFilesystemMode *mode_out,
GError **error)
{
g_autofree char *filesystem = parse_filesystem_flags (filesystem_and_mode, mode_out);
char *slash;
slash = strchr (filesystem, '/');
/* Forbid /../ in paths */
if (slash != NULL)
{
if (g_str_has_prefix (slash + 1, "../") ||
g_str_has_suffix (slash + 1, "/..") ||
strstr (slash + 1, "/../") != NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("Filesystem location \"%s\" contains \"..\""),
filesystem);
return FALSE;
}
/* Convert "//" and "/./" to "/" */
for (; slash != NULL; slash = strchr (slash + 1, '/'))
{
while (TRUE)
{
if (slash[1] == '/')
memmove (slash + 1, slash + 2, strlen (slash + 2) + 1);
else if (slash[1] == '.' && slash[2] == '/')
memmove (slash + 1, slash + 3, strlen (slash + 3) + 1);
else
break;
}
}
/* Eliminate trailing "/." or "/". */
while (TRUE)
{
slash = strrchr (filesystem, '/');
if (slash != NULL &&
((slash != filesystem && slash[1] == '\0') ||
(slash[1] == '.' && slash[2] == '\0')))
*slash = '\0';
else
break;
}
if (filesystem[0] == '/' && filesystem[1] == '\0')
{
/* We don't allow --filesystem=/ as equivalent to host, because
* it doesn't do what you'd think: --filesystem=host mounts some
* host directories in /run/host, not in the root. */
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--filesystem=/ is not available, "
"use --filesystem=host for a similar result"));
return FALSE;
}
}
if (g_strv_contains (flatpak_context_special_filesystems, filesystem) ||
get_xdg_user_dir_from_string (filesystem, NULL, NULL, NULL) ||
g_str_has_prefix (filesystem, "~/") ||
g_str_has_prefix (filesystem, "/"))
{
if (filesystem_out != NULL)
*filesystem_out = g_steal_pointer (&filesystem);
return TRUE;
}
if (strcmp (filesystem, "~") == 0)
{
if (filesystem_out != NULL)
*filesystem_out = g_strdup ("home");
return TRUE;
}
if (g_str_has_prefix (filesystem, "home/"))
{
if (filesystem_out != NULL)
*filesystem_out = g_strconcat ("~/", filesystem + 5, NULL);
return TRUE;
}
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown filesystem location %s, valid locations are: host, host-os, host-etc, home, xdg-*[/…], ~/dir, /dir"), filesystem);
return FALSE;
}
static void
flatpak_context_take_filesystem (FlatpakContext *context,
char *fs,
FlatpakFilesystemMode mode)
{
g_hash_table_insert (context->filesystems, fs, GINT_TO_POINTER (mode));
}
void
flatpak_context_merge (FlatpakContext *context,
FlatpakContext *other)
{
GHashTableIter iter;
gpointer key, value;
context->shares &= ~other->shares_valid;
context->shares |= other->shares;
context->shares_valid |= other->shares_valid;
context->sockets &= ~other->sockets_valid;
context->sockets |= other->sockets;
context->sockets_valid |= other->sockets_valid;
context->devices &= ~other->devices_valid;
context->devices |= other->devices;
context->devices_valid |= other->devices_valid;
context->features &= ~other->features_valid;
context->features |= other->features;
context->features_valid |= other->features_valid;
g_hash_table_iter_init (&iter, other->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->env_vars, g_strdup (key), g_strdup (value));
g_hash_table_iter_init (&iter, other->persistent);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->persistent, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->filesystems, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->session_bus_policy, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->system_bus_policy, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->system_bus_policy, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->generic_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char **policy_values = (const char **) value;
int i;
for (i = 0; policy_values[i] != NULL; i++)
flatpak_context_apply_generic_policy (context, (char *) key, policy_values[i]);
}
}
static gboolean
option_share_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextShares share;
share = flatpak_context_share_from_string (value, error);
if (share == 0)
return FALSE;
flatpak_context_add_shares (context, share);
return TRUE;
}
static gboolean
option_unshare_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextShares share;
share = flatpak_context_share_from_string (value, error);
if (share == 0)
return FALSE;
flatpak_context_remove_shares (context, share);
return TRUE;
}
static gboolean
option_socket_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextSockets socket;
socket = flatpak_context_socket_from_string (value, error);
if (socket == 0)
return FALSE;
if (socket == FLATPAK_CONTEXT_SOCKET_FALLBACK_X11)
socket |= FLATPAK_CONTEXT_SOCKET_X11;
flatpak_context_add_sockets (context, socket);
return TRUE;
}
static gboolean
option_nosocket_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextSockets socket;
socket = flatpak_context_socket_from_string (value, error);
if (socket == 0)
return FALSE;
if (socket == FLATPAK_CONTEXT_SOCKET_FALLBACK_X11)
socket |= FLATPAK_CONTEXT_SOCKET_X11;
flatpak_context_remove_sockets (context, socket);
return TRUE;
}
static gboolean
option_device_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextDevices device;
device = flatpak_context_device_from_string (value, error);
if (device == 0)
return FALSE;
flatpak_context_add_devices (context, device);
return TRUE;
}
static gboolean
option_nodevice_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextDevices device;
device = flatpak_context_device_from_string (value, error);
if (device == 0)
return FALSE;
flatpak_context_remove_devices (context, device);
return TRUE;
}
static gboolean
option_allow_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextFeatures feature;
feature = flatpak_context_feature_from_string (value, error);
if (feature == 0)
return FALSE;
flatpak_context_add_features (context, feature);
return TRUE;
}
static gboolean
option_disallow_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextFeatures feature;
feature = flatpak_context_feature_from_string (value, error);
if (feature == 0)
return FALSE;
flatpak_context_remove_features (context, feature);
return TRUE;
}
static gboolean
option_filesystem_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
g_autofree char *fs = NULL;
FlatpakFilesystemMode mode;
if (!flatpak_context_parse_filesystem (value, &fs, &mode, error))
return FALSE;
flatpak_context_take_filesystem (context, g_steal_pointer (&fs), mode);
return TRUE;
}
static gboolean
option_nofilesystem_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
g_autofree char *fs = NULL;
FlatpakFilesystemMode mode;
if (!flatpak_context_parse_filesystem (value, &fs, &mode, error))
return FALSE;
flatpak_context_take_filesystem (context, g_steal_pointer (&fs),
FLATPAK_FILESYSTEM_MODE_NONE);
return TRUE;
}
static gboolean
option_env_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
g_auto(GStrv) split = g_strsplit (value, "=", 2);
if (split == NULL || split[0] == NULL || split[0][0] == 0 || split[1] == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Invalid env format %s"), value);
return FALSE;
}
flatpak_context_set_env_var (context, split[0], split[1]);
return TRUE;
}
static gboolean
option_own_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_session_bus_policy (context, value, FLATPAK_POLICY_OWN);
return TRUE;
}
static gboolean
option_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_session_bus_policy (context, value, FLATPAK_POLICY_TALK);
return TRUE;
}
static gboolean
option_no_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_session_bus_policy (context, value, FLATPAK_POLICY_NONE);
return TRUE;
}
static gboolean
option_system_own_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_system_bus_policy (context, value, FLATPAK_POLICY_OWN);
return TRUE;
}
static gboolean
option_system_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_system_bus_policy (context, value, FLATPAK_POLICY_TALK);
return TRUE;
}
static gboolean
option_system_no_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_system_bus_policy (context, value, FLATPAK_POLICY_NONE);
return TRUE;
}
static gboolean
option_add_generic_policy_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
char *t;
g_autofree char *key = NULL;
const char *policy_value;
t = strchr (value, '=');
if (t == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--add-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
policy_value = t + 1;
key = g_strndup (value, t - value);
if (strchr (key, '.') == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--add-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
if (policy_value[0] == '!')
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--add-policy values can't start with \"!\""));
return FALSE;
}
flatpak_context_apply_generic_policy (context, key, policy_value);
return TRUE;
}
static gboolean
option_remove_generic_policy_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
char *t;
g_autofree char *key = NULL;
const char *policy_value;
g_autofree char *extended_value = NULL;
t = strchr (value, '=');
if (t == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--remove-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
policy_value = t + 1;
key = g_strndup (value, t - value);
if (strchr (key, '.') == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--remove-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
if (policy_value[0] == '!')
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--remove-policy values can't start with \"!\""));
return FALSE;
}
extended_value = g_strconcat ("!", policy_value, NULL);
flatpak_context_apply_generic_policy (context, key, extended_value);
return TRUE;
}
static gboolean
option_persist_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
flatpak_context_set_persistent (context, value);
return TRUE;
}
static gboolean option_no_desktop_deprecated;
static GOptionEntry context_options[] = {
{ "share", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_share_cb, N_("Share with host"), N_("SHARE") },
{ "unshare", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_unshare_cb, N_("Unshare with host"), N_("SHARE") },
{ "socket", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_socket_cb, N_("Expose socket to app"), N_("SOCKET") },
{ "nosocket", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_nosocket_cb, N_("Don't expose socket to app"), N_("SOCKET") },
{ "device", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_device_cb, N_("Expose device to app"), N_("DEVICE") },
{ "nodevice", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_nodevice_cb, N_("Don't expose device to app"), N_("DEVICE") },
{ "allow", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_allow_cb, N_("Allow feature"), N_("FEATURE") },
{ "disallow", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_disallow_cb, N_("Don't allow feature"), N_("FEATURE") },
{ "filesystem", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_filesystem_cb, N_("Expose filesystem to app (:ro for read-only)"), N_("FILESYSTEM[:ro]") },
{ "nofilesystem", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_nofilesystem_cb, N_("Don't expose filesystem to app"), N_("FILESYSTEM") },
{ "env", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_env_cb, N_("Set environment variable"), N_("VAR=VALUE") },
{ "own-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_own_name_cb, N_("Allow app to own name on the session bus"), N_("DBUS_NAME") },
{ "talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_talk_name_cb, N_("Allow app to talk to name on the session bus"), N_("DBUS_NAME") },
{ "no-talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_no_talk_name_cb, N_("Don't allow app to talk to name on the session bus"), N_("DBUS_NAME") },
{ "system-own-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_system_own_name_cb, N_("Allow app to own name on the system bus"), N_("DBUS_NAME") },
{ "system-talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_system_talk_name_cb, N_("Allow app to talk to name on the system bus"), N_("DBUS_NAME") },
{ "system-no-talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_system_no_talk_name_cb, N_("Don't allow app to talk to name on the system bus"), N_("DBUS_NAME") },
{ "add-policy", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_add_generic_policy_cb, N_("Add generic policy option"), N_("SUBSYSTEM.KEY=VALUE") },
{ "remove-policy", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_remove_generic_policy_cb, N_("Remove generic policy option"), N_("SUBSYSTEM.KEY=VALUE") },
{ "persist", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_persist_cb, N_("Persist home directory subpath"), N_("FILENAME") },
/* This is not needed/used anymore, so hidden, but we accept it for backwards compat */
{ "no-desktop", 0, G_OPTION_FLAG_IN_MAIN | G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &option_no_desktop_deprecated, N_("Don't require a running session (no cgroups creation)"), NULL },
{ NULL }
};
GOptionEntry *
flatpak_context_get_option_entries (void)
{
return context_options;
}
GOptionGroup *
flatpak_context_get_options (FlatpakContext *context)
{
GOptionGroup *group;
group = g_option_group_new ("environment",
"Runtime Environment",
"Runtime Environment",
context,
NULL);
g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
g_option_group_add_entries (group, context_options);
return group;
}
static const char *
parse_negated (const char *option, gboolean *negated)
{
if (option[0] == '!')
{
option++;
*negated = TRUE;
}
else
{
*negated = FALSE;
}
return option;
}
/*
* Merge the FLATPAK_METADATA_GROUP_CONTEXT,
* FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,
* FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY and
* FLATPAK_METADATA_GROUP_ENVIRONMENT groups, and all groups starting
* with FLATPAK_METADATA_GROUP_PREFIX_POLICY, from metakey into context.
*
* This is a merge, not a replace!
*/
gboolean
flatpak_context_load_metadata (FlatpakContext *context,
GKeyFile *metakey,
GError **error)
{
gboolean remove;
g_auto(GStrv) groups = NULL;
gsize i;
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_SHARED, NULL))
{
g_auto(GStrv) shares = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED, NULL, error);
if (shares == NULL)
return FALSE;
for (i = 0; shares[i] != NULL; i++)
{
FlatpakContextShares share;
share = flatpak_context_share_from_string (parse_negated (shares[i], &remove), NULL);
if (share == 0)
g_debug ("Unknown share type %s", shares[i]);
else
{
if (remove)
flatpak_context_remove_shares (context, share);
else
flatpak_context_add_shares (context, share);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_SOCKETS, NULL))
{
g_auto(GStrv) sockets = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS, NULL, error);
if (sockets == NULL)
return FALSE;
for (i = 0; sockets[i] != NULL; i++)
{
FlatpakContextSockets socket = flatpak_context_socket_from_string (parse_negated (sockets[i], &remove), NULL);
if (socket == 0)
g_debug ("Unknown socket type %s", sockets[i]);
else
{
if (remove)
flatpak_context_remove_sockets (context, socket);
else
flatpak_context_add_sockets (context, socket);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_DEVICES, NULL))
{
g_auto(GStrv) devices = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES, NULL, error);
if (devices == NULL)
return FALSE;
for (i = 0; devices[i] != NULL; i++)
{
FlatpakContextDevices device = flatpak_context_device_from_string (parse_negated (devices[i], &remove), NULL);
if (device == 0)
g_debug ("Unknown device type %s", devices[i]);
else
{
if (remove)
flatpak_context_remove_devices (context, device);
else
flatpak_context_add_devices (context, device);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_FEATURES, NULL))
{
g_auto(GStrv) features = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FEATURES, NULL, error);
if (features == NULL)
return FALSE;
for (i = 0; features[i] != NULL; i++)
{
FlatpakContextFeatures feature = flatpak_context_feature_from_string (parse_negated (features[i], &remove), NULL);
if (feature == 0)
g_debug ("Unknown feature type %s", features[i]);
else
{
if (remove)
flatpak_context_remove_features (context, feature);
else
flatpak_context_add_features (context, feature);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_FILESYSTEMS, NULL))
{
g_auto(GStrv) filesystems = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FILESYSTEMS, NULL, error);
if (filesystems == NULL)
return FALSE;
for (i = 0; filesystems[i] != NULL; i++)
{
const char *fs = parse_negated (filesystems[i], &remove);
g_autofree char *filesystem = NULL;
FlatpakFilesystemMode mode;
if (!flatpak_context_parse_filesystem (fs, &filesystem, &mode, NULL))
g_debug ("Unknown filesystem type %s", filesystems[i]);
else
{
if (remove)
flatpak_context_take_filesystem (context, g_steal_pointer (&filesystem),
FLATPAK_FILESYSTEM_MODE_NONE);
else
flatpak_context_take_filesystem (context, g_steal_pointer (&filesystem), mode);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_PERSISTENT, NULL))
{
g_auto(GStrv) persistent = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_PERSISTENT, NULL, error);
if (persistent == NULL)
return FALSE;
for (i = 0; persistent[i] != NULL; i++)
flatpak_context_set_persistent (context, persistent[i]);
}
if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY))
{
g_auto(GStrv) keys = NULL;
gsize keys_count;
keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, &keys_count, NULL);
for (i = 0; i < keys_count; i++)
{
const char *key = keys[i];
g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, key, NULL);
FlatpakPolicy policy;
if (!flatpak_verify_dbus_name (key, error))
return FALSE;
policy = flatpak_policy_from_string (value, NULL);
if ((int) policy != -1)
flatpak_context_set_session_bus_policy (context, key, policy);
}
}
if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY))
{
g_auto(GStrv) keys = NULL;
gsize keys_count;
keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, &keys_count, NULL);
for (i = 0; i < keys_count; i++)
{
const char *key = keys[i];
g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, key, NULL);
FlatpakPolicy policy;
if (!flatpak_verify_dbus_name (key, error))
return FALSE;
policy = flatpak_policy_from_string (value, NULL);
if ((int) policy != -1)
flatpak_context_set_system_bus_policy (context, key, policy);
}
}
if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT))
{
g_auto(GStrv) keys = NULL;
gsize keys_count;
keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, &keys_count, NULL);
for (i = 0; i < keys_count; i++)
{
const char *key = keys[i];
g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, key, NULL);
flatpak_context_set_env_var (context, key, value);
}
}
groups = g_key_file_get_groups (metakey, NULL);
for (i = 0; groups[i] != NULL; i++)
{
const char *group = groups[i];
const char *subsystem;
int j;
if (g_str_has_prefix (group, FLATPAK_METADATA_GROUP_PREFIX_POLICY))
{
g_auto(GStrv) keys = NULL;
subsystem = group + strlen (FLATPAK_METADATA_GROUP_PREFIX_POLICY);
keys = g_key_file_get_keys (metakey, group, NULL, NULL);
for (j = 0; keys != NULL && keys[j] != NULL; j++)
{
const char *key = keys[j];
g_autofree char *policy_key = g_strdup_printf ("%s.%s", subsystem, key);
g_auto(GStrv) values = NULL;
int k;
values = g_key_file_get_string_list (metakey, group, key, NULL, NULL);
for (k = 0; values != NULL && values[k] != NULL; k++)
flatpak_context_apply_generic_policy (context, policy_key,
values[k]);
}
}
}
return TRUE;
}
/*
* Save the FLATPAK_METADATA_GROUP_CONTEXT,
* FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,
* FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY and
* FLATPAK_METADATA_GROUP_ENVIRONMENT groups, and all groups starting
* with FLATPAK_METADATA_GROUP_PREFIX_POLICY, into metakey
*/
void
flatpak_context_save_metadata (FlatpakContext *context,
gboolean flatten,
GKeyFile *metakey)
{
g_auto(GStrv) shared = NULL;
g_auto(GStrv) sockets = NULL;
g_auto(GStrv) devices = NULL;
g_auto(GStrv) features = NULL;
GHashTableIter iter;
gpointer key, value;
FlatpakContextShares shares_mask = context->shares;
FlatpakContextShares shares_valid = context->shares_valid;
FlatpakContextSockets sockets_mask = context->sockets;
FlatpakContextSockets sockets_valid = context->sockets_valid;
FlatpakContextDevices devices_mask = context->devices;
FlatpakContextDevices devices_valid = context->devices_valid;
FlatpakContextFeatures features_mask = context->features;
FlatpakContextFeatures features_valid = context->features_valid;
g_auto(GStrv) groups = NULL;
int i;
if (flatten)
{
/* A flattened format means we don't expect this to be merged on top of
another context. In that case we never need to negate any flags.
We calculate this by removing the zero parts of the mask from the valid set.
*/
/* First we make sure only the valid parts of the mask are set, in case we
got some leftover */
shares_mask &= shares_valid;
sockets_mask &= sockets_valid;
devices_mask &= devices_valid;
features_mask &= features_valid;
/* Then just set the valid set to be the mask set */
shares_valid = shares_mask;
sockets_valid = sockets_mask;
devices_valid = devices_mask;
features_valid = features_mask;
}
shared = flatpak_context_shared_to_string (shares_mask, shares_valid);
sockets = flatpak_context_sockets_to_string (sockets_mask, sockets_valid);
devices = flatpak_context_devices_to_string (devices_mask, devices_valid);
features = flatpak_context_features_to_string (features_mask, features_valid);
if (shared[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED,
(const char * const *) shared, g_strv_length (shared));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED,
NULL);
}
if (sockets[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS,
(const char * const *) sockets, g_strv_length (sockets));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS,
NULL);
}
if (devices[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES,
(const char * const *) devices, g_strv_length (devices));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES,
NULL);
}
if (features[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FEATURES,
(const char * const *) features, g_strv_length (features));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FEATURES,
NULL);
}
if (g_hash_table_size (context->filesystems) > 0)
{
g_autoptr(GPtrArray) array = g_ptr_array_new_with_free_func (g_free);
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
g_ptr_array_add (array, unparse_filesystem_flags (key, mode));
}
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FILESYSTEMS,
(const char * const *) array->pdata, array->len);
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FILESYSTEMS,
NULL);
}
if (g_hash_table_size (context->persistent) > 0)
{
g_autofree char **keys = (char **) g_hash_table_get_keys_as_array (context->persistent, NULL);
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_PERSISTENT,
(const char * const *) keys, g_strv_length (keys));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_PERSISTENT,
NULL);
}
g_key_file_remove_group (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, NULL);
g_hash_table_iter_init (&iter, context->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakPolicy policy = GPOINTER_TO_INT (value);
if (flatten && (policy == 0))
continue;
g_key_file_set_string (metakey,
FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,
(char *) key, flatpak_policy_to_string (policy));
}
g_key_file_remove_group (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, NULL);
g_hash_table_iter_init (&iter, context->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakPolicy policy = GPOINTER_TO_INT (value);
if (flatten && (policy == 0))
continue;
g_key_file_set_string (metakey,
FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY,
(char *) key, flatpak_policy_to_string (policy));
}
g_key_file_remove_group (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, NULL);
g_hash_table_iter_init (&iter, context->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
{
g_key_file_set_string (metakey,
FLATPAK_METADATA_GROUP_ENVIRONMENT,
(char *) key, (char *) value);
}
groups = g_key_file_get_groups (metakey, NULL);
for (i = 0; groups[i] != NULL; i++)
{
const char *group = groups[i];
if (g_str_has_prefix (group, FLATPAK_METADATA_GROUP_PREFIX_POLICY))
g_key_file_remove_group (metakey, group, NULL);
}
g_hash_table_iter_init (&iter, context->generic_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
g_auto(GStrv) parts = g_strsplit ((const char *) key, ".", 2);
g_autofree char *group = NULL;
g_assert (parts[1] != NULL);
const char **policy_values = (const char **) value;
g_autoptr(GPtrArray) new = g_ptr_array_new ();
for (i = 0; policy_values[i] != NULL; i++)
{
const char *policy_value = policy_values[i];
if (!flatten || policy_value[0] != '!')
g_ptr_array_add (new, (char *) policy_value);
}
if (new->len > 0)
{
group = g_strconcat (FLATPAK_METADATA_GROUP_PREFIX_POLICY,
parts[0], NULL);
g_key_file_set_string_list (metakey, group, parts[1],
(const char * const *) new->pdata,
new->len);
}
}
}
void
flatpak_context_allow_host_fs (FlatpakContext *context)
{
flatpak_context_take_filesystem (context, g_strdup ("host"), FLATPAK_FILESYSTEM_MODE_READ_WRITE);
}
gboolean
flatpak_context_get_needs_session_bus_proxy (FlatpakContext *context)
{
return g_hash_table_size (context->session_bus_policy) > 0;
}
gboolean
flatpak_context_get_needs_system_bus_proxy (FlatpakContext *context)
{
return g_hash_table_size (context->system_bus_policy) > 0;
}
static gboolean
adds_flags (guint32 old_flags, guint32 new_flags)
{
return (new_flags & ~old_flags) != 0;
}
static gboolean
adds_bus_policy (GHashTable *old, GHashTable *new)
{
GLNX_HASH_TABLE_FOREACH_KV (new, const char *, name, gpointer, _new_policy)
{
int new_policy = GPOINTER_TO_INT (_new_policy);
int old_policy = GPOINTER_TO_INT (g_hash_table_lookup (old, name));
if (new_policy > old_policy)
return TRUE;
}
return FALSE;
}
static gboolean
adds_generic_policy (GHashTable *old, GHashTable *new)
{
GLNX_HASH_TABLE_FOREACH_KV (new, const char *, key, GPtrArray *, new_values)
{
GPtrArray *old_values = g_hash_table_lookup (old, key);
int i;
if (new_values == NULL || new_values->len == 0)
continue;
if (old_values == NULL || old_values->len == 0)
return TRUE;
for (i = 0; i < new_values->len; i++)
{
const char *new_value = g_ptr_array_index (new_values, i);
if (!flatpak_g_ptr_array_contains_string (old_values, new_value))
return TRUE;
}
}
return FALSE;
}
static gboolean
adds_filesystem_access (GHashTable *old, GHashTable *new)
{
FlatpakFilesystemMode old_host_mode = GPOINTER_TO_INT (g_hash_table_lookup (old, "host"));
GLNX_HASH_TABLE_FOREACH_KV (new, const char *, location, gpointer, _new_mode)
{
FlatpakFilesystemMode new_mode = GPOINTER_TO_INT (_new_mode);
FlatpakFilesystemMode old_mode = GPOINTER_TO_INT (g_hash_table_lookup (old, location));
/* Allow more limited access to the same thing */
if (new_mode <= old_mode)
continue;
/* Allow more limited access if we used to have access to everything */
if (new_mode <= old_host_mode)
continue;
/* For the remainder we have to be pessimistic, for instance even
if we have home access we can't allow adding access to ~/foo,
because foo might be a symlink outside home which didn't work
before but would work with an explicit access to that
particular file. */
return TRUE;
}
return FALSE;
}
gboolean
flatpak_context_adds_permissions (FlatpakContext *old,
FlatpakContext *new)
{
guint32 old_sockets;
if (adds_flags (old->shares & old->shares_valid,
new->shares & new->shares_valid))
return TRUE;
old_sockets = old->sockets & old->sockets_valid;
/* If we used to allow X11, also allow new fallback X11,
as that is actually less permissions */
if (old_sockets & FLATPAK_CONTEXT_SOCKET_X11)
old_sockets |= FLATPAK_CONTEXT_SOCKET_FALLBACK_X11;
if (adds_flags (old_sockets,
new->sockets & new->sockets_valid))
return TRUE;
if (adds_flags (old->devices & old->devices_valid,
new->devices & new->devices_valid))
return TRUE;
/* We allow upgrade to multiarch, that is really not a huge problem */
if (adds_flags ((old->features & old->features_valid) | FLATPAK_CONTEXT_FEATURE_MULTIARCH,
new->features & new->features_valid))
return TRUE;
if (adds_bus_policy (old->session_bus_policy, new->session_bus_policy))
return TRUE;
if (adds_bus_policy (old->system_bus_policy, new->system_bus_policy))
return TRUE;
if (adds_generic_policy (old->generic_policy, new->generic_policy))
return TRUE;
if (adds_filesystem_access (old->filesystems, new->filesystems))
return TRUE;
return FALSE;
}
gboolean
flatpak_context_allows_features (FlatpakContext *context,
FlatpakContextFeatures features)
{
return (context->features & features) == features;
}
void
flatpak_context_to_args (FlatpakContext *context,
GPtrArray *args)
{
GHashTableIter iter;
gpointer key, value;
flatpak_context_shared_to_args (context->shares, context->shares_valid, args);
flatpak_context_sockets_to_args (context->sockets, context->sockets_valid, args);
flatpak_context_devices_to_args (context->devices, context->devices_valid, args);
flatpak_context_features_to_args (context->features, context->features_valid, args);
g_hash_table_iter_init (&iter, context->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
g_ptr_array_add (args, g_strdup_printf ("--env=%s=%s", (char *) key, (char *) value));
g_hash_table_iter_init (&iter, context->persistent);
while (g_hash_table_iter_next (&iter, &key, &value))
g_ptr_array_add (args, g_strdup_printf ("--persist=%s", (char *) key));
g_hash_table_iter_init (&iter, context->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
FlatpakPolicy policy = GPOINTER_TO_INT (value);
g_ptr_array_add (args, g_strdup_printf ("--%s-name=%s", flatpak_policy_to_string (policy), name));
}
g_hash_table_iter_init (&iter, context->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
FlatpakPolicy policy = GPOINTER_TO_INT (value);
g_ptr_array_add (args, g_strdup_printf ("--system-%s-name=%s", flatpak_policy_to_string (policy), name));
}
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
if (mode != FLATPAK_FILESYSTEM_MODE_NONE)
{
g_autofree char *fs = unparse_filesystem_flags (key, mode);
g_ptr_array_add (args, g_strdup_printf ("--filesystem=%s", fs));
}
else
g_ptr_array_add (args, g_strdup_printf ("--nofilesystem=%s", (char *) key));
}
}
void
flatpak_context_add_bus_filters (FlatpakContext *context,
const char *app_id,
gboolean session_bus,
gboolean sandboxed,
FlatpakBwrap *bwrap)
{
GHashTable *ht;
GHashTableIter iter;
gpointer key, value;
flatpak_bwrap_add_arg (bwrap, "--filter");
if (app_id && session_bus)
{
if (!sandboxed)
{
flatpak_bwrap_add_arg_printf (bwrap, "--own=%s.*", app_id);
flatpak_bwrap_add_arg_printf (bwrap, "--own=org.mpris.MediaPlayer2.%s.*", app_id);
}
else
flatpak_bwrap_add_arg_printf (bwrap, "--own=%s.Sandboxed.*", app_id);
}
if (session_bus)
ht = context->session_bus_policy;
else
ht = context->system_bus_policy;
g_hash_table_iter_init (&iter, ht);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakPolicy policy = GPOINTER_TO_INT (value);
if (policy > 0)
flatpak_bwrap_add_arg_printf (bwrap, "--%s=%s",
flatpak_policy_to_string (policy),
(char *) key);
}
}
void
flatpak_context_reset_non_permissions (FlatpakContext *context)
{
g_hash_table_remove_all (context->env_vars);
}
void
flatpak_context_reset_permissions (FlatpakContext *context)
{
context->shares_valid = 0;
context->sockets_valid = 0;
context->devices_valid = 0;
context->features_valid = 0;
context->shares = 0;
context->sockets = 0;
context->devices = 0;
context->features = 0;
g_hash_table_remove_all (context->persistent);
g_hash_table_remove_all (context->filesystems);
g_hash_table_remove_all (context->session_bus_policy);
g_hash_table_remove_all (context->system_bus_policy);
g_hash_table_remove_all (context->generic_policy);
}
void
flatpak_context_make_sandboxed (FlatpakContext *context)
{
/* We drop almost everything from the app permission, except
* multiarch which is inherited, to make sure app code keeps
* running. */
context->shares_valid &= 0;
context->sockets_valid &= 0;
context->devices_valid &= 0;
context->features_valid &= FLATPAK_CONTEXT_FEATURE_MULTIARCH;
context->shares &= context->shares_valid;
context->sockets &= context->sockets_valid;
context->devices &= context->devices_valid;
context->features &= context->features_valid;
g_hash_table_remove_all (context->persistent);
g_hash_table_remove_all (context->filesystems);
g_hash_table_remove_all (context->session_bus_policy);
g_hash_table_remove_all (context->system_bus_policy);
g_hash_table_remove_all (context->generic_policy);
}
const char *dont_mount_in_root[] = {
".", "..", "lib", "lib32", "lib64", "bin", "sbin", "usr", "boot", "root",
"tmp", "etc", "app", "run", "proc", "sys", "dev", "var", NULL
};
static void
flatpak_context_export (FlatpakContext *context,
FlatpakExports *exports,
GFile *app_id_dir,
GPtrArray *extra_app_id_dirs,
gboolean do_create,
GString *xdg_dirs_conf,
gboolean *home_access_out)
{
gboolean home_access = FALSE;
FlatpakFilesystemMode fs_mode, os_mode, etc_mode, home_mode;
GHashTableIter iter;
gpointer key, value;
fs_mode = GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "host"));
if (fs_mode != FLATPAK_FILESYSTEM_MODE_NONE)
{
DIR *dir;
struct dirent *dirent;
g_debug ("Allowing host-fs access");
home_access = TRUE;
/* Bind mount most dirs in / into the new root */
dir = opendir ("/");
if (dir != NULL)
{
while ((dirent = readdir (dir)))
{
g_autofree char *path = NULL;
if (g_strv_contains (dont_mount_in_root, dirent->d_name))
continue;
path = g_build_filename ("/", dirent->d_name, NULL);
flatpak_exports_add_path_expose (exports, fs_mode, path);
}
closedir (dir);
}
flatpak_exports_add_path_expose (exports, fs_mode, "/run/media");
}
os_mode = MAX (GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "host-os")),
fs_mode);
if (os_mode != FLATPAK_FILESYSTEM_MODE_NONE)
flatpak_exports_add_host_os_expose (exports, os_mode);
etc_mode = MAX (GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "host-etc")),
fs_mode);
if (etc_mode != FLATPAK_FILESYSTEM_MODE_NONE)
flatpak_exports_add_host_etc_expose (exports, etc_mode);
home_mode = GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "home"));
if (home_mode != FLATPAK_FILESYSTEM_MODE_NONE)
{
g_debug ("Allowing homedir access");
home_access = TRUE;
flatpak_exports_add_path_expose (exports, MAX (home_mode, fs_mode), g_get_home_dir ());
}
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *filesystem = key;
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
if (g_strv_contains (flatpak_context_special_filesystems, filesystem))
continue;
if (g_str_has_prefix (filesystem, "xdg-"))
{
const char *path, *rest = NULL;
const char *config_key = NULL;
g_autofree char *subpath = NULL;
if (!get_xdg_user_dir_from_string (filesystem, &config_key, &rest, &path))
{
g_warning ("Unsupported xdg dir %s", filesystem);
continue;
}
if (path == NULL)
continue; /* Unconfigured, ignore */
if (strcmp (path, g_get_home_dir ()) == 0)
{
/* xdg-user-dirs sets disabled dirs to $HOME, and its in general not a good
idea to set full access to $HOME other than explicitly, so we ignore
these */
g_debug ("Xdg dir %s is $HOME (i.e. disabled), ignoring", filesystem);
continue;
}
subpath = g_build_filename (path, rest, NULL);
if (mode == FLATPAK_FILESYSTEM_MODE_CREATE && do_create)
g_mkdir_with_parents (subpath, 0755);
if (g_file_test (subpath, G_FILE_TEST_EXISTS))
{
if (config_key && xdg_dirs_conf)
g_string_append_printf (xdg_dirs_conf, "%s=\"%s\"\n",
config_key, path);
flatpak_exports_add_path_expose_or_hide (exports, mode, subpath);
}
}
else if (g_str_has_prefix (filesystem, "~/"))
{
g_autofree char *path = NULL;
path = g_build_filename (g_get_home_dir (), filesystem + 2, NULL);
if (mode == FLATPAK_FILESYSTEM_MODE_CREATE && do_create)
g_mkdir_with_parents (path, 0755);
if (g_file_test (path, G_FILE_TEST_EXISTS))
flatpak_exports_add_path_expose_or_hide (exports, mode, path);
}
else if (g_str_has_prefix (filesystem, "/"))
{
if (mode == FLATPAK_FILESYSTEM_MODE_CREATE && do_create)
g_mkdir_with_parents (filesystem, 0755);
if (g_file_test (filesystem, G_FILE_TEST_EXISTS))
flatpak_exports_add_path_expose_or_hide (exports, mode, filesystem);
}
else
{
g_warning ("Unexpected filesystem arg %s", filesystem);
}
}
if (app_id_dir)
{
g_autoptr(GFile) apps_dir = g_file_get_parent (app_id_dir);
int i;
/* Hide the .var/app dir by default (unless explicitly made visible) */
flatpak_exports_add_path_tmpfs (exports, flatpak_file_get_path_cached (apps_dir));
/* But let the app write to the per-app dir in it */
flatpak_exports_add_path_expose (exports, FLATPAK_FILESYSTEM_MODE_READ_WRITE,
flatpak_file_get_path_cached (app_id_dir));
if (extra_app_id_dirs != NULL)
{
for (i = 0; i < extra_app_id_dirs->len; i++)
{
GFile *extra_app_id_dir = g_ptr_array_index (extra_app_id_dirs, i);
flatpak_exports_add_path_expose (exports, FLATPAK_FILESYSTEM_MODE_READ_WRITE,
flatpak_file_get_path_cached (extra_app_id_dir));
}
}
}
if (home_access_out != NULL)
*home_access_out = home_access;
}
FlatpakExports *
flatpak_context_get_exports (FlatpakContext *context,
const char *app_id)
{
g_autoptr(FlatpakExports) exports = flatpak_exports_new ();
g_autoptr(GFile) app_id_dir = flatpak_get_data_dir (app_id);
flatpak_context_export (context, exports, app_id_dir, NULL, FALSE, NULL, NULL);
return g_steal_pointer (&exports);
}
FlatpakRunFlags
flatpak_context_get_run_flags (FlatpakContext *context)
{
FlatpakRunFlags flags = 0;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_DEVEL))
flags |= FLATPAK_RUN_FLAG_DEVEL;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_MULTIARCH))
flags |= FLATPAK_RUN_FLAG_MULTIARCH;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_BLUETOOTH))
flags |= FLATPAK_RUN_FLAG_BLUETOOTH;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_CANBUS))
flags |= FLATPAK_RUN_FLAG_CANBUS;
return flags;
}
void
flatpak_context_append_bwrap_filesystem (FlatpakContext *context,
FlatpakBwrap *bwrap,
const char *app_id,
GFile *app_id_dir,
GPtrArray *extra_app_id_dirs,
FlatpakExports **exports_out)
{
g_autoptr(FlatpakExports) exports = flatpak_exports_new ();
g_autoptr(GString) xdg_dirs_conf = g_string_new ("");
g_autoptr(GFile) user_flatpak_dir = NULL;
gboolean home_access = FALSE;
GHashTableIter iter;
gpointer key, value;
flatpak_context_export (context, exports, app_id_dir, extra_app_id_dirs, TRUE, xdg_dirs_conf, &home_access);
if (app_id_dir != NULL)
flatpak_run_apply_env_appid (bwrap, app_id_dir);
if (!home_access)
{
/* Enable persistent mapping only if no access to real home dir */
g_hash_table_iter_init (&iter, context->persistent);
while (g_hash_table_iter_next (&iter, &key, NULL))
{
const char *persist = key;
g_autofree char *src = g_build_filename (g_get_home_dir (), ".var/app", app_id, persist, NULL);
g_autofree char *dest = g_build_filename (g_get_home_dir (), persist, NULL);
g_mkdir_with_parents (src, 0755);
flatpak_bwrap_add_bind_arg (bwrap, "--bind", src, dest);
}
}
if (app_id_dir != NULL)
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *run_user_app_dst = g_strdup_printf ("/run/user/%d/app/%s", getuid (), app_id);
g_autofree char *run_user_app_src = g_build_filename (user_runtime_dir, "app", app_id, NULL);
if (glnx_shutil_mkdir_p_at (AT_FDCWD,
run_user_app_src,
0700,
NULL,
NULL))
flatpak_bwrap_add_args (bwrap,
"--bind", run_user_app_src, run_user_app_dst,
NULL);
}
/* Hide the flatpak dir by default (unless explicitly made visible) */
user_flatpak_dir = flatpak_get_user_base_dir_location ();
flatpak_exports_add_path_tmpfs (exports, flatpak_file_get_path_cached (user_flatpak_dir));
/* Ensure we always have a homedir */
flatpak_exports_add_path_dir (exports, g_get_home_dir ());
/* This actually outputs the args for the hide/expose operations above */
flatpak_exports_append_bwrap_args (exports, bwrap);
/* Special case subdirectories of the cache, config and data xdg
* dirs. If these are accessible explicitly, then we bind-mount
* these in the app-id dir. This allows applications to explicitly
* opt out of keeping some config/cache/data in the app-specific
* directory.
*/
if (app_id_dir)
{
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *filesystem = key;
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
g_autofree char *xdg_path = NULL;
const char *rest, *where;
xdg_path = get_xdg_dir_from_string (filesystem, &rest, &where);
if (xdg_path != NULL && *rest != 0 &&
mode >= FLATPAK_FILESYSTEM_MODE_READ_ONLY)
{
g_autoptr(GFile) app_version = g_file_get_child (app_id_dir, where);
g_autoptr(GFile) app_version_subdir = g_file_resolve_relative_path (app_version, rest);
if (g_file_test (xdg_path, G_FILE_TEST_IS_DIR) ||
g_file_test (xdg_path, G_FILE_TEST_IS_REGULAR))
{
g_autofree char *xdg_path_in_app = g_file_get_path (app_version_subdir);
flatpak_bwrap_add_bind_arg (bwrap,
mode == FLATPAK_FILESYSTEM_MODE_READ_ONLY ? "--ro-bind" : "--bind",
xdg_path, xdg_path_in_app);
}
}
}
}
if (home_access && app_id_dir != NULL)
{
g_autofree char *src_path = g_build_filename (g_get_user_config_dir (),
"user-dirs.dirs",
NULL);
g_autofree char *path = g_build_filename (flatpak_file_get_path_cached (app_id_dir),
"config/user-dirs.dirs", NULL);
if (g_file_test (src_path, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_bind_arg (bwrap, "--ro-bind", src_path, path);
}
else if (xdg_dirs_conf->len > 0 && app_id_dir != NULL)
{
g_autofree char *path =
g_build_filename (flatpak_file_get_path_cached (app_id_dir),
"config/user-dirs.dirs", NULL);
flatpak_bwrap_add_args_data (bwrap, "xdg-config-dirs",
xdg_dirs_conf->str, xdg_dirs_conf->len, path, NULL);
}
if (exports_out)
*exports_out = g_steal_pointer (&exports);
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1907_0 |
crossvul-cpp_data_good_1003_1 | /***********************************************************************
* *
* This software is part of the ast package *
* Copyright (c) 1982-2013 AT&T Intellectual Property *
* and is licensed under the *
* Eclipse Public License, Version 1.0 *
* by AT&T Intellectual Property *
* *
* A copy of the License is available at *
* http://www.eclipse.org/org/documents/epl-v10.html *
* (with md5 checksum b35adb5213ca9657e911e9befb180842) *
* *
* Information and Software Systems Research *
* AT&T Research *
* Florham Park NJ *
* *
* David Korn <dgkorn@gmail.com> *
* *
***********************************************************************/
//
// Shell arithmetic - uses streval library
// David Korn
// AT&T Labs
//
#include "config_ast.h" // IWYU pragma: keep
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "ast.h"
#include "builtins.h"
#include "cdt.h"
#include "defs.h"
#include "error.h"
#include "lexstates.h"
#include "name.h"
#include "sfio.h"
#include "shcmd.h"
#include "stk.h"
#include "streval.h"
#include "variables.h"
#ifndef LLONG_MAX
#define LLONG_MAX LONG_MAX
#endif
typedef Sfdouble_t (*Math_f)(Sfdouble_t, ...);
extern const Namdisc_t ENUM_disc;
static bool Varsubscript;
static Sfdouble_t NaN, Inf, Fun;
static Namval_t Infnod = {.nvname = "Inf"};
static Namval_t NaNnod = {.nvname = "NaN"};
static Namval_t FunNode = {.nvname = "?"};
struct Mathconst {
char name[9];
Sfdouble_t value;
};
#ifndef M_1_PIl
#define M_1_PIl 0.3183098861837906715377675267450287L
#endif
#ifndef M_2_PIl
#define M_2_PIl 0.6366197723675813430755350534900574L
#endif
#ifndef M_2_SQRTPIl
#define M_2_SQRTPIl 1.1283791670955125738961589031215452L
#endif
#ifndef M_El
#define M_El 2.7182818284590452353602874713526625L
#endif
#ifndef M_LOG2El
#define M_LOG2El 1.4426950408889634073599246810018921L
#endif
#ifndef M_LOG10El
#define M_LOG10El 0.4342944819032518276511289189166051L
#endif
#ifndef M_LN2l
#define M_LN2l 0.6931471805599453094172321214581766L
#endif
#ifndef M_LN10l
#define M_LN10l 2.3025850929940456840179914546843642L
#endif
#ifndef M_PIl
#define M_PIl 3.1415926535897932384626433832795029L
#endif
#ifndef M_PI_2l
#define M_PI_2l 1.5707963267948966192313216916397514L
#endif
#ifndef M_PI_4l
#define M_PI_4l 0.7853981633974483096156608458198757L
#endif
#ifndef M_SQRT2l
#define M_SQRT2l 1.4142135623730950488016887242096981L
#endif
#ifndef M_SQRT1_2l
#define M_SQRT1_2l 0.7071067811865475244008443621048490L
#endif
// The first three entries cann't be moved or it will break the code.
static const struct Mathconst Mtable[] = {
{"1_PI", M_1_PIl}, {"2_PI", M_2_PIl}, {"2_SQRTPI", M_2_SQRTPIl},
{"E", M_El}, {"LOG2E", M_LOG2El}, {"LOG10E", M_LOG10El},
{"LN2", M_LN2l}, {"PI", M_PIl}, {"PI_2", M_PI_2l},
{"PI_4", M_PI_4l}, {"SQRT2", M_SQRT2l}, {"SQRT1_2", M_SQRT1_2l},
{"", 0.0}};
static_fn Namval_t *scope(Namval_t *np, struct lval *lvalue, int assign) {
int flag = lvalue->flag;
char *sub = 0, *cp = (char *)np;
Namval_t *mp;
Shell_t *shp = lvalue->shp;
int c = 0, nosub = lvalue->nosub;
Dt_t *sdict = (shp->st.real_fun ? shp->st.real_fun->sdict : 0);
Dt_t *nsdict = (shp->namespace ? nv_dict(shp->namespace) : 0);
Dt_t *root = shp->var_tree;
nvflag_t nvflags = assign ? NV_ASSIGN : 0;
lvalue->nosub = 0;
if (nosub < 0 && lvalue->ovalue) return (Namval_t *)lvalue->ovalue;
lvalue->ovalue = NULL;
if (cp >= lvalue->expr && cp < lvalue->expr + lvalue->elen) {
int offset;
// Do binding to node now.
int d = cp[flag];
cp[flag] = 0;
np = nv_open(cp, root, nvflags | NV_VARNAME | NV_NOADD | NV_NOFAIL);
if ((!np || nv_isnull(np)) && sh_macfun(shp, cp, offset = stktell(shp->stk))) {
Fun = sh_arith(shp, sub = stkptr(shp->stk, offset));
STORE_VT(FunNode.nvalue, sfdoublep, &Fun);
FunNode.nvshell = shp;
nv_onattr(&FunNode, NV_NOFREE | NV_LDOUBLE | NV_RDONLY);
cp[flag] = d;
return &FunNode;
}
if (!np && assign) {
np = nv_open(cp, root, nvflags | NV_VARNAME);
}
cp[flag] = d;
if (!np) return 0;
root = shp->last_root;
if (cp[flag + 1] == '[') {
flag++;
} else {
flag = 0;
}
}
if ((lvalue->emode & ARITH_COMP) && dtvnext(root)) {
mp = nv_search_namval(np, sdict ? sdict : root, NV_NOSCOPE);
if (!mp && nsdict) mp = nv_search_namval(np, nsdict, 0);
if (mp) np = mp;
}
while (nv_isref(np)) {
sub = nv_refsub(np);
np = nv_refnode(np);
if (sub) nv_putsub(np, sub, 0, assign ? ARRAY_ADD : 0);
}
if (!nosub && flag) {
int hasdot = 0;
cp = (char *)&lvalue->expr[flag];
if (sub) goto skip;
sub = cp;
while (1) {
Namarr_t *ap;
Namval_t *nq;
cp = nv_endsubscript(np, cp, 0, shp);
if (c || *cp == '.') {
c = '.';
while (*cp == '.') {
hasdot = 1;
cp++;
while (c = mb1char(&cp), isaname(c)) {
; // empty body
}
}
if (c == '[') continue;
}
flag = *cp;
*cp = 0;
if (c || hasdot) {
sfprintf(shp->strbuf, "%s%s%c", nv_name(np), sub, 0);
sub = sfstruse(shp->strbuf);
}
if (strchr(sub, '$')) sub = sh_mactrim(shp, sub, 0);
*cp = flag;
if (c || hasdot) {
np = nv_open(sub, shp->var_tree, NV_VARNAME | nvflags);
return np;
}
cp = nv_endsubscript(np, sub, (assign ? NV_ADD : 0) | NV_SUBQUOTE, np->nvshell);
if (*cp != '[') break;
skip:
nq = nv_opensub(np);
if (nq) {
np = nq;
} else {
ap = nv_arrayptr(np);
if (ap && !ap->table) {
ap->table = dtopen(&_Nvdisc, Dtoset);
dtuserdata(ap->table, shp, 1);
}
if (ap && ap->table && (nq = nv_search(nv_getsub(np), ap->table, NV_ADD))) {
nq->nvenv = np;
}
if (nq && nv_isnull(nq)) np = nv_arraychild(np, nq, 0);
}
sub = cp;
}
} else if (nosub > 0) {
nv_putsub(np, NULL, nosub - 1, 0);
}
return np;
}
Math_f sh_mathstdfun(const char *fname, size_t fsize, short *nargs) {
const struct mathtab *tp;
char c = fname[0];
for (tp = shtab_math; *tp->fname; tp++) {
if (*tp->fname > c) break;
if (tp->fname[1] == c && tp->fname[fsize + 1] == 0 &&
strncmp(&tp->fname[1], fname, fsize) == 0) {
if (nargs) *nargs = *tp->fname;
return tp->fnptr;
}
}
return NULL;
}
int sh_mathstd(const char *name) { return sh_mathstdfun(name, strlen(name), NULL) != 0; }
static_fn Sfdouble_t number(const char *s, char **p, int b, struct lval *lvalue) {
Sfdouble_t r;
char *t;
int oerrno;
int c;
char base;
struct lval v;
oerrno = errno;
errno = 0;
base = b;
if (!lvalue) {
lvalue = &v;
} else if (lvalue->shp->bltindata.bnode == SYSLET && !sh_isoption(lvalue->shp, SH_LETOCTAL)) {
while (*s == '0' && isdigit(s[1])) s++;
}
lvalue->eflag = 0;
lvalue->isfloat = 0;
r = strton64(s, &t, &base, -1);
if (*t == '8' || *t == '9') {
base = 10;
errno = 0;
r = strton64(s, &t, &base, -1);
}
if (base <= 1) base = 10;
if (*t == '_') {
if ((r == 1 || r == 2) && strcmp(t, "_PI") == 0) {
t += 3;
r = Mtable[(int)r - 1].value;
} else if (r == 2 && strcmp(t, "_SQRTPI") == 0) {
t += 7;
r = Mtable[2].value;
}
}
c = r == LLONG_MAX && errno ? 'e' : *t;
if (c == getdecimal() || c == 'e' || c == 'E' || (base == 16 && (c == 'p' || c == 'P'))) {
r = strtold(s, &t);
lvalue->isfloat = TYPE_LD;
}
if (t > s) {
if (*t == 'f' || *t == 'F') {
t++;
lvalue->isfloat = TYPE_F;
r = (float)r;
} else if (*t == 'l' || *t == 'L') {
t++;
lvalue->isfloat = TYPE_LD;
} else if (*t == 'd' || *t == 'D') {
t++;
lvalue->isfloat = TYPE_LD;
r = (double)r;
}
}
errno = oerrno;
*p = t;
return r;
}
static_fn Sfdouble_t arith(const char **ptr, struct lval *lvalue, int type, Sfdouble_t n) {
Shell_t *shp = lvalue->shp;
Sfdouble_t r = 0;
char *str = (char *)*ptr;
char *cp;
switch (type) {
case ASSIGN: {
Namval_t *np = (Namval_t *)(lvalue->value);
np = scope(np, lvalue, 1);
nv_putval(np, (char *)&n, NV_LDOUBLE);
if (lvalue->eflag) lvalue->ptr = nv_hasdisc(np, &ENUM_disc);
lvalue->eflag = 0;
r = nv_getnum(np);
lvalue->value = (char *)np;
break;
}
case LOOKUP: {
int c = *str;
char *xp = str;
lvalue->value = NULL;
if (c == '.') str++;
c = mb1char(&str);
if (isaletter(c)) {
Namval_t *np = NULL;
int dot = 0;
while (1) {
xp = str;
while (c = mb1char(&str), isaname(c)) xp = str;
str = xp;
while (c == '[' && dot == NV_NOADD) {
str = nv_endsubscript(NULL, str, 0, shp);
c = *str;
}
if (c != '.') break;
dot = NV_NOADD;
c = *++str;
if (c != '[') continue;
str = nv_endsubscript(NULL, cp = str, NV_SUBQUOTE, shp) - 1;
if (sh_checkid(cp + 1, NULL)) str -= 2;
}
if (c == '(') {
int off = stktell(shp->stk);
int fsize = str - (char *)(*ptr);
const struct mathtab *tp;
Namval_t *nq;
lvalue->fun = NULL;
sfprintf(shp->stk, ".sh.math.%.*s%c", fsize, *ptr, 0);
stkseek(shp->stk, off);
nq = nv_search(stkptr(shp->stk, off), shp->fun_tree, 0);
if (nq) {
struct Ufunction *rp = FETCH_VT(nq->nvalue, rp);
lvalue->nargs = -rp->argc;
lvalue->fun = (Math_f)nq;
break;
}
if (fsize <= (sizeof(tp->fname) - 2)) {
lvalue->fun = (Math_f)sh_mathstdfun(*ptr, fsize, &lvalue->nargs);
}
if (lvalue->fun) break;
if (lvalue->emode & ARITH_COMP) {
lvalue->value = (char *)e_function;
} else {
lvalue->value = (char *)ERROR_dictionary(e_function);
}
return r;
}
if ((lvalue->emode & ARITH_COMP) && dot) {
lvalue->value = (char *)*ptr;
lvalue->flag = str - lvalue->value;
break;
}
*str = 0;
if (sh_isoption(shp, SH_NOEXEC)) {
np = VAR_underscore;
} else {
int offset = stktell(shp->stk);
char *saveptr = stkfreeze(shp->stk, 0);
Dt_t *root = (lvalue->emode & ARITH_COMP) ? shp->var_base : shp->var_tree;
*str = c;
cp = str;
while (c == '[' || c == '.') {
if (c == '[') {
str = nv_endsubscript(np, str, 0, shp);
c = *str;
if (c != '[' && c != '.') {
str = cp;
c = '[';
break;
}
} else {
dot = NV_NOADD | NV_NOFAIL;
str++;
xp = str;
while (c = mb1char(&str), isaname(c)) xp = str;
str = xp;
}
}
*str = 0;
cp = (char *)*ptr;
Varsubscript = false;
if ((cp[0] == 'i' || cp[0] == 'I') && (cp[1] == 'n' || cp[1] == 'N') &&
(cp[2] == 'f' || cp[2] == 'F') && cp[3] == 0) {
Inf = strtold("Inf", NULL);
STORE_VT(Infnod.nvalue, sfdoublep, &Inf);
np = &Infnod;
np->nvshell = shp;
nv_onattr(np, NV_NOFREE | NV_LDOUBLE | NV_RDONLY);
} else if ((cp[0] == 'n' || cp[0] == 'N') && (cp[1] == 'a' || cp[1] == 'A') &&
(cp[2] == 'n' || cp[2] == 'N') && cp[3] == 0) {
NaN = strtold("NaN", NULL);
STORE_VT(NaNnod.nvalue, sfdoublep, &NaN);
np = &NaNnod;
np->nvshell = shp;
nv_onattr(np, NV_NOFREE | NV_LDOUBLE | NV_RDONLY);
} else {
const struct Mathconst *mp = NULL;
np = NULL;
if (strchr("ELPS12", **ptr)) {
for (mp = Mtable; *mp->name; mp++) {
if (strcmp(mp->name, *ptr) == 0) break;
}
}
if (mp && *mp->name) {
r = mp->value;
lvalue->isfloat = TYPE_LD;
goto skip2;
}
if (shp->namref_root && !(lvalue->emode & ARITH_COMP)) {
np = nv_open(*ptr, shp->namref_root,
NV_NOREF | NV_VARNAME | NV_NOSCOPE | NV_NOADD | dot);
}
if (!np) {
np = nv_open(*ptr, root, NV_NOREF | NV_VARNAME | dot);
}
if (!np || Varsubscript) {
np = NULL;
lvalue->value = (char *)*ptr;
lvalue->flag = str - lvalue->value;
}
}
skip2:
if (saveptr != stkptr(shp->stk, 0)) {
stkset(shp->stk, saveptr, offset);
} else {
stkseek(shp->stk, offset);
}
}
*str = c;
if (lvalue->isfloat == TYPE_LD) break;
if (!np) break; // this used to also test `&& lvalue->value` but that's redundant
lvalue->value = (char *)np;
// Bind subscript later.
if (nv_isattr(np, NV_DOUBLE) == NV_DOUBLE) lvalue->isfloat = 1;
lvalue->flag = 0;
if (c == '[') {
lvalue->flag = (str - lvalue->expr);
do {
while (c == '.') {
str++;
while (xp = str, c = mb1char(&str), isaname(c)) {
; // empty body
}
c = *(str = xp);
}
if (c == '[') str = nv_endsubscript(np, str, 0, np->nvshell);
c = *str;
} while (c == '[' || c == '.');
break;
}
} else {
r = number(xp, &str, 0, lvalue);
}
break;
}
case VALUE: {
Namval_t *np = (Namval_t *)(lvalue->value);
Namarr_t *ap;
if (sh_isoption(shp, SH_NOEXEC)) return 0;
np = scope(np, lvalue, 0);
if (!np) {
if (sh_isoption(shp, SH_NOUNSET)) {
*ptr = lvalue->value;
goto skip;
}
return 0;
}
lvalue->ovalue = (char *)np;
if (lvalue->eflag) {
lvalue->ptr = nv_hasdisc(np, &ENUM_disc);
} else if ((Namfun_t *)lvalue->ptr && !nv_hasdisc(np, &ENUM_disc) &&
!nv_isattr(np, NV_INTEGER)) {
// TODO: The calloc() below should be considered a bandaid and may not be correct.
// See https://github.com/att/ast/issues/980. This dynamic allocation may leak some
// memory but that is preferable to referencing a stack var after this function
// returns. I think I have addressed this by removing the NV_NOFREE flag but I'm
// leaving this comment due to my low confidence.
Namval_t *mp = ((Namfun_t *)lvalue->ptr)->type;
Namval_t *node = calloc(1, sizeof(Namval_t));
nv_clone(mp, node, 0);
nv_offattr(node, NV_NOFREE);
nv_offattr(node, NV_RDONLY);
nv_putval(node, np->nvname, 0);
if (nv_isattr(node, NV_NOFREE)) return nv_getnum(node);
}
lvalue->eflag = 0;
if (((lvalue->emode & 2) || lvalue->level > 1 ||
(lvalue->nextop != A_STORE && sh_isoption(shp, SH_NOUNSET))) &&
nv_isnull(np) && !nv_isattr(np, NV_INTEGER)) {
*ptr = nv_name(np);
skip:
lvalue->value = (char *)ERROR_dictionary(e_notset);
lvalue->emode |= 010;
return 0;
}
if (lvalue->userfn) {
ap = nv_arrayptr(np);
if (ap && (ap->flags & ARRAY_UNDEF)) {
r = (Sfdouble_t)(uintptr_t)np;
lvalue->isfloat = 5;
return r;
}
}
r = nv_getnum(np);
if (nv_isattr(np, NV_INTEGER | NV_BINARY) == (NV_INTEGER | NV_BINARY)) {
lvalue->isfloat = (r != (Sflong_t)r) ? TYPE_LD : 0;
} else if (nv_isattr(np, (NV_DOUBLE | NV_SHORT)) == (NV_DOUBLE | NV_SHORT)) {
lvalue->isfloat = TYPE_F;
r = (float)r;
} else if (nv_isattr(np, (NV_DOUBLE | NV_LONG)) == (NV_DOUBLE | NV_LONG)) {
lvalue->isfloat = TYPE_LD;
} else if (nv_isattr(np, NV_DOUBLE) == NV_DOUBLE) {
lvalue->isfloat = TYPE_D;
r = (double)r;
}
if ((lvalue->emode & ARITH_ASSIGNOP) && nv_isarray(np)) {
lvalue->nosub = nv_aindex(np) + 1;
}
return r;
}
case MESSAGE: {
sfsync(NULL);
if (lvalue->emode & ARITH_COMP) return -1;
errormsg(SH_DICT, ERROR_exit((lvalue->emode & 3) != 0), lvalue->value, *ptr);
}
}
*ptr = str;
return r;
}
Sfdouble_t sh_arith(Shell_t *shp, const char *str) { return sh_strnum(shp, str, NULL, 1); }
void *sh_arithcomp(Shell_t *shp, char *str) {
const char *ptr = str;
Arith_t *ep;
ep = arith_compile(shp, str, (char **)&ptr, arith, ARITH_COMP | 1);
if (*ptr) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *ptr, str);
return ep;
}
// Convert number defined by string to a Sfdouble_t.
// Ptr is set to the last character processed.
// If mode>0, an error will be fatal with value <mode>.
Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {
Sfdouble_t d;
char *last;
if (*str == 0) {
d = 0.0;
last = (char *)str;
} else {
d = number(str, &last, shp->inarith ? 0 : 10, NULL);
if (*last && !shp->inarith && sh_isstate(shp, SH_INIT)) {
// This call is to handle "base#value" literals if we're importing untrusted env vars.
d = number(str, &last, 0, NULL);
}
if (*last) {
if (sh_isstate(shp, SH_INIT)) {
// Initializing means importing untrusted env vars. Since the string does not appear
// to be a recognized numeric literal give up. We can't safely call strval() since
// that allows arbitrary expressions which would create a security vulnerability.
d = 0.0;
} else {
if (*last != '.' || last[1] != '.') {
d = strval(shp, str, &last, arith, mode);
Varsubscript = true;
}
if (!ptr && *last && mode > 0) {
errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);
}
}
} else if (d == 0.0 && *str == '-') {
d = -0.0;
}
}
if (ptr) *ptr = last;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1003_1 |
crossvul-cpp_data_bad_433_0 | // SPDX-License-Identifier: GPL-3.0-or-later
#include "../libnetdata.h"
// ----------------------------------------------------------------------------
// URL encode / decode
// code from: http://www.geekhideout.com/urlcode.shtml
/* Converts a hex character to its integer value */
char from_hex(char ch) {
return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10);
}
/* Converts an integer value to its hex character*/
char to_hex(char code) {
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *url_encode(char *str) {
char *buf, *pbuf;
pbuf = buf = mallocz(strlen(str) * 3 + 1);
while (*str) {
if (isalnum(*str) || *str == '-' || *str == '_' || *str == '.' || *str == '~')
*pbuf++ = *str;
else if (*str == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*str >> 4), *pbuf++ = to_hex(*str & 15);
str++;
}
*pbuf = '\0';
pbuf = strdupz(buf);
freez(buf);
return pbuf;
}
/* Returns a url-decoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *url_decode(char *str) {
size_t size = strlen(str) + 1;
char *buf = mallocz(size);
return url_decode_r(buf, str, size);
}
char *url_decode_r(char *to, char *url, size_t size) {
char *s = url, // source
*d = to, // destination
*e = &to[size - 1]; // destination end
while(*s && d < e) {
if(unlikely(*s == '%')) {
if(likely(s[1] && s[2])) {
*d++ = from_hex(s[1]) << 4 | from_hex(s[2]);
s += 2;
}
}
else if(unlikely(*s == '+'))
*d++ = ' ';
else
*d++ = *s;
s++;
}
*d = '\0';
return to;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_433_0 |
crossvul-cpp_data_good_433_0 | // SPDX-License-Identifier: GPL-3.0-or-later
#include "../libnetdata.h"
// ----------------------------------------------------------------------------
// URL encode / decode
// code from: http://www.geekhideout.com/urlcode.shtml
/* Converts a hex character to its integer value */
char from_hex(char ch) {
return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10);
}
/* Converts an integer value to its hex character*/
char to_hex(char code) {
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *url_encode(char *str) {
char *buf, *pbuf;
pbuf = buf = mallocz(strlen(str) * 3 + 1);
while (*str) {
if (isalnum(*str) || *str == '-' || *str == '_' || *str == '.' || *str == '~')
*pbuf++ = *str;
else if (*str == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*str >> 4), *pbuf++ = to_hex(*str & 15);
str++;
}
*pbuf = '\0';
pbuf = strdupz(buf);
freez(buf);
return pbuf;
}
/* Returns a url-decoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *url_decode(char *str) {
size_t size = strlen(str) + 1;
char *buf = mallocz(size);
return url_decode_r(buf, str, size);
}
char *url_decode_r(char *to, char *url, size_t size) {
char *s = url, // source
*d = to, // destination
*e = &to[size - 1]; // destination end
while(*s && d < e) {
if(unlikely(*s == '%')) {
if(likely(s[1] && s[2])) {
char t = from_hex(s[1]) << 4 | from_hex(s[2]);
// avoid HTTP header injection
*d++ = (char)((isprint(t))? t : ' ');
s += 2;
}
}
else if(unlikely(*s == '+'))
*d++ = ' ';
else
*d++ = *s;
s++;
}
*d = '\0';
return to;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_433_0 |
crossvul-cpp_data_bad_1908_0 | /*
* Copyright © 2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
/* NOTE: This code was copied mostly as-is from xdg-desktop-portal */
#include <locale.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
#include <gio/gdesktopappinfo.h>
#include "flatpak-portal-dbus.h"
#include "flatpak-portal.h"
#include "flatpak-dir-private.h"
#include "flatpak-utils-private.h"
#include "flatpak-transaction.h"
#include "flatpak-installation-private.h"
#include "flatpak-instance-private.h"
#include "flatpak-portal-app-info.h"
#include "flatpak-portal-error.h"
#include "flatpak-utils-base-private.h"
#include "portal-impl.h"
#include "flatpak-permission-dbus.h"
/* GLib 2.47.92 was the first release to define these in gdbus-codegen */
#if !GLIB_CHECK_VERSION (2, 47, 92)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakSkeleton, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorSkeleton, g_object_unref)
#endif
#define IDLE_TIMEOUT_SECS 10 * 60
/* Should be roughly 2 seconds */
#define CHILD_STATUS_CHECK_ATTEMPTS 20
static GHashTable *client_pid_data_hash = NULL;
static GDBusConnection *session_bus = NULL;
static GNetworkMonitor *network_monitor = NULL;
static gboolean no_idle_exit = FALSE;
static guint name_owner_id = 0;
static GMainLoop *main_loop;
static PortalFlatpak *portal;
static gboolean opt_verbose;
static int opt_poll_timeout;
static gboolean opt_poll_when_metered;
static FlatpakSpawnSupportFlags supports = 0;
G_LOCK_DEFINE (update_monitors); /* This protects the three variables below */
static GHashTable *update_monitors;
static guint update_monitors_timeout = 0;
static gboolean update_monitors_timeout_running_thread = FALSE;
/* Poll all update monitors twice an hour */
#define DEFAULT_UPDATE_POLL_TIMEOUT_SEC (30 * 60)
#define PERMISSION_TABLE "flatpak"
#define PERMISSION_ID "updates"
/* Instance IDs are 32-bit unsigned integers */
#define INSTANCE_ID_BUFFER_SIZE 16
typedef enum { UNSET, ASK, YES, NO } Permission;
typedef enum {
PROGRESS_STATUS_RUNNING = 0,
PROGRESS_STATUS_EMPTY = 1,
PROGRESS_STATUS_DONE = 2,
PROGRESS_STATUS_ERROR = 3
} UpdateStatus;
static XdpDbusPermissionStore *permission_store;
typedef struct {
GMutex lock; /* This protects the closed, running and installed state */
gboolean closed;
gboolean running; /* While this is set, don't close the monitor */
gboolean installing;
char *sender;
char *obj_path;
GCancellable *cancellable;
/* Static data */
char *name;
char *arch;
char *branch;
char *commit;
char *app_path;
/* Last reported values, starting at the instance commit */
char *reported_local_commit;
char *reported_remote_commit;
} UpdateMonitorData;
static gboolean check_all_for_updates_cb (void *data);
static gboolean has_update_monitors (void);
static UpdateMonitorData *update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor);
static gboolean handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation);
static gboolean handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options);
static void
skeleton_died_cb (gpointer data)
{
g_debug ("skeleton finalized, exiting");
g_main_loop_quit (main_loop);
}
static gboolean
unref_skeleton_in_timeout_cb (gpointer user_data)
{
static gboolean unreffed = FALSE;
g_debug ("unreffing portal main ref");
if (!unreffed)
{
g_object_unref (portal);
unreffed = TRUE;
}
return G_SOURCE_REMOVE;
}
static void
unref_skeleton_in_timeout (void)
{
if (name_owner_id)
g_bus_unown_name (name_owner_id);
name_owner_id = 0;
/* After we've lost the name or idled we drop the main ref on the helper
so that we'll exit when it drops to zero. However, if there are
outstanding calls these will keep the refcount up during the
execution of them. We do the unref on a timeout to make sure
we're completely draining the queue of (stale) requests. */
g_timeout_add (500, unref_skeleton_in_timeout_cb, NULL);
}
static guint idle_timeout_id = 0;
static gboolean
idle_timeout_cb (gpointer user_data)
{
if (name_owner_id &&
g_hash_table_size (client_pid_data_hash) == 0 &&
!has_update_monitors ())
{
g_debug ("Idle - unowning name");
unref_skeleton_in_timeout ();
}
idle_timeout_id = 0;
return G_SOURCE_REMOVE;
}
G_LOCK_DEFINE_STATIC (idle);
static void
schedule_idle_callback (void)
{
G_LOCK (idle);
if (!no_idle_exit)
{
if (idle_timeout_id != 0)
g_source_remove (idle_timeout_id);
idle_timeout_id = g_timeout_add_seconds (IDLE_TIMEOUT_SECS, idle_timeout_cb, NULL);
}
G_UNLOCK (idle);
}
typedef struct
{
GPid pid;
char *client;
guint child_watch;
gboolean watch_bus;
gboolean expose_or_share_pids;
} PidData;
static void
pid_data_free (PidData *data)
{
g_free (data->client);
g_free (data);
}
static void
child_watch_died (GPid pid,
gint status,
gpointer user_data)
{
PidData *pid_data = user_data;
g_autoptr(GVariant) signal_variant = NULL;
g_debug ("Client Pid %d died", pid_data->pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, status));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnExited",
signal_variant,
NULL);
/* This frees the pid_data, so be careful */
g_hash_table_remove (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid));
/* This might have caused us to go to idle (zero children) */
schedule_idle_callback ();
}
typedef struct
{
int from;
int to;
int final;
} FdMapEntry;
typedef struct
{
FdMapEntry *fd_map;
int fd_map_len;
int instance_id_fd;
gboolean set_tty;
int tty;
} ChildSetupData;
typedef struct
{
guint pid;
gchar buffer[INSTANCE_ID_BUFFER_SIZE];
} InstanceIdReadData;
typedef struct
{
FlatpakInstance *instance;
guint pid;
guint attempt;
} BwrapinfoWatcherData;
static void
bwrapinfo_watcher_data_free (BwrapinfoWatcherData* data)
{
g_object_unref (data->instance);
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (BwrapinfoWatcherData, bwrapinfo_watcher_data_free)
static int
get_child_pid_relative_to_parent_sandbox (int pid,
GError **error)
{
g_autofree char *status_file_path = NULL;
g_autoptr(GFile) status_file = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
int relative_pid = 0;
status_file_path = g_strdup_printf ("/proc/%u/status", pid);
status_file = g_file_new_for_path (status_file_path);
input_stream = g_file_read (status_file, NULL, error);
if (input_stream == NULL)
return 0;
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line_utf8 (data_stream, NULL, NULL, error);
if (line == NULL)
break;
g_strchug (line);
if (g_str_has_prefix (line, "NSpid:"))
{
g_auto(GStrv) fields = NULL;
guint nfields = 0;
char *endptr = NULL;
fields = g_strsplit (line, "\t", -1);
nfields = g_strv_length (fields);
if (nfields < 3)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"NSpid line has too few fields: %s", line);
return 0;
}
/* The second to last PID namespace is the one that spawned this process */
relative_pid = strtol (fields[nfields - 2], &endptr, 10);
if (*endptr)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"Invalid parent-relative PID in NSpid line: %s", line);
return 0;
}
return relative_pid;
}
}
if (*error == NULL)
/* EOF was reached while reading the file */
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "NSpid not found");
return 0;
}
static int
check_child_pid_status (void *user_data)
{
/* Stores a sequence of the time interval to use until the child PID is checked again.
In general from testing, bwrapinfo is never ready before 25ms have passed at minimum,
thus 25ms is the first interval, doubling until a max interval of 100ms is reached.
In addition, if the program is not available after 100ms for an extended period of time,
the timeout is further increased to a full second. */
static gint timeouts[] = {25, 50, 100};
g_autoptr(GVariant) signal_variant = NULL;
g_autoptr(BwrapinfoWatcherData) data = user_data;
PidData *pid_data;
guint pid;
int child_pid;
int relative_child_pid = 0;
pid = data->pid;
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (pid));
/* Process likely already exited if pid_data == NULL, so don't send the
signal to avoid an awkward out-of-order SpawnExited -> SpawnStarted. */
if (pid_data == NULL)
{
g_warning ("%u already exited, skipping SpawnStarted", pid);
return G_SOURCE_REMOVE;
}
child_pid = flatpak_instance_get_child_pid (data->instance);
if (child_pid == 0)
{
gint timeout;
gboolean readd_timer = FALSE;
if (data->attempt >= CHILD_STATUS_CHECK_ATTEMPTS)
/* If too many attempts, use a 1 second timeout */
timeout = 1000;
else
timeout = timeouts[MIN (data->attempt, G_N_ELEMENTS (timeouts) - 1)];
g_debug ("Failed to read child PID, trying again in %d ms", timeout);
/* The timer source only needs to be re-added if the timeout has changed,
which won't happen while staying on the 100 or 1000ms timeouts.
This test must happen *before* the attempt counter is incremented, since the
attempt counter represents the *current* timeout. */
readd_timer = data->attempt <= G_N_ELEMENTS (timeouts) || data->attempt == CHILD_STATUS_CHECK_ATTEMPTS;
data->attempt++;
/* Make sure the data isn't destroyed */
data = NULL;
if (readd_timer)
{
g_timeout_add (timeout, check_child_pid_status, user_data);
return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
/* Only send the child PID if it's exposed */
if (pid_data->expose_or_share_pids)
{
g_autoptr(GError) error = NULL;
relative_child_pid = get_child_pid_relative_to_parent_sandbox (child_pid, &error);
if (relative_child_pid == 0)
g_warning ("Failed to find relative PID for %d: %s", child_pid, error->message);
}
g_debug ("Emitting SpawnStarted(%u, %d)", pid, relative_child_pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, relative_child_pid));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnStarted",
signal_variant,
NULL);
return G_SOURCE_REMOVE;
}
static void
instance_id_read_finish (GObject *source,
GAsyncResult *res,
gpointer user_data)
{
g_autoptr(GInputStream) stream = NULL;
g_autofree InstanceIdReadData *data = NULL;
g_autoptr(FlatpakInstance) instance = NULL;
g_autoptr(GError) error = NULL;
BwrapinfoWatcherData *watcher_data = NULL;
gssize bytes_read;
stream = G_INPUT_STREAM (source);
data = (InstanceIdReadData *) user_data;
bytes_read = g_input_stream_read_finish (stream, res, &error);
if (bytes_read <= 0)
{
/* 0 means EOF, so the process could never have been started. */
if (bytes_read == -1)
g_warning ("Failed to read instance id: %s", error->message);
return;
}
data->buffer[bytes_read] = 0;
instance = flatpak_instance_new_for_id (data->buffer);
watcher_data = g_new0 (BwrapinfoWatcherData, 1);
watcher_data->instance = g_steal_pointer (&instance);
watcher_data->pid = data->pid;
check_child_pid_status (watcher_data);
}
static void
drop_cloexec (int fd)
{
fcntl (fd, F_SETFD, 0);
}
static void
child_setup_func (gpointer user_data)
{
ChildSetupData *data = (ChildSetupData *) user_data;
FdMapEntry *fd_map = data->fd_map;
sigset_t set;
int i;
flatpak_close_fds_workaround (3);
if (data->instance_id_fd != -1)
drop_cloexec (data->instance_id_fd);
/* Unblock all signals */
sigemptyset (&set);
if (pthread_sigmask (SIG_SETMASK, &set, NULL) == -1)
{
g_warning ("Failed to unblock signals when starting child");
return;
}
/* Reset the handlers for all signals to their defaults. */
for (i = 1; i < NSIG; i++)
{
if (i != SIGSTOP && i != SIGKILL)
signal (i, SIG_DFL);
}
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from != fd_map[i].to)
{
dup2 (fd_map[i].from, fd_map[i].to);
close (fd_map[i].from);
}
}
/* Second pass in case we needed an in-between fd value to avoid conflicts */
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].to != fd_map[i].final)
{
dup2 (fd_map[i].to, fd_map[i].final);
close (fd_map[i].to);
}
/* Ensure we inherit the final fd value */
drop_cloexec (fd_map[i].final);
}
/* We become our own session and process group, because it never makes sense
to share the flatpak-session-helper dbus activated process group */
setsid ();
setpgid (0, 0);
if (data->set_tty)
{
/* data->tty is our from fd which is closed at this point.
* so locate the destination fd and use it for the ioctl.
*/
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from == data->tty)
{
if (ioctl (fd_map[i].final, TIOCSCTTY, 0) == -1)
g_debug ("ioctl(%d, TIOCSCTTY, 0) failed: %s",
fd_map[i].final, strerror (errno));
break;
}
}
}
}
static gboolean
is_valid_expose (const char *expose,
GError **error)
{
/* No subdirs or absolute paths */
if (expose[0] == '/')
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: absolute paths not allowed");
return FALSE;
}
else if (strchr (expose, '/'))
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: subdirectories not allowed");
return FALSE;
}
return TRUE;
}
static char *
filesystem_arg (const char *path,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
filesystem_sandbox_arg (const char *path,
const char *sandbox,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
g_string_append (s, "/sandbox/");
for (p = sandbox; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
bubblewrap_remap_path (const char *path)
{
if (g_str_has_prefix (path, "/newroot/"))
path = path + strlen ("/newroot");
return g_strdup (path);
}
static char *
verify_proc_self_fd (const char *proc_path,
GError **error)
{
char path_buffer[PATH_MAX + 1];
ssize_t symlink_size;
symlink_size = readlink (proc_path, path_buffer, PATH_MAX);
if (symlink_size < 0)
return glnx_null_throw_errno_prefix (error, "readlink");
path_buffer[symlink_size] = 0;
/* All normal paths start with /, but some weird things
don't, such as socket:[27345] or anon_inode:[eventfd].
We don't support any of these */
if (path_buffer[0] != '/')
return glnx_null_throw (error, "%s resolves to non-absolute path %s",
proc_path, path_buffer);
/* File descriptors to actually deleted files have " (deleted)"
appended to them. This also happens to some fake fd types
like shmem which are "/<name> (deleted)". All such
files are considered invalid. Unfortunatelly this also
matches files with filenames that actually end in " (deleted)",
but there is not much to do about this. */
if (g_str_has_suffix (path_buffer, " (deleted)"))
return glnx_null_throw (error, "%s resolves to deleted path %s",
proc_path, path_buffer);
/* remap from sandbox to host if needed */
return bubblewrap_remap_path (path_buffer);
}
static char *
get_path_for_fd (int fd,
gboolean *writable_out,
GError **error)
{
g_autofree char *proc_path = NULL;
int fd_flags;
struct stat st_buf;
struct stat real_st_buf;
g_autofree char *path = NULL;
gboolean writable = FALSE;
int read_access_mode;
/* Must be able to get fd flags */
fd_flags = fcntl (fd, F_GETFL);
if (fd_flags == -1)
return glnx_null_throw_errno_prefix (error, "fcntl F_GETFL");
/* Must be O_PATH */
if ((fd_flags & O_PATH) != O_PATH)
return glnx_null_throw (error, "not opened with O_PATH");
/* We don't want to allow exposing symlinks, because if they are
* under the callers control they could be changed between now and
* starting the child allowing it to point anywhere, so enforce NOFOLLOW.
* and verify that stat is not a link.
*/
if ((fd_flags & O_NOFOLLOW) != O_NOFOLLOW)
return glnx_null_throw (error, "not opened with O_NOFOLLOW");
/* Must be able to fstat */
if (fstat (fd, &st_buf) < 0)
return glnx_null_throw_errno_prefix (error, "fstat");
/* As per above, no symlinks */
if (S_ISLNK (st_buf.st_mode))
return glnx_null_throw (error, "is a symbolic link");
proc_path = g_strdup_printf ("/proc/self/fd/%d", fd);
/* Must be able to read valid path from /proc/self/fd */
/* This is an absolute and (at least at open time) symlink-expanded path */
path = verify_proc_self_fd (proc_path, error);
if (path == NULL)
return NULL;
/* Verify that this is the same file as the app opened */
if (stat (path, &real_st_buf) < 0 ||
st_buf.st_dev != real_st_buf.st_dev ||
st_buf.st_ino != real_st_buf.st_ino)
{
/* Different files on the inside and the outside, reject the request */
return glnx_null_throw (error,
"different file inside and outside sandbox");
}
read_access_mode = R_OK;
if (S_ISDIR (st_buf.st_mode))
read_access_mode |= X_OK;
/* Must be able to access the path via the sandbox supplied O_PATH fd,
which applies the sandbox side mount options (like readonly). */
if (access (proc_path, read_access_mode) != 0)
return glnx_null_throw (error, "not %s in sandbox",
read_access_mode & X_OK ? "accessible" : "readable");
if (access (proc_path, W_OK) == 0)
writable = TRUE;
*writable_out = writable;
return g_steal_pointer (&path);
}
static gboolean
handle_spawn (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GUnixFDList *fd_list,
const gchar *arg_cwd_path,
const gchar *const *arg_argv,
GVariant *arg_fds,
GVariant *arg_envs,
guint arg_flags,
GVariant *arg_options)
{
g_autoptr(GError) error = NULL;
ChildSetupData child_setup_data = { NULL };
GPid pid;
PidData *pid_data;
InstanceIdReadData *instance_id_read_data = NULL;
gsize i, j, n_fds, n_envs;
const gint *fds = NULL;
gint fds_len = 0;
g_autofree FdMapEntry *fd_map = NULL;
gchar **env;
gint32 max_fd;
GKeyFile *app_info;
g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);
g_autofree char *app_id = NULL;
g_autofree char *branch = NULL;
g_autofree char *arch = NULL;
g_autofree char *app_commit = NULL;
g_autofree char *runtime_ref = NULL;
g_auto(GStrv) runtime_parts = NULL;
g_autofree char *runtime_commit = NULL;
g_autofree char *instance_path = NULL;
g_auto(GStrv) extra_args = NULL;
g_auto(GStrv) shares = NULL;
g_auto(GStrv) sockets = NULL;
g_auto(GStrv) devices = NULL;
g_auto(GStrv) sandbox_expose = NULL;
g_auto(GStrv) sandbox_expose_ro = NULL;
g_autoptr(GVariant) sandbox_expose_fd = NULL;
g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;
g_autoptr(GOutputStream) instance_id_out_stream = NULL;
guint sandbox_flags = 0;
gboolean sandboxed;
gboolean expose_pids;
gboolean share_pids;
gboolean notify_start;
gboolean devel;
child_setup_data.instance_id_fd = -1;
if (fd_list != NULL)
fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);
app_info = g_object_get_data (G_OBJECT (invocation), "app-info");
g_assert (app_info != NULL);
app_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, NULL);
g_assert (app_id != NULL);
g_debug ("spawn() called from app: '%s'", app_id);
if (*app_id == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (*arg_cwd_path == 0)
arg_cwd_path = NULL;
if (arg_argv == NULL || *arg_argv == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No command given");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_ref = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_RUNTIME, NULL);
if (runtime_ref == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"No runtime found");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_parts = g_strsplit (runtime_ref, "/", -1);
branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BRANCH, NULL);
instance_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);
arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_ARCH, NULL);
extra_args = g_key_file_get_string_list (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);
app_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_COMMIT, NULL);
runtime_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);
shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED, NULL, NULL);
sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);
devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);
devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_DEVEL, NULL);
g_variant_lookup (arg_options, "sandbox-expose", "^as", &sandbox_expose);
g_variant_lookup (arg_options, "sandbox-expose-ro", "^as", &sandbox_expose_ro);
g_variant_lookup (arg_options, "sandbox-flags", "u", &sandbox_flags);
sandbox_expose_fd = g_variant_lookup_value (arg_options, "sandbox-expose-fd", G_VARIANT_TYPE ("ah"));
sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, "sandbox-expose-fd-ro", G_VARIANT_TYPE ("ah"));
if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported sandbox flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_path == NULL &&
((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||
(sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose, caller has no instance path");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
{
const char *expose = sandbox_expose[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
g_debug ("Running spawn command %s", arg_argv[0]);
n_fds = 0;
if (fds != NULL)
n_fds = g_variant_n_children (arg_fds);
fd_map = g_new0 (FdMapEntry, n_fds);
child_setup_data.fd_map = fd_map;
child_setup_data.fd_map_len = n_fds;
max_fd = -1;
for (i = 0; i < n_fds; i++)
{
gint32 handle, dest_fd;
int handle_fd;
g_variant_get_child (arg_fds, i, "{uh}", &dest_fd, &handle);
if (handle >= fds_len || handle < 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
handle_fd = fds[handle];
fd_map[i].to = dest_fd;
fd_map[i].from = handle_fd;
fd_map[i].final = fd_map[i].to;
/* If stdin/out/err is a tty we try to set it as the controlling
tty for the app, this way we can use this to run in a terminal. */
if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&
!child_setup_data.set_tty &&
isatty (handle_fd))
{
child_setup_data.set_tty = TRUE;
child_setup_data.tty = handle_fd;
}
max_fd = MAX (max_fd, fd_map[i].to);
max_fd = MAX (max_fd, fd_map[i].from);
}
/* We make a second pass over the fds to find if any "to" fd index
overlaps an already in use fd (i.e. one in the "from" category
that are allocated randomly). If a fd overlaps "to" fd then its
a caller issue and not our fault, so we ignore that. */
for (i = 0; i < n_fds; i++)
{
int to_fd = fd_map[i].to;
gboolean conflict = FALSE;
/* At this point we're fine with using "from" values for this
value (because we handle to==from in the code), or values
that are before "i" in the fd_map (because those will be
closed at this point when dup:ing). However, we can't
reuse a fd that is in "from" for j > i. */
for (j = i + 1; j < n_fds; j++)
{
int from_fd = fd_map[j].from;
if (from_fd == to_fd)
{
conflict = TRUE;
break;
}
}
if (conflict)
fd_map[i].to = ++max_fd;
}
if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)
{
char *empty[] = { NULL };
env = g_strdupv (empty);
}
else
env = g_get_environ ();
n_envs = g_variant_n_children (arg_envs);
for (i = 0; i < n_envs; i++)
{
const char *var = NULL;
const char *val = NULL;
g_variant_get_child (arg_envs, i, "{&s&s}", &var, &val);
env = g_environ_setenv (env, var, val, TRUE);
}
g_ptr_array_add (flatpak_argv, g_strdup ("flatpak"));
g_ptr_array_add (flatpak_argv, g_strdup ("run"));
sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;
if (sandboxed)
{
g_ptr_array_add (flatpak_argv, g_strdup ("--sandbox"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "wayland"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=wayland"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "fallback-x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=fallback-x11"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=x11"));
if (shares != NULL && g_strv_contains ((const char * const *) shares, "ipc") &&
sockets != NULL && (g_strv_contains ((const char * const *) sockets, "fallback-x11") ||
g_strv_contains ((const char * const *) sockets, "x11")))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=ipc"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "pulseaudio"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=pulseaudio"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)
{
if (devices != NULL &&
(g_strv_contains ((const char * const *) devices, "dri") ||
g_strv_contains ((const char * const *) devices, "all")))
g_ptr_array_add (flatpak_argv, g_strdup ("--device=dri"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)
g_ptr_array_add (flatpak_argv, g_strdup ("--session-bus"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)
g_ptr_array_add (flatpak_argv, g_strdup ("--a11y-bus"));
}
else
{
for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)
g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));
}
expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;
share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;
if (expose_pids || share_pids)
{
g_autofree char *instance_id = NULL;
int sender_pid1 = 0;
if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_NOT_SUPPORTED,
"Expose pids not supported with setuid bwrap");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
instance_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);
if (instance_id)
{
g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);
sender_pid1 = flatpak_instance_get_child_pid (instance);
}
if (sender_pid1 == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Could not find requesting pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--parent-pid=%d", sender_pid1));
if (share_pids)
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-share-pids"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-expose-pids"));
}
notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;
if (notify_start)
{
int pipe_fds[2];
if (pipe (pipe_fds) == -1)
{
int errsv = errno;
g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,
g_io_error_from_errno (errsv),
"Failed to create instance ID pipe: %s",
g_strerror (errsv));
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));
/* This is saved to ensure the portal's end gets closed after the exec. */
instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));
instance_id_read_data = g_new0 (InstanceIdReadData, 1);
g_input_stream_read_async (in_stream, instance_id_read_data->buffer,
INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,
instance_id_read_finish, instance_id_read_data);
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--instance-id-fd=%d", pipe_fds[1]));
child_setup_data.instance_id_fd = pipe_fds[1];
}
if (devel)
g_ptr_array_add (flatpak_argv, g_strdup ("--devel"));
/* Inherit launcher network access from launcher, unless
NO_NETWORK set. */
if (shares != NULL && g_strv_contains ((const char * const *) shares, "network") &&
!(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=network"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--unshare=network"));
if (instance_path)
{
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
}
if (sandbox_expose_fd != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
if (sandbox_expose_fd_ro != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd_ro);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd_ro, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime=%s", runtime_parts[1]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-version=%s", runtime_parts[3]));
if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)
{
if (app_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--commit=%s", app_commit));
if (runtime_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-commit=%s", runtime_commit));
}
if (arg_cwd_path != NULL)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--cwd=%s", arg_cwd_path));
if (arg_argv[0][0] != 0)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--command=%s", arg_argv[0]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("%s/%s/%s", app_id, arch ? arch : "", branch ? branch : ""));
for (i = 1; arg_argv[i] != NULL; i++)
g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));
g_ptr_array_add (flatpak_argv, NULL);
if (opt_verbose)
{
g_autoptr(GString) cmd = g_string_new ("");
for (i = 0; flatpak_argv->pdata[i] != NULL; i++)
{
if (i > 0)
g_string_append (cmd, " ");
g_string_append (cmd, flatpak_argv->pdata[i]);
}
g_debug ("Starting: %s\n", cmd->str);
}
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_async_with_pipes (NULL,
(char **) flatpak_argv->pdata,
env,
G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
child_setup_func, &child_setup_data,
&pid,
NULL,
NULL,
NULL,
&error))
{
gint code = G_DBUS_ERROR_FAILED;
if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))
code = G_DBUS_ERROR_ACCESS_DENIED;
else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))
code = G_DBUS_ERROR_FILE_NOT_FOUND;
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,
"Failed to start command: %s",
error->message);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_id_read_data)
instance_id_read_data->pid = pid;
pid_data = g_new0 (PidData, 1);
pid_data->pid = pid;
pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));
pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;
pid_data->expose_or_share_pids = (expose_pids || share_pids);
pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,
pid,
child_watch_died,
pid_data,
NULL);
g_debug ("Client Pid is %d", pid_data->pid);
g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),
pid_data);
portal_flatpak_complete_spawn (object, invocation, NULL, pid);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
handle_spawn_signal (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
guint arg_pid,
guint arg_signal,
gboolean arg_to_process_group)
{
PidData *pid_data = NULL;
g_debug ("spawn_signal(%d %d)", arg_pid, arg_signal);
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (arg_pid));
if (pid_data == NULL ||
strcmp (pid_data->client, g_dbus_method_invocation_get_sender (invocation)) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,
"No such pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_debug ("Sending signal %d to client pid %d", arg_signal, arg_pid);
if (arg_to_process_group)
killpg (pid_data->pid, arg_signal);
else
kill (pid_data->pid, arg_signal);
portal_flatpak_complete_spawn_signal (portal, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
authorize_method_handler (GDBusInterfaceSkeleton *interface,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
g_autoptr(GError) error = NULL;
g_autoptr(GKeyFile) keyfile = NULL;
g_autofree char *app_id = NULL;
const char *required_sender;
/* Ensure we don't idle exit */
schedule_idle_callback ();
required_sender = g_object_get_data (G_OBJECT (interface), "required-sender");
if (required_sender)
{
const char *sender = g_dbus_method_invocation_get_sender (invocation);
if (g_strcmp0 (required_sender, sender) != 0)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
"Client not allowed to access object");
return FALSE;
}
}
keyfile = flatpak_invocation_lookup_app_info (invocation, NULL, &error);
if (keyfile == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
app_id = g_key_file_get_string (keyfile,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, &error);
if (app_id == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
g_object_set_data_full (G_OBJECT (invocation), "app-info", g_steal_pointer (&keyfile), (GDestroyNotify) g_key_file_unref);
return TRUE;
}
static void
register_update_monitor (PortalFlatpakUpdateMonitor *monitor,
const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_insert (update_monitors, g_strdup (obj_path), g_object_ref (monitor));
/* Trigger update timeout if needed */
if (update_monitors_timeout == 0 && !update_monitors_timeout_running_thread)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
static void
unregister_update_monitor (const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_remove (update_monitors, obj_path);
G_UNLOCK (update_monitors);
}
static gboolean
has_update_monitors (void)
{
gboolean res;
G_LOCK (update_monitors);
res = g_hash_table_size (update_monitors) > 0;
G_UNLOCK (update_monitors);
return res;
}
static GList *
update_monitors_get_all (const char *optional_sender)
{
GList *list = NULL;
G_LOCK (update_monitors);
if (update_monitors)
{
GLNX_HASH_TABLE_FOREACH_V (update_monitors, PortalFlatpakUpdateMonitor *, monitor)
{
UpdateMonitorData *data = update_monitor_get_data (monitor);
if (optional_sender == NULL ||
strcmp (data->sender, optional_sender) == 0)
list = g_list_prepend (list, g_object_ref (monitor));
}
}
G_UNLOCK (update_monitors);
return list;
}
static void
update_monitor_data_free (gpointer data)
{
UpdateMonitorData *m = data;
g_mutex_clear (&m->lock);
g_free (m->sender);
g_free (m->obj_path);
g_object_unref (m->cancellable);
g_free (m->name);
g_free (m->arch);
g_free (m->branch);
g_free (m->commit);
g_free (m->app_path);
g_free (m->reported_local_commit);
g_free (m->reported_remote_commit);
g_free (m);
}
static UpdateMonitorData *
update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor)
{
return (UpdateMonitorData *)g_object_get_data (G_OBJECT (monitor), "update-monitor-data");
}
static PortalFlatpakUpdateMonitor *
create_update_monitor (GDBusMethodInvocation *invocation,
const char *obj_path,
GError **error)
{
PortalFlatpakUpdateMonitor *monitor;
UpdateMonitorData *m;
g_autoptr(GKeyFile) app_info = NULL;
g_autofree char *name = NULL;
app_info = flatpak_invocation_lookup_app_info (invocation, NULL, error);
if (app_info == NULL)
return NULL;
name = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
"name", NULL);
if (name == NULL || *name == 0)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
"Updates only supported by flatpak apps");
return NULL;
}
m = g_new0 (UpdateMonitorData, 1);
g_mutex_init (&m->lock);
m->obj_path = g_strdup (obj_path);
m->sender = g_strdup (g_dbus_method_invocation_get_sender (invocation));
m->cancellable = g_cancellable_new ();
m->name = g_steal_pointer (&name);
m->arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"arch", NULL);
m->branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"branch", NULL);
m->commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-commit", NULL);
m->app_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-path", NULL);
m->reported_local_commit = g_strdup (m->commit);
m->reported_remote_commit = g_strdup (m->commit);
monitor = portal_flatpak_update_monitor_skeleton_new ();
g_object_set_data_full (G_OBJECT (monitor), "update-monitor-data", m, update_monitor_data_free);
g_object_set_data_full (G_OBJECT (monitor), "required-sender", g_strdup (m->sender), g_free);
g_debug ("created UpdateMonitor for %s/%s at %s", m->name, m->branch, obj_path);
return monitor;
}
static void
update_monitor_do_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_dbus_interface_skeleton_unexport (G_DBUS_INTERFACE_SKELETON (monitor));
unregister_update_monitor (m->obj_path);
}
/* Always called in worker thread */
static void
update_monitor_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean do_close;
g_mutex_lock (&m->lock);
/* Close at most once, but not if running, if running it will be closed when that is done */
do_close = !m->closed && !m->running;
m->closed = TRUE;
g_mutex_unlock (&m->lock);
/* Always cancel though, so we can exit any running code early */
g_cancellable_cancel (m->cancellable);
if (do_close)
update_monitor_do_close (monitor);
}
static GDBusConnection *
update_monitor_get_connection (PortalFlatpakUpdateMonitor *monitor)
{
return g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (monitor));
}
static GHashTable *installation_cache = NULL;
static void
clear_installation_cache (void)
{
if (installation_cache != NULL)
g_hash_table_remove_all (installation_cache);
}
/* Caching lookup of Installation for a path */
static FlatpakInstallation *
lookup_installation_for_path (GFile *path, GError **error)
{
FlatpakInstallation *installation;
if (installation_cache == NULL)
installation_cache = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal, g_object_unref, g_object_unref);
installation = g_hash_table_lookup (installation_cache, path);
if (installation == NULL)
{
g_autoptr(FlatpakDir) dir = NULL;
dir = flatpak_dir_get_by_path (path);
installation = flatpak_installation_new_for_dir (dir, NULL, error);
if (installation == NULL)
return NULL;
flatpak_installation_set_no_interaction (installation, TRUE);
g_hash_table_insert (installation_cache, g_object_ref (path), installation);
}
return g_object_ref (installation);
}
static GFile *
update_monitor_get_installation_path (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) app_path = NULL;
app_path = g_file_new_for_path (m->app_path);
/* The app path is always 6 level deep inside the installation dir,
* like $dir/app/org.the.app/x86_64/stable/$commit/files, so we find
* the installation by just going up 6 parents. */
return g_file_resolve_relative_path (app_path, "../../../../../..");
}
static void
check_for_updates (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) installation_path = NULL;
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakInstalledRef) installed_ref = NULL;
g_autoptr(FlatpakRemoteRef) remote_ref = NULL;
const char *origin = NULL;
const char *local_commit = NULL;
const char *remote_commit;
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
const char *ref;
installation_path = update_monitor_get_installation_path (monitor);
g_debug ("Checking for updates for %s/%s/%s in %s", m->name, m->arch, m->branch, flatpak_file_get_path_cached (installation_path));
installation = lookup_installation_for_path (installation_path, &error);
if (installation == NULL)
{
g_debug ("Unable to find installation for path %s: %s", flatpak_file_get_path_cached (installation_path), error->message);
return;
}
installed_ref = flatpak_installation_get_installed_ref (installation,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (installed_ref == NULL)
{
g_debug ("getting installed ref failed: %s", error->message);
return; /* Never report updates for uninstalled refs */
}
dir = flatpak_installation_get_dir (installation, NULL);
if (dir == NULL)
return;
ref = flatpak_ref_format_ref_cached (FLATPAK_REF (installed_ref));
if (flatpak_dir_ref_is_masked (dir, ref))
return; /* Never report updates for masked refs */
local_commit = flatpak_ref_get_commit (FLATPAK_REF (installed_ref));
origin = flatpak_installed_ref_get_origin (installed_ref);
remote_ref = flatpak_installation_fetch_remote_ref_sync (installation, origin,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (remote_ref == NULL)
{
/* Probably some network issue.
* Fall back to the local_commit to at least be able to pick up already installed updates.
*/
g_debug ("getting remote ref failed: %s", error->message);
g_clear_error (&error);
remote_commit = local_commit;
}
else
{
remote_commit = flatpak_ref_get_commit (FLATPAK_REF (remote_ref));
if (remote_commit == NULL)
{
/* This can happen if we're offline and there is an update from an usb drive.
* Not much we can do in terms of reporting it, but at least handle the case
*/
g_debug ("Unknown remote commit, setting to local_commit");
remote_commit = local_commit;
}
}
if (g_strcmp0 (m->reported_local_commit, local_commit) != 0 ||
g_strcmp0 (m->reported_remote_commit, remote_commit) != 0)
{
GVariantBuilder builder;
gboolean is_closed;
g_free (m->reported_local_commit);
m->reported_local_commit = g_strdup (local_commit);
g_free (m->reported_remote_commit);
m->reported_remote_commit = g_strdup (remote_commit);
g_debug ("Found update for %s/%s/%s, local: %s, remote: %s", m->name, m->arch, m->branch, local_commit, remote_commit);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&builder, "{sv}", "running-commit", g_variant_new_string (m->commit));
g_variant_builder_add (&builder, "{sv}", "local-commit", g_variant_new_string (local_commit));
g_variant_builder_add (&builder, "{sv}", "remote-commit", g_variant_new_string (remote_commit));
/* Maybe someone closed the monitor while we were checking for updates, then drop the signal.
* There is still a minimal race between this check and the emit where a client could call close()
* and still see the signal though. */
g_mutex_lock (&m->lock);
is_closed = m->closed;
g_mutex_unlock (&m->lock);
if (!is_closed &&
!g_dbus_connection_emit_signal (update_monitor_get_connection (monitor),
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"UpdateAvailable",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit UpdateAvailable: %s", error->message);
g_clear_error (&error);
}
}
}
static void
check_all_for_updates_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *monitors, *l;
monitors = update_monitors_get_all (NULL);
for (l = monitors; l != NULL; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean was_closed = FALSE;
g_mutex_lock (&m->lock);
if (m->closed)
was_closed = TRUE;
else
m->running = TRUE;
g_mutex_unlock (&m->lock);
if (!was_closed)
{
check_for_updates (monitor);
g_mutex_lock (&m->lock);
m->running = FALSE;
if (m->closed) /* Was closed during running, do delayed close */
update_monitor_do_close (monitor);
g_mutex_unlock (&m->lock);
}
}
g_list_free_full (monitors, g_object_unref);
/* We want to cache stuff between multiple monitors
when a poll is scheduled, but there is no need to keep it
long term to the next poll, the in-memory is just
a waste of space then. */
clear_installation_cache ();
G_LOCK (update_monitors);
update_monitors_timeout_running_thread = FALSE;
if (g_hash_table_size (update_monitors) > 0)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
/* Runs on main thread */
static gboolean
check_all_for_updates_cb (void *data)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
if (!opt_poll_when_metered &&
g_network_monitor_get_network_metered (network_monitor))
{
g_debug ("Skipping update check on metered network");
return G_SOURCE_CONTINUE;
}
g_debug ("Checking all update monitors");
G_LOCK (update_monitors);
update_monitors_timeout = 0;
update_monitors_timeout_running_thread = TRUE;
G_UNLOCK (update_monitors);
g_task_run_in_thread (task, check_all_for_updates_in_thread_func);
return G_SOURCE_REMOVE; /* This will be re-added by the thread when done */
}
/* Runs in worker thread */
static gboolean
handle_create_update_monitor (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GVariant *options)
{
GDBusConnection *connection = g_dbus_method_invocation_get_connection (invocation);
g_autoptr(PortalFlatpakUpdateMonitorSkeleton) monitor = NULL;
const char *sender;
g_autofree char *sender_escaped = NULL;
g_autofree char *obj_path = NULL;
g_autofree char *token = NULL;
g_autoptr(GError) error = NULL;
int i;
if (!g_variant_lookup (options, "handle_token", "s", &token))
token = g_strdup_printf ("%d", g_random_int_range (0, 1000));
sender = g_dbus_method_invocation_get_sender (invocation);
g_debug ("handle CreateUpdateMonitor from %s", sender);
sender_escaped = g_strdup (sender + 1);
for (i = 0; sender_escaped[i]; i++)
{
if (sender_escaped[i] == '.')
sender_escaped[i] = '_';
}
obj_path = g_strdup_printf ("/org/freedesktop/portal/Flatpak/update_monitor/%s/%s",
sender_escaped,
token);
monitor = (PortalFlatpakUpdateMonitorSkeleton *) create_update_monitor (invocation, obj_path, &error);
if (monitor == NULL)
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_signal_connect (monitor, "handle-close", G_CALLBACK (handle_close), NULL);
g_signal_connect (monitor, "handle-update", G_CALLBACK (handle_update), NULL);
g_signal_connect (monitor, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (monitor),
connection,
obj_path,
&error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
register_update_monitor ((PortalFlatpakUpdateMonitor*)monitor, obj_path);
portal_flatpak_complete_create_update_monitor (portal, invocation, obj_path);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
/* Runs in worker thread */
static gboolean
handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation)
{
update_monitor_close (monitor);
g_debug ("handle UpdateMonitor.Close");
portal_flatpak_update_monitor_complete_close (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
deep_free_object_list (gpointer data)
{
g_list_free_full ((GList *)data, g_object_unref);
}
static void
close_update_monitors_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *list = task_data;
GList *l;
for (l = list; l; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_debug ("closing monitor %s", m->obj_path);
update_monitor_close (monitor);
}
}
static void
close_update_monitors_for_sender (const char *sender)
{
GList *list = update_monitors_get_all (sender);
if (list)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
g_task_set_task_data (task, list, deep_free_object_list);
g_debug ("%s dropped off the bus, closing monitors", sender);
g_task_run_in_thread (task, close_update_monitors_in_thread_func);
}
}
static guint32
get_update_permission (const char *app_id)
{
g_autoptr(GVariant) out_perms = NULL;
g_autoptr(GVariant) out_data = NULL;
g_autoptr(GError) error = NULL;
guint32 ret = UNSET;
if (permission_store == NULL)
{
g_debug ("No portals installed, assume no permissions");
return NO;
}
if (!xdp_dbus_permission_store_call_lookup_sync (permission_store,
PERMISSION_TABLE,
PERMISSION_ID,
&out_perms,
&out_data,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_debug ("No updates permissions found: %s", error->message);
g_clear_error (&error);
}
if (out_perms != NULL)
{
const char **perms;
if (g_variant_lookup (out_perms, app_id, "^a&s", &perms))
{
if (strcmp (perms[0], "ask") == 0)
ret = ASK;
else if (strcmp (perms[0], "yes") == 0)
ret = YES;
else
ret = NO;
}
}
g_debug ("Updates permissions for %s: %d", app_id, ret);
return ret;
}
static void
set_update_permission (const char *app_id,
Permission permission)
{
g_autoptr(GError) error = NULL;
const char *permissions[2];
if (permission == ASK)
permissions[0] = "ask";
else if (permission == YES)
permissions[0] = "yes";
else if (permission == NO)
permissions[0] = "no";
else
{
g_warning ("Wrong permission format, ignoring");
return;
}
permissions[1] = NULL;
if (!xdp_dbus_permission_store_call_set_permission_sync (permission_store,
PERMISSION_TABLE,
TRUE,
PERMISSION_ID,
app_id,
(const char * const*)permissions,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_info ("Error updating permission store: %s", error->message);
}
}
static char *
get_app_display_name (const char *app_id)
{
g_autofree char *id = NULL;
g_autoptr(GDesktopAppInfo) info = NULL;
const char *name = NULL;
id = g_strconcat (app_id, ".desktop", NULL);
info = g_desktop_app_info_new (id);
if (info)
{
name = g_app_info_get_display_name (G_APP_INFO (info));
if (name)
return g_strdup (name);
}
return g_strdup (app_id);
}
static gboolean
request_update_permissions_sync (PortalFlatpakUpdateMonitor *monitor,
const char *app_id,
const char *window,
GError **error)
{
Permission permission;
permission = get_update_permission (app_id);
if (permission == UNSET || permission == ASK)
{
guint access_response = 2;
PortalImplementation *access_impl;
GVariantBuilder access_opt_builder;
g_autofree char *app_name = NULL;
g_autofree char *title = NULL;
g_autoptr(GVariant) ret = NULL;
access_impl = find_portal_implementation ("org.freedesktop.impl.portal.Access");
if (access_impl == NULL)
{
g_warning ("No Access portal implementation found");
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED, _("No portal support found"));
return FALSE;
}
g_variant_builder_init (&access_opt_builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&access_opt_builder, "{sv}",
"deny_label", g_variant_new_string (_("Deny")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"grant_label", g_variant_new_string (_("Update")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"icon", g_variant_new_string ("package-x-generic-symbolic"));
app_name = get_app_display_name (app_id);
title = g_strdup_printf (_("Update %s?"), app_name);
ret = g_dbus_connection_call_sync (update_monitor_get_connection (monitor),
access_impl->dbus_name,
"/org/freedesktop/portal/desktop",
"org.freedesktop.impl.portal.Access",
"AccessDialog",
g_variant_new ("(osssssa{sv})",
"/request/path",
app_id,
window,
title,
_("The application wants to update itself."),
_("Update access can be changed any time from the privacy settings."),
&access_opt_builder),
G_VARIANT_TYPE ("(ua{sv})"),
G_DBUS_CALL_FLAGS_NONE,
G_MAXINT,
NULL,
error);
if (ret == NULL)
{
g_dbus_error_strip_remote_error (*error);
g_warning ("Failed to show access dialog: %s", (*error)->message);
return FALSE;
}
g_variant_get (ret, "(ua{sv})", &access_response, NULL);
if (permission == UNSET)
set_update_permission (app_id, (access_response == 0) ? YES : NO);
permission = (access_response == 0) ? YES : NO;
}
if (permission == NO)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
_("Application update not allowed"));
return FALSE;
}
return TRUE;
}
static void
emit_progress (PortalFlatpakUpdateMonitor *monitor,
int op,
int n_ops,
int progress,
int status,
const char *error_name,
const char *error_message)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
GDBusConnection *connection;
GVariantBuilder builder;
g_autoptr(GError) error = NULL;
g_debug ("%d/%d ops, progress %d, status: %d", op, n_ops, progress, status);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
if (n_ops > 0)
{
g_variant_builder_add (&builder, "{sv}", "op", g_variant_new_uint32 (op));
g_variant_builder_add (&builder, "{sv}", "n_ops", g_variant_new_uint32 (n_ops));
g_variant_builder_add (&builder, "{sv}", "progress", g_variant_new_uint32 (progress));
}
g_variant_builder_add (&builder, "{sv}", "status", g_variant_new_uint32 (status));
if (error_name)
{
g_variant_builder_add (&builder, "{sv}", "error", g_variant_new_string (error_name));
g_variant_builder_add (&builder, "{sv}", "error_message", g_variant_new_string (error_message));
}
connection = update_monitor_get_connection (monitor);
if (!g_dbus_connection_emit_signal (connection,
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"Progress",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit ::progress: %s", error->message);
}
}
static char *
get_progress_error (const GError *update_error)
{
g_autofree gchar *name = NULL;
name = g_dbus_error_encode_gerror (update_error);
/* Don't return weird dbus wrapped things from the portal */
if (g_str_has_prefix (name, "org.gtk.GDBus.UnmappedGError.Quark"))
return g_strdup ("org.freedesktop.DBus.Error.Failed");
return g_steal_pointer (&name);
}
static void
emit_progress_error (PortalFlatpakUpdateMonitor *monitor,
GError *update_error)
{
g_autofree gchar *error_name = get_progress_error (update_error);
emit_progress (monitor, 0, 0, 0,
PROGRESS_STATUS_ERROR,
error_name, update_error->message);
}
static void
send_variant (GVariant *v, GOutputStream *out)
{
g_autoptr(GError) error = NULL;
const guchar *data;
gsize size;
guint32 size32;
data = g_variant_get_data (v);
size = g_variant_get_size (v);
size32 = size;
if (!g_output_stream_write_all (out, &size32, 4, NULL, NULL, &error) ||
!g_output_stream_write_all (out, data, size, NULL, NULL, &error))
{
g_warning ("sending to parent failed: %s", error->message);
exit (1); // This will exit the child process and cause the parent to report an error
}
}
static void
send_progress (GOutputStream *out,
int op,
int n_ops,
int progress,
int status,
const GError *update_error)
{
g_autoptr(GVariant) v = NULL;
g_autofree gchar *error_name = NULL;
if (update_error)
error_name = get_progress_error (update_error);
v = g_variant_ref_sink (g_variant_new ("(uuuuss)",
op, n_ops, progress, status,
error_name ? error_name : "",
update_error ? update_error->message : ""));
send_variant (v, out);
}
typedef struct {
GOutputStream *out;
int n_ops;
int op;
int progress;
gboolean saw_first_operation;
} TransactionData;
static gboolean
transaction_ready (FlatpakTransaction *transaction,
TransactionData *d)
{
GList *ops = flatpak_transaction_get_operations (transaction);
int status;
GList *l;
d->n_ops = g_list_length (ops);
d->op = 0;
d->progress = 0;
for (l = ops; l != NULL; l = l->next)
{
FlatpakTransactionOperation *op = l->data;
const char *ref = flatpak_transaction_operation_get_ref (op);
FlatpakTransactionOperationType type = flatpak_transaction_operation_get_operation_type (op);
/* Actual app updates need to not increase premission requirements */
if (type == FLATPAK_TRANSACTION_OPERATION_UPDATE && g_str_has_prefix (ref, "app/"))
{
GKeyFile *new_metadata = flatpak_transaction_operation_get_metadata (op);
GKeyFile *old_metadata = flatpak_transaction_operation_get_old_metadata (op);
g_autoptr(FlatpakContext) new_context = flatpak_context_new ();
g_autoptr(FlatpakContext) old_context = flatpak_context_new ();
if (!flatpak_context_load_metadata (new_context, new_metadata, NULL) ||
!flatpak_context_load_metadata (old_context, old_metadata, NULL) ||
flatpak_context_adds_permissions (old_context, new_context))
{
g_autoptr(GError) error = NULL;
g_set_error (&error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
_("Self update not supported, new version requires new permissions"));
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE;
}
}
}
if (flatpak_transaction_is_empty (transaction))
status = PROGRESS_STATUS_EMPTY;
else
status = PROGRESS_STATUS_RUNNING;
send_progress (d->out,
d->op, d->n_ops,
d->progress, status,
NULL);
if (status == PROGRESS_STATUS_EMPTY)
return FALSE; /* This will cause us to return an ABORTED error */
return TRUE;
}
static void
transaction_progress_changed (FlatpakTransactionProgress *progress,
TransactionData *d)
{
/* Only report 100 when really done */
d->progress = MIN (flatpak_transaction_progress_get_progress (progress), 99);
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
transaction_new_operation (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
FlatpakTransactionProgress *progress,
TransactionData *d)
{
d->progress = 0;
if (d->saw_first_operation)
d->op++;
else
d->saw_first_operation = TRUE;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
g_signal_connect (progress, "changed", G_CALLBACK (transaction_progress_changed), d);
}
static gboolean
transaction_operation_error (FlatpakTransaction *transaction,
FlatpakTransactionOperation *operation,
const GError *error,
FlatpakTransactionErrorDetails detail,
TransactionData *d)
{
gboolean non_fatal = (detail & FLATPAK_TRANSACTION_ERROR_DETAILS_NON_FATAL) != 0;
if (non_fatal)
return TRUE; /* Continue */
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE; /* This will cause us to return an ABORTED error */
}
static void
transaction_operation_done (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
const char *commit,
FlatpakTransactionResult result,
TransactionData *d)
{
d->progress = 100;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
update_child_setup_func (gpointer user_data)
{
int *socket = user_data;
dup2 (*socket, 3);
flatpak_close_fds_workaround (4);
}
/* This is the meat of the update process, its run out of process (via
spawn) to avoid running lots of complicated code in the portal
process and possibly long-term leaks in a long-running process. */
static int
do_update_child_process (const char *installation_path, const char *ref, int socket_fd)
{
g_autoptr(GOutputStream) out = g_unix_output_stream_new (socket_fd, TRUE);
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakTransaction) transaction = NULL;
g_autoptr(GFile) f = g_file_new_for_path (installation_path);
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
TransactionData transaction_data = { NULL };
dir = flatpak_dir_get_by_path (f);
if (!flatpak_dir_maybe_ensure_repo (dir, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
installation = flatpak_installation_new_for_dir (dir, NULL, &error);
if (installation)
transaction = flatpak_transaction_new_for_installation (installation, NULL, &error);
if (transaction == NULL)
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
flatpak_transaction_add_default_dependency_sources (transaction);
if (!flatpak_transaction_add_update (transaction, ref, NULL, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
transaction_data.out = out;
g_signal_connect (transaction, "ready", G_CALLBACK (transaction_ready), &transaction_data);
g_signal_connect (transaction, "new-operation", G_CALLBACK (transaction_new_operation), &transaction_data);
g_signal_connect (transaction, "operation-done", G_CALLBACK (transaction_operation_done), &transaction_data);
g_signal_connect (transaction, "operation-error", G_CALLBACK (transaction_operation_error), &transaction_data);
if (!flatpak_transaction_run (transaction, NULL, &error))
{
if (!g_error_matches (error, FLATPAK_ERROR, FLATPAK_ERROR_ABORTED)) /* If aborted we already sent error */
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_ERROR, error);
return 0;
}
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_DONE, error);
return 0;
}
static GVariant *
read_variant (GInputStream *in,
GCancellable *cancellable,
GError **error)
{
guint32 size;
guchar *data;
gsize bytes_read;
if (!g_input_stream_read_all (in, &size, 4, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != 4)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
data = g_try_malloc (size);
if (data == NULL)
{
flatpak_fail (error, "Out of memory");
return NULL;
}
if (!g_input_stream_read_all (in, data, size, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != size)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
return g_variant_ref_sink (g_variant_new_from_data (G_VARIANT_TYPE("(uuuuss)"),
data, size, FALSE, g_free, data));
}
/* We do the actual update out of process (in do_update_child_process,
via spawn) and just proxy the feedback here */
static gboolean
handle_update_responses (PortalFlatpakUpdateMonitor *monitor,
int socket_fd,
GError **error)
{
g_autoptr(GInputStream) in = g_unix_input_stream_new (socket_fd, FALSE); /* Closed by parent */
UpdateMonitorData *m = update_monitor_get_data (monitor);
guint32 status;
do
{
g_autoptr(GVariant) v = NULL;
guint32 op;
guint32 n_ops;
guint32 progress;
const char *error_name;
const char *error_message;
v = read_variant (in, m->cancellable, error);
if (v == NULL)
{
g_debug ("Reading message from child update process failed %s", (*error)->message);
return FALSE;
}
g_variant_get (v, "(uuuu&s&s)",
&op, &n_ops, &progress, &status, &error_name, &error_message);
emit_progress (monitor, op, n_ops, progress, status,
*error_name != 0 ? error_name : NULL,
*error_message != 0 ? error_message : NULL);
}
while (status == PROGRESS_STATUS_RUNNING);
/* Don't return an received error as we emited it already, that would cause it to be emitted twice */
return TRUE;
}
static void
handle_update_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
PortalFlatpakUpdateMonitor *monitor = source_object;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GError) error = NULL;
const char *window;
window = (const char *)g_object_get_data (G_OBJECT (task), "window");
if (request_update_permissions_sync (monitor, m->name, window, &error))
{
g_autoptr(GFile) installation_path = update_monitor_get_installation_path (monitor);
g_autofree char *ref = flatpak_build_app_ref (m->name, m->branch, m->arch);
const char *argv[] = { "/proc/self/exe", "flatpak-portal", "--update", flatpak_file_get_path_cached (installation_path), ref, NULL };
int sockets[2];
GPid pid;
if (socketpair (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sockets) != 0)
{
glnx_throw_errno (&error);
}
else
{
gboolean spawn_ok;
spawn_ok = g_spawn_async (NULL, (char **)argv, NULL,
G_SPAWN_FILE_AND_ARGV_ZERO |
G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
update_child_setup_func, &sockets[1],
&pid, &error);
close (sockets[1]); // Close remote side
if (spawn_ok)
{
if (!handle_update_responses (monitor, sockets[0], &error))
{
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
kill (pid, SIGINT);
}
}
close (sockets[0]); // Close local side
}
}
if (error)
emit_progress_error (monitor, error);
g_mutex_lock (&m->lock);
m->installing = FALSE;
g_mutex_unlock (&m->lock);
}
static gboolean
handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GTask) task = NULL;
gboolean already_installing = FALSE;
g_debug ("handle UpdateMonitor.Update");
g_mutex_lock (&m->lock);
if (m->installing)
already_installing = TRUE;
else
m->installing = TRUE;
g_mutex_unlock (&m->lock);
if (already_installing)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR,
G_DBUS_ERROR_FAILED,
"Already installing");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
task = g_task_new (monitor, NULL, NULL, NULL);
g_object_set_data_full (G_OBJECT (task), "window", g_strdup (arg_window), g_free);
g_task_run_in_thread (task, handle_update_in_thread_func);
portal_flatpak_update_monitor_complete_update (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
name_owner_changed (GDBusConnection *connection,
const gchar *sender_name,
const gchar *object_path,
const gchar *interface_name,
const gchar *signal_name,
GVariant *parameters,
gpointer user_data)
{
const char *name, *from, *to;
g_variant_get (parameters, "(&s&s&s)", &name, &from, &to);
if (name[0] == ':' &&
strcmp (name, from) == 0 &&
strcmp (to, "") == 0)
{
GHashTableIter iter;
PidData *pid_data = NULL;
gpointer value = NULL;
GList *list = NULL, *l;
g_hash_table_iter_init (&iter, client_pid_data_hash);
while (g_hash_table_iter_next (&iter, NULL, &value))
{
pid_data = value;
if (pid_data->watch_bus && g_str_equal (pid_data->client, name))
list = g_list_prepend (list, pid_data);
}
for (l = list; l; l = l->next)
{
pid_data = l->data;
g_debug ("%s dropped off the bus, killing %d", pid_data->client, pid_data->pid);
killpg (pid_data->pid, SIGINT);
}
g_list_free (list);
close_update_monitors_for_sender (name);
}
}
#define DBUS_NAME_DBUS "org.freedesktop.DBus"
#define DBUS_INTERFACE_DBUS DBUS_NAME_DBUS
#define DBUS_PATH_DBUS "/org/freedesktop/DBus"
static gboolean
supports_expose_pids (void)
{
const char *path = g_find_program_in_path (flatpak_get_bwrap ());
struct stat st;
/* This is supported only if bwrap exists and is not setuid */
return
path != NULL &&
stat (path, &st) == 0 &&
(st.st_mode & S_ISUID) == 0;
}
static void
on_bus_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
GError *error = NULL;
g_debug ("Bus acquired, creating skeleton");
g_dbus_connection_set_exit_on_close (connection, FALSE);
update_monitors = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
permission_store = xdp_dbus_permission_store_proxy_new_sync (connection,
G_DBUS_PROXY_FLAGS_NONE,
"org.freedesktop.impl.portal.PermissionStore",
"/org/freedesktop/impl/portal/PermissionStore",
NULL, NULL);
portal = portal_flatpak_skeleton_new ();
g_dbus_connection_signal_subscribe (connection,
DBUS_NAME_DBUS,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged",
DBUS_PATH_DBUS,
NULL,
G_DBUS_SIGNAL_FLAGS_NONE,
name_owner_changed,
NULL, NULL);
g_object_set_data_full (G_OBJECT (portal), "track-alive", GINT_TO_POINTER (42), skeleton_died_cb);
g_dbus_interface_skeleton_set_flags (G_DBUS_INTERFACE_SKELETON (portal),
G_DBUS_INTERFACE_SKELETON_FLAGS_HANDLE_METHOD_INVOCATIONS_IN_THREAD);
portal_flatpak_set_version (PORTAL_FLATPAK (portal), 5);
portal_flatpak_set_supports (PORTAL_FLATPAK (portal), supports);
g_signal_connect (portal, "handle-spawn", G_CALLBACK (handle_spawn), NULL);
g_signal_connect (portal, "handle-spawn-signal", G_CALLBACK (handle_spawn_signal), NULL);
g_signal_connect (portal, "handle-create-update-monitor", G_CALLBACK (handle_create_update_monitor), NULL);
g_signal_connect (portal, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (portal),
connection,
"/org/freedesktop/portal/Flatpak",
&error))
{
g_warning ("error: %s", error->message);
g_error_free (error);
}
}
static void
on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name acquired");
}
static void
on_name_lost (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name lost");
unref_skeleton_in_timeout ();
}
static void
binary_file_changed_cb (GFileMonitor *file_monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
gpointer data)
{
static gboolean got_it = FALSE;
if (!got_it)
{
g_debug ("binary file changed");
unref_skeleton_in_timeout ();
}
got_it = TRUE;
}
static void
message_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data)
{
/* Make this look like normal console output */
if (log_level & G_LOG_LEVEL_DEBUG)
g_printerr ("F: %s\n", message);
else
g_printerr ("%s: %s\n", g_get_prgname (), message);
}
int
main (int argc,
char **argv)
{
gchar exe_path[PATH_MAX + 1];
ssize_t exe_path_len;
gboolean replace;
gboolean show_version;
GOptionContext *context;
GBusNameOwnerFlags flags;
g_autoptr(GError) error = NULL;
const GOptionEntry options[] = {
{ "replace", 'r', 0, G_OPTION_ARG_NONE, &replace, "Replace old daemon.", NULL },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &opt_verbose, "Enable debug output.", NULL },
{ "version", 0, 0, G_OPTION_ARG_NONE, &show_version, "Show program version.", NULL},
{ "no-idle-exit", 0, 0, G_OPTION_ARG_NONE, &no_idle_exit, "Don't exit when idle.", NULL },
{ "poll-timeout", 0, 0, G_OPTION_ARG_INT, &opt_poll_timeout, "Delay in seconds between polls for updates.", NULL },
{ "poll-when-metered", 0, 0, G_OPTION_ARG_NONE, &opt_poll_when_metered, "Whether to check for updates on metered networks", NULL },
{ NULL }
};
setlocale (LC_ALL, "");
g_setenv ("GIO_USE_VFS", "local", TRUE);
g_set_prgname (argv[0]);
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, message_handler, NULL);
if (argc >= 4 && strcmp (argv[1], "--update") == 0)
{
return do_update_child_process (argv[2], argv[3], 3);
}
context = g_option_context_new ("");
replace = FALSE;
opt_verbose = FALSE;
show_version = FALSE;
g_option_context_set_summary (context, "Flatpak portal");
g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
if (!g_option_context_parse (context, &argc, &argv, &error))
{
g_printerr ("%s: %s", g_get_application_name (), error->message);
g_printerr ("\n");
g_printerr ("Try \"%s --help\" for more information.",
g_get_prgname ());
g_printerr ("\n");
g_option_context_free (context);
return 1;
}
if (opt_poll_timeout == 0)
opt_poll_timeout = DEFAULT_UPDATE_POLL_TIMEOUT_SEC;
if (show_version)
{
g_print (PACKAGE_STRING "\n");
return 0;
}
if (opt_verbose)
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, message_handler, NULL);
client_pid_data_hash = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) pid_data_free);
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
if (session_bus == NULL)
{
g_printerr ("Can't find bus: %s\n", error->message);
return 1;
}
exe_path_len = readlink ("/proc/self/exe", exe_path, sizeof (exe_path) - 1);
if (exe_path_len > 0 && (size_t) exe_path_len < sizeof (exe_path))
{
exe_path[exe_path_len] = 0;
GFileMonitor *monitor;
g_autoptr(GFile) exe = NULL;
g_autoptr(GError) local_error = NULL;
exe = g_file_new_for_path (exe_path);
monitor = g_file_monitor_file (exe,
G_FILE_MONITOR_NONE,
NULL,
&local_error);
if (monitor == NULL)
g_warning ("Failed to set watch on %s: %s", exe_path, error->message);
else
g_signal_connect (monitor, "changed",
G_CALLBACK (binary_file_changed_cb), NULL);
}
flatpak_connection_track_name_owners (session_bus);
if (supports_expose_pids ())
supports |= FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS;
flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
if (replace)
flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
"org.freedesktop.portal.Flatpak",
flags,
on_bus_acquired,
on_name_acquired,
on_name_lost,
NULL,
NULL);
load_installed_portals (opt_verbose);
/* Ensure we don't idle exit */
schedule_idle_callback ();
network_monitor = g_network_monitor_get_default ();
main_loop = g_main_loop_new (NULL, FALSE);
g_main_loop_run (main_loop);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1908_0 |
crossvul-cpp_data_good_1906_1 | /*
* Copyright © 2014-2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/personality.h>
#include <grp.h>
#include <unistd.h>
#include <gio/gunixfdlist.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include "libglnx/libglnx.h"
#include "flatpak-bwrap-private.h"
#include "flatpak-utils-private.h"
#include "flatpak-utils-base-private.h"
static void
clear_fd (gpointer data)
{
int *fd_p = data;
if (fd_p != NULL && *fd_p != -1)
close (*fd_p);
}
char *flatpak_bwrap_empty_env[] = { NULL };
FlatpakBwrap *
flatpak_bwrap_new (char **env)
{
FlatpakBwrap *bwrap = g_new0 (FlatpakBwrap, 1);
bwrap->argv = g_ptr_array_new_with_free_func (g_free);
bwrap->noinherit_fds = g_array_new (FALSE, TRUE, sizeof (int));
g_array_set_clear_func (bwrap->noinherit_fds, clear_fd);
bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));
g_array_set_clear_func (bwrap->fds, clear_fd);
if (env)
bwrap->envp = g_strdupv (env);
else
bwrap->envp = g_get_environ ();
return bwrap;
}
void
flatpak_bwrap_free (FlatpakBwrap *bwrap)
{
g_ptr_array_unref (bwrap->argv);
g_array_unref (bwrap->noinherit_fds);
g_array_unref (bwrap->fds);
g_strfreev (bwrap->envp);
g_free (bwrap);
}
gboolean
flatpak_bwrap_is_empty (FlatpakBwrap *bwrap)
{
return bwrap->argv->len == 0;
}
void
flatpak_bwrap_set_env (FlatpakBwrap *bwrap,
const char *variable,
const char *value,
gboolean overwrite)
{
bwrap->envp = g_environ_setenv (bwrap->envp, variable, value, overwrite);
}
void
flatpak_bwrap_unset_env (FlatpakBwrap *bwrap,
const char *variable)
{
bwrap->envp = g_environ_unsetenv (bwrap->envp, variable);
}
void
flatpak_bwrap_add_arg (FlatpakBwrap *bwrap, const char *arg)
{
g_ptr_array_add (bwrap->argv, g_strdup (arg));
}
/*
* flatpak_bwrap_take_arg:
* @arg: (transfer full): Take ownership of this argument
*
* Add @arg to @bwrap's argv, taking ownership of the pointer.
*/
void
flatpak_bwrap_take_arg (FlatpakBwrap *bwrap, char *arg)
{
g_ptr_array_add (bwrap->argv, arg);
}
void
flatpak_bwrap_finish (FlatpakBwrap *bwrap)
{
g_ptr_array_add (bwrap->argv, NULL);
}
void
flatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,
int fd)
{
g_array_append_val (bwrap->noinherit_fds, fd);
}
void
flatpak_bwrap_add_fd (FlatpakBwrap *bwrap,
int fd)
{
g_array_append_val (bwrap->fds, fd);
}
void
flatpak_bwrap_add_arg_printf (FlatpakBwrap *bwrap, const char *format, ...)
{
va_list args;
va_start (args, format);
g_ptr_array_add (bwrap->argv, g_strdup_vprintf (format, args));
va_end (args);
}
void
flatpak_bwrap_add_args (FlatpakBwrap *bwrap, ...)
{
va_list args;
const gchar *arg;
va_start (args, bwrap);
while ((arg = va_arg (args, const gchar *)))
flatpak_bwrap_add_arg (bwrap, arg);
va_end (args);
}
void
flatpak_bwrap_append_argsv (FlatpakBwrap *bwrap,
char **args,
int len)
{
int i;
if (len < 0)
len = g_strv_length (args);
for (i = 0; i < len; i++)
g_ptr_array_add (bwrap->argv, g_strdup (args[i]));
}
void
flatpak_bwrap_append_args (FlatpakBwrap *bwrap,
GPtrArray *other_array)
{
flatpak_bwrap_append_argsv (bwrap,
(char **) other_array->pdata,
other_array->len);
}
static int *
flatpak_bwrap_steal_fds (FlatpakBwrap *bwrap,
gsize *len_out)
{
gsize len = bwrap->fds->len;
int *res = (int *) g_array_free (bwrap->fds, FALSE);
bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));
*len_out = len;
return res;
}
void
flatpak_bwrap_append_bwrap (FlatpakBwrap *bwrap,
FlatpakBwrap *other)
{
g_autofree int *fds = NULL;
gsize n_fds, i;
fds = flatpak_bwrap_steal_fds (other, &n_fds);
for (i = 0; i < n_fds; i++)
flatpak_bwrap_add_fd (bwrap, fds[i]);
flatpak_bwrap_append_argsv (bwrap,
(char **) other->argv->pdata,
other->argv->len);
for (i = 0; other->envp[i] != NULL; i++)
{
char *key_val = other->envp[i];
char *eq = strchr (key_val, '=');
if (eq)
{
g_autofree char *key = g_strndup (key_val, eq - key_val);
flatpak_bwrap_set_env (bwrap,
key, eq + 1, TRUE);
}
}
}
void
flatpak_bwrap_add_args_data_fd (FlatpakBwrap *bwrap,
const char *op,
int fd,
const char *path_optional)
{
g_autofree char *fd_str = g_strdup_printf ("%d", fd);
flatpak_bwrap_add_fd (bwrap, fd);
flatpak_bwrap_add_args (bwrap,
op, fd_str, path_optional,
NULL);
}
/* Given a buffer @content of size @content_size, generate a fd (memfd if available)
* of the data. The @name parameter is used by memfd_create() as a debugging aid;
* it has no semantic meaning. The bwrap command line will inject it into the target
* container as @path.
*/
gboolean
flatpak_bwrap_add_args_data (FlatpakBwrap *bwrap,
const char *name,
const char *content,
gssize content_size,
const char *path,
GError **error)
{
g_auto(GLnxTmpfile) args_tmpf = { 0, };
if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, name, content, content_size, error))
return FALSE;
flatpak_bwrap_add_args_data_fd (bwrap, "--ro-bind-data", glnx_steal_fd (&args_tmpf.fd), path);
return TRUE;
}
/* This resolves the target here rather than in bwrap, because it may
* not resolve in bwrap setup due to absolute symlinks conflicting
* with /newroot root. For example, dest could be inside
* ~/.var/app/XXX where XXX is an absolute symlink. However, in the
* usecases here the destination file often doesn't exist, so we
* only resolve the directory part.
*/
void
flatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,
const char *type,
const char *src,
const char *dest)
{
g_autofree char *dest_dirname = g_path_get_dirname (dest);
g_autofree char *dest_dirname_real = realpath (dest_dirname, NULL);
if (dest_dirname_real)
{
g_autofree char *dest_basename = g_path_get_basename (dest);
g_autofree char *dest_real = g_build_filename (dest_dirname_real, dest_basename, NULL);
flatpak_bwrap_add_args (bwrap, type, src, dest_real, NULL);
}
}
/*
* Convert bwrap->envp into a series of --setenv arguments for bwrap(1),
* assumed to be applied to an empty environment. Reset envp to be an
* empty environment.
*/
void
flatpak_bwrap_envp_to_args (FlatpakBwrap *bwrap)
{
gsize i;
for (i = 0; bwrap->envp[i] != NULL; i++)
{
char *key_val = bwrap->envp[i];
char *eq = strchr (key_val, '=');
if (eq)
{
flatpak_bwrap_add_arg (bwrap, "--setenv");
flatpak_bwrap_take_arg (bwrap, g_strndup (key_val, eq - key_val));
flatpak_bwrap_add_arg (bwrap, eq + 1);
}
else
{
g_warn_if_reached ();
}
}
g_strfreev (g_steal_pointer (&bwrap->envp));
bwrap->envp = g_strdupv (flatpak_bwrap_empty_env);
}
gboolean
flatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,
int start,
int end,
gboolean one_arg,
GError **error)
{
g_autofree gchar *data = NULL;
gchar *ptr;
gint i;
gsize data_len = 0;
int fd;
g_auto(GLnxTmpfile) args_tmpf = { 0, };
if (end == -1)
end = bwrap->argv->len;
for (i = start; i < end; i++)
data_len += strlen (bwrap->argv->pdata[i]) + 1;
data = g_new (gchar, data_len);
ptr = data;
for (i = start; i < end; i++)
ptr = g_stpcpy (ptr, bwrap->argv->pdata[i]) + 1;
if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, "bwrap-args", data, data_len, error))
return FALSE;
fd = glnx_steal_fd (&args_tmpf.fd);
{
g_autofree char *commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata + start, end - start);
flatpak_debug2 ("bwrap --args %d = %s", fd, commandline);
}
flatpak_bwrap_add_fd (bwrap, fd);
g_ptr_array_remove_range (bwrap->argv, start, end - start);
if (one_arg)
{
g_ptr_array_insert (bwrap->argv, start, g_strdup_printf ("--args=%d", fd));
}
else
{
g_ptr_array_insert (bwrap->argv, start, g_strdup ("--args"));
g_ptr_array_insert (bwrap->argv, start + 1, g_strdup_printf ("%d", fd));
}
return TRUE;
}
void
flatpak_bwrap_child_setup (GArray *fd_array,
gboolean close_fd_workaround)
{
int i;
if (close_fd_workaround)
flatpak_close_fds_workaround (3);
/* If no fd_array was specified, don't care. */
if (fd_array == NULL)
return;
/* Otherwise, mark not - close-on-exec all the fds in the array */
for (i = 0; i < fd_array->len; i++)
{
int fd = g_array_index (fd_array, int, i);
/* We also seek all fds to the start, because this lets
us use the same fd_array multiple times */
if (lseek (fd, 0, SEEK_SET) < 0)
{
/* Ignore the error, this happens on e.g. pipe fds */
}
fcntl (fd, F_SETFD, 0);
}
}
/* Unset FD_CLOEXEC on the array of fds passed in @user_data */
void
flatpak_bwrap_child_setup_cb (gpointer user_data)
{
GArray *fd_array = user_data;
flatpak_bwrap_child_setup (fd_array, TRUE);
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1906_1 |
crossvul-cpp_data_bad_4069_3 | /**
* @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 (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "private.h"
#include "mutt/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "gui/lib.h"
#include "mutt.h"
#include "lib.h"
#include "auth.h"
#include "commands.h"
#include "globals.h"
#include "hook.h"
#include "init.h"
#include "message.h"
#include "mutt_logging.h"
#include "mutt_socket.h"
#include "muttlib.h"
#include "mx.h"
#include "pattern.h"
#include "progress.h"
#include "sort.h"
#ifdef ENABLE_NLS
#include <libintl.h>
#endif
struct stat;
/* These Config Variables are only used in imap/imap.c */
#ifdef USE_ZLIB
bool C_ImapDeflate; ///< Config: (imap) Compress network traffic
#endif
bool C_ImapIdle; ///< Config: (imap) Use the IMAP IDLE extension to check for new mail
bool C_ImapRfc5161; ///< Config: (imap) Use the IMAP ENABLE extension to select capabilities
/**
* check_capabilities - Make sure we can log in to this server
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*/
static int check_capabilities(struct ImapAccountData *adata)
{
if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
imap_error("check_capabilities", adata->buf);
return -1;
}
if (!((adata->capabilities & IMAP_CAP_IMAP4) || (adata->capabilities & IMAP_CAP_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 NULL Failure
*
* return stream following FLAGS response
*/
static char *get_flags(struct ListHead *hflags, char *s)
{
/* sanity-check string */
const size_t plen = mutt_str_startswith(s, "FLAGS", CASE_IGNORE);
if (plen == 0)
{
mutt_debug(LL_DEBUG1, "not a FLAGS response: %s\n", s);
return NULL;
}
s += plen;
SKIPWS(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "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 != ')') && !IS_SPACE(*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(LL_DEBUG1, "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 aclflag
* @param[in] m Selected Imap Mailbox
* @param[in] aclflag Permissions, see #AclFlags
* @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 Mailbox *m, AclFlags aclflag, int flag,
const char *str, char *flags, size_t flsize)
{
if (m->rights & aclflag)
if (flag && imap_has_flag(&imap_mdata_get(m)->flags, str))
mutt_str_strcat(flags, flsize, str);
}
/**
* make_msg_set - Make a message set
* @param[in] m Selected Imap Mailbox
* @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 Mailbox *m, 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 ImapAccountData *adata = imap_adata_get(m);
if (!adata || (adata->mailbox != m))
return -1;
for (n = *pos; (n < m->msg_count) && (mutt_buffer_len(buf) < IMAP_MAX_CMDLEN); n++)
{
struct Email *e = m->emails[n];
if (!e)
break;
bool match = false; /* whether current message matches flag condition */
/* don't include pending expunged messages.
*
* TODO: can we unset active in cmd_parse_expunge() and
* cmd_parse_vanished() instead of checking for index != INT_MAX. */
if (e->active && (e->index != INT_MAX))
{
switch (flag)
{
case MUTT_DELETED:
if (e->deleted != imap_edata_get(e)->deleted)
match = invert ^ e->deleted;
break;
case MUTT_FLAG:
if (e->flagged != imap_edata_get(e)->flagged)
match = invert ^ e->flagged;
break;
case MUTT_OLD:
if (e->old != imap_edata_get(e)->old)
match = invert ^ e->old;
break;
case MUTT_READ:
if (e->read != imap_edata_get(e)->read)
match = invert ^ e->read;
break;
case MUTT_REPLIED:
if (e->replied != imap_edata_get(e)->replied)
match = invert ^ e->replied;
break;
case MUTT_TAG:
if (e->tagged)
match = true;
break;
case MUTT_TRASH:
if (e->deleted && !e->purge)
match = true;
break;
}
}
if (match && (!changed || e->changed))
{
count++;
if (setstart == 0)
{
setstart = imap_edata_get(e)->uid;
if (started)
{
mutt_buffer_add_printf(buf, ",%u", imap_edata_get(e)->uid);
}
else
{
mutt_buffer_add_printf(buf, "%u", imap_edata_get(e)->uid);
started = true;
}
}
/* tie up if the last message also matches */
else if (n == (m->msg_count - 1))
mutt_buffer_add_printf(buf, ":%u", imap_edata_get(e)->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 && (e->active || (n == adata->mailbox->msg_count - 1)))
{
if (imap_edata_get(m->emails[n - 1])->uid > setstart)
mutt_buffer_add_printf(buf, ":%u", imap_edata_get(m->emails[n - 1])->uid);
setstart = 0;
}
}
*pos = n;
return count;
}
/**
* compare_flags_for_copy - Compare local flags against the server
* @param e 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 Email *e)
{
struct ImapEmailData *edata = e->edata;
if (e->read != edata->read)
return true;
if (e->old != edata->old)
return true;
if (e->flagged != edata->flagged)
return true;
if (e->replied != edata->replied)
return true;
return false;
}
/**
* sync_helper - Sync flag changes to the server
* @param m Selected Imap Mailbox
* @param right ACL, see #AclFlags
* @param flag NeoMutt 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 Mailbox *m, AclFlags right, int flag, const char *name)
{
int count = 0;
int rc;
char buf[1024];
if (!m)
return -1;
if ((m->rights & right) == 0)
return 0;
if ((right == MUTT_ACL_WRITE) && !imap_has_flag(&imap_mdata_get(m)->flags, name))
return 0;
snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name);
rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, false);
if (rc < 0)
return rc;
count += rc;
buf[0] = '-';
rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, true);
if (rc < 0)
return rc;
count += rc;
return count;
}
/**
* 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 Connection *conn = NULL;
int rc = -1;
size_t matchlen;
matchlen = mutt_str_strlen(buf);
struct MailboxList ml = STAILQ_HEAD_INITIALIZER(ml);
neomutt_mailboxlist_get_all(&ml, NeoMutt, MUTT_MAILBOX_ANY);
struct MailboxNode *np = NULL;
STAILQ_FOREACH(np, &ml, entries)
{
if (!mutt_str_startswith(mailbox_path(np->mailbox), buf, CASE_MATCH))
continue;
if (rc)
{
mutt_str_strfcpy(buf, mailbox_path(np->mailbox), buflen);
rc = 0;
}
else
longest_common_prefix(buf, mailbox_path(np->mailbox), matchlen, buflen);
}
neomutt_mailboxlist_clear(&ml);
#if 0
TAILQ_FOREACH(conn, mutt_socket_head(), entries)
{
struct Url url = { 0 };
char urlstr[1024];
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);
}
}
#endif
return rc;
}
/**
* imap_create_mailbox - Create a new mailbox
* @param adata Imap Account data
* @param mailbox Mailbox to create
* @retval 0 Success
* @retval -1 Failure
*/
int imap_create_mailbox(struct ImapAccountData *adata, char *mailbox)
{
char buf[2048], mbox[1024];
imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), mailbox);
snprintf(buf, sizeof(buf), "CREATE %s", mbox);
if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(adata));
return -1;
}
return 0;
}
/**
* imap_access - Check permissions on an IMAP mailbox with a new connection
* @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.
* TODO: This method should take a Mailbox as parameter to be able to reuse the
* existing connection.
*/
int imap_access(const char *path)
{
if (imap_path_status(path, false) >= 0)
return 0;
return -1;
}
/**
* imap_rename_mailbox - Rename a mailbox
* @param adata Imap Account data
* @param oldname Existing mailbox
* @param newname New name for mailbox
* @retval 0 Success
* @retval -1 Failure
*/
int imap_rename_mailbox(struct ImapAccountData *adata, char *oldname, const char *newname)
{
char oldmbox[1024];
char newmbox[1024];
int rc = 0;
imap_munge_mbox_name(adata->unicode, oldmbox, sizeof(oldmbox), oldname);
imap_munge_mbox_name(adata->unicode, newmbox, sizeof(newmbox), newname);
struct Buffer *buf = mutt_buffer_pool_get();
mutt_buffer_printf(buf, "RENAME %s %s", oldmbox, newmbox);
if (imap_exec(adata, mutt_b2s(buf), IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
rc = -1;
mutt_buffer_pool_release(&buf);
return rc;
}
/**
* imap_delete_mailbox - Delete a mailbox
* @param m Mailbox
* @param path name of the mailbox to delete
* @retval 0 Success
* @retval -1 Failure
*/
int imap_delete_mailbox(struct Mailbox *m, char *path)
{
char buf[PATH_MAX + 7];
char mbox[PATH_MAX];
struct Url *url = url_parse(path);
struct ImapAccountData *adata = imap_adata_get(m);
imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), url->path);
url_free(&url);
snprintf(buf, sizeof(buf), "DELETE %s", mbox);
if (imap_exec(m->account->adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
return -1;
return 0;
}
/**
* imap_logout - Gracefully log out of server
* @param adata Imap Account data
*/
static void imap_logout(struct ImapAccountData *adata)
{
/* 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) */
if (adata->state == IMAP_DISCONNECTED)
{
return;
}
adata->status = IMAP_BYE;
imap_cmd_start(adata, "LOGOUT");
if ((C_ImapPollTimeout <= 0) || (mutt_socket_poll(adata->conn, C_ImapPollTimeout) != 0))
{
while (imap_cmd_step(adata) == IMAP_RES_CONTINUE)
; // do nothing
}
mutt_socket_close(adata->conn);
adata->state = IMAP_DISCONNECTED;
}
/**
* 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 Account *np = NULL;
TAILQ_FOREACH(np, &NeoMutt->accounts, entries)
{
if (np->type != MUTT_IMAP)
continue;
struct ImapAccountData *adata = np->adata;
if (!adata)
continue;
struct Connection *conn = adata->conn;
if (!conn || (conn->fd < 0))
continue;
mutt_message(_("Closing connection to %s..."), conn->account.host);
imap_logout(np->adata);
mutt_clear_error();
}
}
/**
* imap_read_literal - Read bytes bytes from server into file
* @param fp File handle for email file
* @param adata Imap Account 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 ImapAccountData *adata,
unsigned long bytes, struct Progress *pbar)
{
char c;
bool r = false;
struct Buffer buf = { 0 }; // Do not allocate, maybe it won't be used
if (C_DebugLevel >= IMAP_LOG_LTRL)
mutt_buffer_alloc(&buf, bytes + 10);
mutt_debug(LL_DEBUG2, "reading %ld bytes\n", bytes);
for (unsigned long pos = 0; pos < bytes; pos++)
{
if (mutt_socket_readchar(adata->conn, &c) != 1)
{
mutt_debug(LL_DEBUG1, "error during read, %ld bytes read\n", pos);
adata->status = IMAP_FATAL;
mutt_buffer_dealloc(&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 (C_DebugLevel >= IMAP_LOG_LTRL)
mutt_buffer_addch(&buf, c);
}
if (C_DebugLevel >= IMAP_LOG_LTRL)
{
mutt_debug(IMAP_LOG_LTRL, "\n%s", buf.data);
mutt_buffer_dealloc(&buf);
}
return 0;
}
/**
* imap_expunge_mailbox - Purge messages from the server
* @param m Mailbox
*
* 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 Mailbox *m)
{
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!adata || !mdata)
return;
struct Email *e = NULL;
#ifdef USE_HCACHE
mdata->hcache = imap_hcache_open(adata, mdata);
#endif
for (int i = 0; i < m->msg_count; i++)
{
e = m->emails[i];
if (!e)
break;
if (e->index == INT_MAX)
{
mutt_debug(LL_DEBUG2, "Expunging message UID %u\n", imap_edata_get(e)->uid);
e->deleted = true;
imap_cache_del(m, e);
#ifdef USE_HCACHE
imap_hcache_del(mdata, imap_edata_get(e)->uid);
#endif
mutt_hash_int_delete(mdata->uid_hash, imap_edata_get(e)->uid, e);
imap_edata_free((void **) &e->edata);
}
else
{
e->index = i;
/* NeoMutt has several places where it turns off e->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 ctx_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. */
e->active = true;
}
}
#ifdef USE_HCACHE
imap_hcache_close(mdata);
#endif
mailbox_changed(m, NT_MAILBOX_UPDATE);
mailbox_changed(m, NT_MAILBOX_RESORT);
}
/**
* imap_open_connection - Open an IMAP connection
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*/
int imap_open_connection(struct ImapAccountData *adata)
{
if (mutt_socket_open(adata->conn) < 0)
return -1;
adata->state = IMAP_CONNECTED;
if (imap_cmd_step(adata) != IMAP_RES_OK)
{
imap_close_connection(adata);
return -1;
}
if (mutt_str_startswith(adata->buf, "* OK", CASE_IGNORE))
{
if (!mutt_str_startswith(adata->buf, "* OK [CAPABILITY", CASE_IGNORE) &&
check_capabilities(adata))
{
goto bail;
}
#ifdef USE_SSL
/* Attempt STARTTLS if available and desired. */
if (!adata->conn->ssf && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS)))
{
enum QuadOption ans;
if (C_SslForceTls)
ans = MUTT_YES;
else if ((ans = query_quadoption(C_SslStarttls,
_("Secure connection with TLS?"))) == MUTT_ABORT)
{
goto err_close_conn;
}
if (ans == MUTT_YES)
{
enum ImapExecResult rc = imap_exec(adata, "STARTTLS", IMAP_CMD_NO_FLAGS);
if (rc == IMAP_EXEC_FATAL)
goto bail;
if (rc != IMAP_EXEC_ERROR)
{
if (mutt_ssl_starttls(adata->conn))
{
mutt_error(_("Could not negotiate TLS connection"));
goto err_close_conn;
}
else
{
/* RFC2595 demands we recheck CAPABILITY after TLS completes. */
if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS))
goto bail;
}
}
}
}
if (C_SslForceTls && !adata->conn->ssf)
{
mutt_error(_("Encrypted connection unavailable"));
goto err_close_conn;
}
#endif
}
else if (mutt_str_startswith(adata->buf, "* PREAUTH", CASE_IGNORE))
{
#ifdef USE_SSL
/* An unencrypted PREAUTH response is most likely a MITM attack.
* Require a confirmation. */
if (adata->conn->ssf == 0)
{
bool proceed = true;
if (C_SslForceTls)
{
proceed = false;
}
else if (C_SslStarttls != MUTT_NO)
{
proceed = mutt_yesorno(_("Abort unencrypted PREAUTH connection?"),
C_SslStarttls) != MUTT_NO;
}
if (!proceed)
{
mutt_error(_("Encrypted connection unavailable"));
goto err_close_conn;
}
}
#endif
adata->state = IMAP_AUTHENTICATED;
if (check_capabilities(adata) != 0)
goto bail;
FREE(&adata->capstr);
}
else
{
imap_error("imap_open_connection()", adata->buf);
goto bail;
}
return 0;
#ifdef USE_SSL
err_close_conn:
imap_close_connection(adata);
#endif
bail:
FREE(&adata->capstr);
return -1;
}
/**
* imap_close_connection - Close an IMAP connection
* @param adata Imap Account data
*/
void imap_close_connection(struct ImapAccountData *adata)
{
if (adata->state != IMAP_DISCONNECTED)
{
mutt_socket_close(adata->conn);
adata->state = IMAP_DISCONNECTED;
}
adata->seqno = 0;
adata->nextcmd = 0;
adata->lastcmd = 0;
adata->status = 0;
memset(adata->cmds, 0, sizeof(struct ImapCommand) * adata->cmdslots);
}
/**
* 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 '\*'. Note that "flag" might contain additional
* whitespace at the end, so we really need to compare up to the length of each
* element in "flag_list".
*/
bool imap_has_flag(struct ListHead *flag_list, const char *flag)
{
if (STAILQ_EMPTY(flag_list))
return false;
const size_t flaglen = mutt_str_strlen(flag);
struct ListNode *np = NULL;
STAILQ_FOREACH(np, flag_list, entries)
{
const size_t nplen = strlen(np->data);
if ((flaglen >= nplen) && ((flag[nplen] == '\0') || (flag[nplen] == ' ')) &&
(mutt_str_strncasecmp(np->data, flag, nplen) == 0))
{
return true;
}
if (mutt_str_strcmp(np->data, "\\*") == 0)
return true;
}
return false;
}
/**
* compare_uid - Compare two Emails by UID - Implements ::sort_t
*/
static int compare_uid(const void *a, const void *b)
{
const struct Email *ea = *(struct Email const *const *) a;
const struct Email *eb = *(struct Email const *const *) b;
return imap_edata_get((struct Email *) ea)->uid -
imap_edata_get((struct Email *) eb)->uid;
}
/**
* imap_exec_msgset - Prepare commands for all messages matching conditions
* @param m Selected Imap Mailbox
* @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 Mailbox *m, const char *pre, const char *post,
int flag, bool changed, bool invert)
{
struct ImapAccountData *adata = imap_adata_get(m);
if (!adata || (adata->mailbox != m))
return -1;
struct Email **emails = NULL;
short oldsort;
int pos;
int rc;
int count = 0;
struct Buffer cmd = mutt_buffer_make(0);
/* 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 = C_Sort;
if (C_Sort != SORT_ORDER)
{
emails = m->emails;
// We overcommit here, just in case new mail arrives whilst we're sync-ing
m->emails = mutt_mem_malloc(m->email_max * sizeof(struct Email *));
memcpy(m->emails, emails, m->email_max * sizeof(struct Email *));
C_Sort = SORT_ORDER;
qsort(m->emails, m->msg_count, sizeof(struct Email *), compare_uid);
}
pos = 0;
do
{
mutt_buffer_reset(&cmd);
mutt_buffer_add_printf(&cmd, "%s ", pre);
rc = make_msg_set(m, &cmd, flag, changed, invert, &pos);
if (rc > 0)
{
mutt_buffer_add_printf(&cmd, " %s", post);
if (imap_exec(adata, cmd.data, IMAP_CMD_QUEUE) != IMAP_EXEC_SUCCESS)
{
rc = -1;
goto out;
}
count += rc;
}
} while (rc > 0);
rc = count;
out:
mutt_buffer_dealloc(&cmd);
if (oldsort != C_Sort)
{
C_Sort = oldsort;
FREE(&m->emails);
m->emails = emails;
}
return rc;
}
/**
* imap_sync_message_for_copy - Update server to reflect the flags of a single message
* @param[in] m Mailbox
* @param[in] e 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 Mailbox *m, struct Email *e,
struct Buffer *cmd, enum QuadOption *err_continue)
{
struct ImapAccountData *adata = imap_adata_get(m);
if (!adata || (adata->mailbox != m))
return -1;
char flags[1024];
char *tags = NULL;
char uid[11];
if (!compare_flags_for_copy(e))
{
if (e->deleted == imap_edata_get(e)->deleted)
e->changed = false;
return 0;
}
snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid);
mutt_buffer_reset(cmd);
mutt_buffer_addstr(cmd, "UID STORE ");
mutt_buffer_addstr(cmd, uid);
flags[0] = '\0';
set_flag(m, MUTT_ACL_SEEN, e->read, "\\Seen ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, e->old, "Old ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, e->flagged, "\\Flagged ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, e->replied, "\\Answered ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_DELETE, imap_edata_get(e)->deleted, "\\Deleted ", flags,
sizeof(flags));
if (m->rights & MUTT_ACL_WRITE)
{
/* restore system flags */
if (imap_edata_get(e)->flags_system)
mutt_str_strcat(flags, sizeof(flags), imap_edata_get(e)->flags_system);
/* set custom flags */
tags = driver_tags_get_with_hidden(&e->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 == '\0')
{
set_flag(m, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_DELETE, !imap_edata_get(e)->deleted, "\\Deleted ",
flags, sizeof(flags));
/* erase custom flags */
if ((m->rights & MUTT_ACL_WRITE) && imap_edata_get(e)->flags_remote)
mutt_str_strcat(flags, sizeof(flags), imap_edata_get(e)->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, ")");
/* after all this it's still possible to have no flags, if you
* have no ACL rights */
if (*flags && (imap_exec(adata, cmd->data, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) &&
err_continue && (*err_continue != MUTT_YES))
{
*err_continue = imap_continue("imap_sync_message: STORE failed", adata->buf);
if (*err_continue != MUTT_YES)
return -1;
}
/* server have now the updated flags */
FREE(&imap_edata_get(e)->flags_remote);
imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags);
if (e->deleted == imap_edata_get(e)->deleted)
e->changed = false;
return 0;
}
/**
* imap_check_mailbox - use the NOOP or IDLE command to poll for new mail
* @param m Mailbox
* @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 Mailbox *m, bool force)
{
if (!m || !m->account)
return -1;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
/* 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 rc = 0;
/* try IDLE first, unless force is set */
if (!force && C_ImapIdle && (adata->capabilities & IMAP_CAP_IDLE) &&
((adata->state != IMAP_IDLE) || (mutt_date_epoch() >= adata->lastread + C_ImapKeepalive)))
{
if (imap_cmd_idle(adata) < 0)
return -1;
}
if (adata->state == IMAP_IDLE)
{
while ((rc = mutt_socket_poll(adata->conn, 0)) > 0)
{
if (imap_cmd_step(adata) != IMAP_RES_CONTINUE)
{
mutt_debug(LL_DEBUG1, "Error reading IDLE response\n");
return -1;
}
}
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "Poll failed, disabling IDLE\n");
adata->capabilities &= ~IMAP_CAP_IDLE; // Clear the flag
}
}
if ((force || ((adata->state != IMAP_IDLE) &&
(mutt_date_epoch() >= adata->lastread + C_Timeout))) &&
(imap_exec(adata, "NOOP", IMAP_CMD_POLL) != IMAP_EXEC_SUCCESS))
{
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(adata);
if (mdata->check_status & IMAP_EXPUNGE_PENDING)
rc = MUTT_REOPENED;
else if (mdata->check_status & IMAP_NEWMAIL_PENDING)
rc = MUTT_NEW_MAIL;
else if (mdata->check_status & IMAP_FLAGS_PENDING)
rc = MUTT_FLAGS;
mdata->check_status = IMAP_OPEN_NO_FLAGS;
return rc;
}
/**
* imap_status - Refresh the number of total and new messages
* @param adata IMAP Account data
* @param mdata IMAP Mailbox data
* @param queue Queue the STATUS command
* @retval num Total number of messages
*/
static int imap_status(struct ImapAccountData *adata, struct ImapMboxData *mdata, bool queue)
{
char *uidvalidity_flag = NULL;
char cmd[2048];
if (!adata || !mdata)
return -1;
/* Don't issue STATUS on the selected mailbox, it will be NOOPed or
* IDLEd elsewhere.
* adata->mailbox may be NULL for connections other than the current
* mailbox's. */
if (adata->mailbox && (adata->mailbox->mdata == mdata))
{
adata->mailbox->has_new = false;
return mdata->messages;
}
if (adata->capabilities & IMAP_CAP_IMAP4REV1)
uidvalidity_flag = "UIDVALIDITY";
else if (adata->capabilities & IMAP_CAP_STATUS)
uidvalidity_flag = "UID-VALIDITY";
else
{
mutt_debug(LL_DEBUG2, "Server doesn't support STATUS\n");
return -1;
}
snprintf(cmd, sizeof(cmd), "STATUS %s (UIDNEXT %s UNSEEN RECENT MESSAGES)",
mdata->munge_name, uidvalidity_flag);
int rc = imap_exec(adata, cmd, queue ? IMAP_CMD_QUEUE : IMAP_CMD_NO_FLAGS | IMAP_CMD_POLL);
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "Error queueing command\n");
return rc;
}
return mdata->messages;
}
/**
* imap_mbox_check_stats - Check the Mailbox statistics - Implements MxOps::mbox_check_stats()
*/
static int imap_mbox_check_stats(struct Mailbox *m, int flags)
{
return imap_mailbox_status(m, true);
}
/**
* imap_path_status - Refresh the number of total and new messages
* @param path Mailbox path
* @param queue Queue the STATUS command
* @retval num Total number of messages
*/
int imap_path_status(const char *path, bool queue)
{
struct Mailbox *m = mx_mbox_find2(path);
if (m)
return imap_mailbox_status(m, queue);
// FIXME(sileht): Is that case possible ?
struct ImapAccountData *adata = NULL;
struct ImapMboxData *mdata = NULL;
if (imap_adata_find(path, &adata, &mdata) < 0)
return -1;
int rc = imap_status(adata, mdata, queue);
imap_mdata_free((void *) &mdata);
return rc;
}
/**
* imap_mailbox_status - Refresh the number of total and new messages
* @param m Mailbox
* @param queue Queue the STATUS command
* @retval num Total number of messages
* @retval -1 Error
*
* @note Prepare the mailbox if we are not connected
*/
int imap_mailbox_status(struct Mailbox *m, bool queue)
{
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!adata || !mdata)
return -1;
return imap_status(adata, mdata, queue);
}
/**
* 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 ImapAccountData *adata = NULL;
struct ImapMboxData *mdata = NULL;
char buf[2048];
struct Buffer err;
if (imap_adata_find(path, &adata, &mdata) < 0)
return -1;
if (C_ImapCheckSubscribed)
{
char mbox[1024];
mutt_buffer_init(&err);
err.dsize = 256;
err.data = mutt_mem_malloc(err.dsize);
size_t len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un");
imap_quote_string(mbox + len, sizeof(mbox) - len, path, true);
if (mutt_parse_rc_line(mbox, &err))
mutt_debug(LL_DEBUG1, "Error adding subscribed mailbox: %s\n", err.data);
FREE(&err.data);
}
if (subscribe)
mutt_message(_("Subscribing to %s..."), mdata->name);
else
mutt_message(_("Unsubscribing from %s..."), mdata->name);
snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mdata->munge_name);
if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
imap_mdata_free((void *) &mdata);
return -1;
}
if (subscribe)
mutt_message(_("Subscribed to %s"), mdata->name);
else
mutt_message(_("Unsubscribed from %s"), mdata->name);
imap_mdata_free((void *) &mdata);
return 0;
}
/**
* 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, const char *path)
{
struct ImapAccountData *adata = NULL;
struct ImapMboxData *mdata = NULL;
char tmp[2048];
struct ImapList listresp = { 0 };
char completion[1024];
int clen;
size_t matchlen = 0;
int completions = 0;
int rc;
if (imap_adata_find(path, &adata, &mdata) < 0)
{
mutt_str_strfcpy(buf, path, buflen);
return complete_hosts(buf, buflen);
}
/* fire off command */
snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"",
C_ImapListSubscribed ? "LSUB" : "LIST", mdata->real_name);
imap_cmd_start(adata, tmp);
/* and see what the results are */
mutt_str_strfcpy(completion, mdata->name, sizeof(completion));
imap_mdata_free((void *) &mdata);
adata->cmdresult = &listresp;
do
{
listresp.name = NULL;
rc = imap_cmd_step(adata);
if ((rc == IMAP_RES_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_RES_CONTINUE);
adata->cmdresult = NULL;
if (completions)
{
/* reformat output */
imap_qualify_path(buf, buflen, &adata->conn->account, completion);
mutt_pretty_mailbox(buf, buflen);
return 0;
}
return -1;
}
/**
* imap_fast_trash - Use server COPY command to copy deleted messages to trash
* @param m Mailbox
* @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 Mailbox *m, char *dest)
{
char prompt[1024];
int rc = -1;
bool triedcreate = false;
enum QuadOption err_continue = MUTT_NO;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapAccountData *dest_adata = NULL;
struct ImapMboxData *dest_mdata = NULL;
if (imap_adata_find(dest, &dest_adata, &dest_mdata) < 0)
return -1;
struct Buffer sync_cmd = mutt_buffer_make(0);
/* check that the save-to folder is in the same account */
if (!imap_account_match(&(adata->conn->account), &(dest_adata->conn->account)))
{
mutt_debug(LL_DEBUG3, "%s not same server as %s\n", dest, mailbox_path(m));
goto out;
}
for (int i = 0; i < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
if (e->active && e->changed && e->deleted && !e->purge)
{
rc = imap_sync_message_for_copy(m, e, &sync_cmd, &err_continue);
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "could not sync\n");
goto out;
}
}
}
/* loop in case of TRYCREATE */
do
{
rc = imap_exec_msgset(m, "UID COPY", dest_mdata->munge_name, MUTT_TRASH, false, false);
if (rc == 0)
{
mutt_debug(LL_DEBUG1, "No messages to trash\n");
rc = -1;
goto out;
}
else if (rc < 0)
{
mutt_debug(LL_DEBUG1, "could not queue copy\n");
goto out;
}
else if (m->verbose)
{
mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc),
rc, dest_mdata->name);
}
/* let's get it on */
rc = imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS);
if (rc == IMAP_EXEC_ERROR)
{
if (triedcreate)
{
mutt_debug(LL_DEBUG1, "Already tried to create mailbox %s\n", dest_mdata->name);
break;
}
/* bail out if command failed for reasons other than nonexistent target */
if (!mutt_str_startswith(imap_get_qualifier(adata->buf), "[TRYCREATE]", CASE_IGNORE))
break;
mutt_debug(LL_DEBUG3, "server suggests TRYCREATE\n");
snprintf(prompt, sizeof(prompt), _("Create %s?"), dest_mdata->name);
if (C_Confirmcreate && (mutt_yesorno(prompt, MUTT_YES) != MUTT_YES))
{
mutt_clear_error();
goto out;
}
if (imap_create_mailbox(adata, dest_mdata->name) < 0)
break;
triedcreate = true;
}
} while (rc == IMAP_EXEC_ERROR);
if (rc != IMAP_EXEC_SUCCESS)
{
imap_error("imap_fast_trash", adata->buf);
goto out;
}
rc = IMAP_EXEC_SUCCESS;
out:
mutt_buffer_dealloc(&sync_cmd);
imap_mdata_free((void *) &dest_mdata);
return ((rc == IMAP_EXEC_SUCCESS) ? 0 : -1);
}
/**
* imap_sync_mailbox - Sync all the changes to the server
* @param m Mailbox
* @param expunge if true do expunge
* @param close if true we move imap state to CLOSE
* @retval #MUTT_REOPENED mailbox has been externally modified
* @retval #MUTT_NEW_MAIL new mail has arrived
* @retval 0 Success
* @retval -1 Error
*
* @note The flag retvals come from a call to imap_check_mailbox()
*/
int imap_sync_mailbox(struct Mailbox *m, bool expunge, bool close)
{
if (!m)
return -1;
struct Email **emails = NULL;
int oldsort;
int rc;
int check;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (adata->state < IMAP_SELECTED)
{
mutt_debug(LL_DEBUG2, "no mailbox selected\n");
return -1;
}
/* This function is only called when the calling code expects the context
* to be changed. */
imap_allow_reopen(m);
check = imap_check_mailbox(m, false);
if (check < 0)
return check;
/* if we are expunging anyway, we can do deleted messages very quickly... */
if (expunge && (m->rights & MUTT_ACL_DELETE))
{
rc = imap_exec_msgset(m, "UID STORE", "+FLAGS.SILENT (\\Deleted)",
MUTT_DELETED, true, false);
if (rc < 0)
{
mutt_error(_("Expunge failed"));
return rc;
}
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 < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
if (e->deleted && e->changed)
e->active = false;
}
if (m->verbose)
{
mutt_message(ngettext("Marking %d message deleted...",
"Marking %d messages deleted...", rc),
rc);
}
}
}
#ifdef USE_HCACHE
mdata->hcache = imap_hcache_open(adata, mdata);
#endif
/* save messages with real (non-flag) changes */
for (int i = 0; i < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
if (e->deleted)
{
imap_cache_del(m, e);
#ifdef USE_HCACHE
imap_hcache_del(mdata, imap_edata_get(e)->uid);
#endif
}
if (e->active && e->changed)
{
#ifdef USE_HCACHE
imap_hcache_put(mdata, e);
#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. */
/* TODO: why the e->env check? */
if ((e->env && e->env->changed) || e->attach_del)
{
/* L10N: The plural is chosen by the last %d, i.e. the total number */
if (m->verbose)
{
mutt_message(ngettext("Saving changed message... [%d/%d]",
"Saving changed messages... [%d/%d]", m->msg_count),
i + 1, m->msg_count);
}
bool save_append = m->append;
m->append = true;
mutt_save_message_ctx(e, true, false, false, m);
m->append = save_append;
/* TODO: why the check for h->env? Is this possible? */
if (e->env)
e->env->changed = 0;
}
}
}
#ifdef USE_HCACHE
imap_hcache_close(mdata);
#endif
/* presort here to avoid doing 10 resorts in imap_exec_msgset */
oldsort = C_Sort;
if (C_Sort != SORT_ORDER)
{
emails = m->emails;
m->emails = mutt_mem_malloc(m->msg_count * sizeof(struct Email *));
memcpy(m->emails, emails, m->msg_count * sizeof(struct Email *));
C_Sort = SORT_ORDER;
qsort(m->emails, m->msg_count, sizeof(struct Email *), mutt_get_sort_func(SORT_ORDER));
}
rc = sync_helper(m, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_OLD, "Old");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_SEEN, MUTT_READ, "\\Seen");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered");
if (oldsort != C_Sort)
{
C_Sort = oldsort;
FREE(&m->emails);
m->emails = emails;
}
/* Flush the queued flags if any were changed in sync_helper. */
if (rc > 0)
if (imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
rc = -1;
if (rc < 0)
{
if (close)
{
if (mutt_yesorno(_("Error saving flags. Close anyway?"), MUTT_NO) == MUTT_YES)
{
adata->state = IMAP_AUTHENTICATED;
return 0;
}
}
else
mutt_error(_("Error saving flags"));
return -1;
}
/* 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 < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
struct ImapEmailData *edata = imap_edata_get(e);
edata->deleted = e->deleted;
edata->flagged = e->flagged;
edata->old = e->old;
edata->read = e->read;
edata->replied = e->replied;
e->changed = false;
}
m->changed = false;
/* We must send an EXPUNGE command if we're not closing. */
if (expunge && !close && (m->rights & MUTT_ACL_DELETE))
{
if (m->verbose)
mutt_message(_("Expunging messages from server..."));
/* Set expunge bit so we don't get spurious reopened messages */
mdata->reopen |= IMAP_EXPUNGE_EXPECTED;
if (imap_exec(adata, "EXPUNGE", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
imap_error(_("imap_sync_mailbox: EXPUNGE failed"), adata->buf);
return -1;
}
mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
}
if (expunge && close)
{
adata->closing = true;
imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE);
adata->state = IMAP_AUTHENTICATED;
}
if (C_MessageCacheClean)
imap_cache_clean(m);
return check;
}
/**
* imap_ac_find - Find an Account that matches a Mailbox path - Implements MxOps::ac_find()
*/
static struct Account *imap_ac_find(struct Account *a, const char *path)
{
if (!a || (a->type != MUTT_IMAP) || !path)
return NULL;
struct Url *url = url_parse(path);
if (!url)
return NULL;
struct ImapAccountData *adata = a->adata;
struct ConnAccount *cac = &adata->conn->account;
if (mutt_str_strcasecmp(url->host, cac->host) != 0)
a = NULL;
else if (url->user && (mutt_str_strcasecmp(url->user, cac->user) != 0))
a = NULL;
url_free(&url);
return a;
}
/**
* imap_ac_add - Add a Mailbox to an Account - Implements MxOps::ac_add()
*/
static int imap_ac_add(struct Account *a, struct Mailbox *m)
{
if (!a || !m || (m->type != MUTT_IMAP))
return -1;
struct ImapAccountData *adata = a->adata;
if (!adata)
{
struct ConnAccount cac = { { 0 } };
char mailbox[PATH_MAX];
if (imap_parse_path(mailbox_path(m), &cac, mailbox, sizeof(mailbox)) < 0)
return -1;
adata = imap_adata_new(a);
adata->conn = mutt_conn_new(&cac);
if (!adata->conn)
{
imap_adata_free((void **) &adata);
return -1;
}
mutt_account_hook(m->realpath);
if (imap_login(adata) < 0)
{
imap_adata_free((void **) &adata);
return -1;
}
a->adata = adata;
a->adata_free = imap_adata_free;
}
if (!m->mdata)
{
struct Url *url = url_parse(mailbox_path(m));
struct ImapMboxData *mdata = imap_mdata_new(adata, url->path);
/* fixup path and realpath, mainly to replace / by /INBOX */
char buf[1024];
imap_qualify_path(buf, sizeof(buf), &adata->conn->account, mdata->name);
mutt_buffer_strcpy(&m->pathbuf, buf);
mutt_str_replace(&m->realpath, mailbox_path(m));
m->mdata = mdata;
m->mdata_free = imap_mdata_free;
url_free(&url);
}
return 0;
}
/**
* imap_mbox_select - Select a Mailbox
* @param m Mailbox
*/
static void imap_mbox_select(struct Mailbox *m)
{
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!adata || !mdata)
return;
const char *condstore = NULL;
#ifdef USE_HCACHE
if ((adata->capabilities & IMAP_CAP_CONDSTORE) && C_ImapCondstore)
condstore = " (CONDSTORE)";
else
#endif
condstore = "";
char buf[PATH_MAX];
snprintf(buf, sizeof(buf), "%s %s%s", m->readonly ? "EXAMINE" : "SELECT",
mdata->munge_name, condstore);
adata->state = IMAP_SELECTED;
imap_cmd_start(adata, buf);
}
/**
* imap_login - Open an IMAP connection
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*
* Ensure ImapAccountData is connected and logged into the imap server.
*/
int imap_login(struct ImapAccountData *adata)
{
if (!adata)
return -1;
if (adata->state == IMAP_DISCONNECTED)
{
mutt_buffer_reset(&adata->cmdbuf); // purge outstanding queued commands
imap_open_connection(adata);
}
if (adata->state == IMAP_CONNECTED)
{
if (imap_authenticate(adata) == IMAP_AUTH_SUCCESS)
{
adata->state = IMAP_AUTHENTICATED;
FREE(&adata->capstr);
if (adata->conn->ssf)
{
mutt_debug(LL_DEBUG2, "Communication encrypted at %d bits\n",
adata->conn->ssf);
}
}
else
mutt_account_unsetpass(&adata->conn->account);
}
if (adata->state == IMAP_AUTHENTICATED)
{
/* capabilities may have changed */
imap_exec(adata, "CAPABILITY", IMAP_CMD_PASS);
#ifdef USE_ZLIB
/* RFC4978 */
if ((adata->capabilities & IMAP_CAP_COMPRESS) && C_ImapDeflate &&
(imap_exec(adata, "COMPRESS DEFLATE", IMAP_CMD_PASS) == IMAP_EXEC_SUCCESS))
{
mutt_debug(LL_DEBUG2, "IMAP compression is enabled on connection to %s\n",
adata->conn->account.host);
mutt_zstrm_wrap_conn(adata->conn);
}
#endif
/* enable RFC6855, if the server supports that */
if (C_ImapRfc5161 && (adata->capabilities & IMAP_CAP_ENABLE))
imap_exec(adata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE);
/* enable QRESYNC. Advertising QRESYNC also means CONDSTORE
* is supported (even if not advertised), so flip that bit. */
if (adata->capabilities & IMAP_CAP_QRESYNC)
{
adata->capabilities |= IMAP_CAP_CONDSTORE;
if (C_ImapRfc5161 && C_ImapQresync)
imap_exec(adata, "ENABLE QRESYNC", IMAP_CMD_QUEUE);
}
/* get root delimiter, '/' as default */
adata->delim = '/';
imap_exec(adata, "LIST \"\" \"\"", IMAP_CMD_QUEUE);
/* we may need the root delimiter before we open a mailbox */
imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS);
/* select the mailbox that used to be open before disconnect */
if (adata->mailbox)
{
imap_mbox_select(adata->mailbox);
}
}
if (adata->state < IMAP_AUTHENTICATED)
return -1;
return 0;
}
/**
* imap_mbox_open - Open a mailbox - Implements MxOps::mbox_open()
*/
static int imap_mbox_open(struct Mailbox *m)
{
if (!m || !m->account || !m->mdata)
return -1;
char buf[PATH_MAX];
int count = 0;
int rc;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
mutt_debug(LL_DEBUG3, "opening %s, saving %s\n", m->pathbuf.data,
(adata->mailbox ? adata->mailbox->pathbuf.data : "(none)"));
adata->prev_mailbox = adata->mailbox;
adata->mailbox = m;
/* clear mailbox status */
adata->status = 0;
m->rights = 0;
mdata->new_mail_count = 0;
if (m->verbose)
mutt_message(_("Selecting %s..."), mdata->name);
/* pipeline ACL test */
if (adata->capabilities & IMAP_CAP_ACL)
{
snprintf(buf, sizeof(buf), "MYRIGHTS %s", mdata->munge_name);
imap_exec(adata, buf, IMAP_CMD_QUEUE);
}
/* assume we have all rights if ACL is unavailable */
else
{
m->rights |= MUTT_ACL_LOOKUP | MUTT_ACL_READ | MUTT_ACL_SEEN | MUTT_ACL_WRITE |
MUTT_ACL_INSERT | MUTT_ACL_POST | MUTT_ACL_CREATE | MUTT_ACL_DELETE;
}
/* pipeline the postponed count if possible */
struct Mailbox *m_postponed = mx_mbox_find2(C_Postponed);
struct ImapAccountData *postponed_adata = imap_adata_get(m_postponed);
if (postponed_adata &&
imap_account_match(&postponed_adata->conn->account, &adata->conn->account))
{
imap_mailbox_status(m_postponed, true);
}
if (C_ImapCheckSubscribed)
imap_exec(adata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE);
imap_mbox_select(m);
do
{
char *pc = NULL;
rc = imap_cmd_step(adata);
if (rc != IMAP_RES_CONTINUE)
break;
pc = adata->buf + 2;
/* Obtain list of available flags here, may be overridden by a
* PERMANENTFLAGS tag in the OK response */
if (mutt_str_startswith(pc, "FLAGS", CASE_IGNORE))
{
/* don't override PERMANENTFLAGS */
if (STAILQ_EMPTY(&mdata->flags))
{
mutt_debug(LL_DEBUG3, "Getting mailbox FLAGS\n");
pc = get_flags(&mdata->flags, pc);
if (!pc)
goto fail;
}
}
/* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
else if (mutt_str_startswith(pc, "OK [PERMANENTFLAGS", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox PERMANENTFLAGS\n");
/* safe to call on NULL */
mutt_list_free(&mdata->flags);
/* skip "OK [PERMANENT" so syntax is the same as FLAGS */
pc += 13;
pc = get_flags(&(mdata->flags), pc);
if (!pc)
goto fail;
}
/* save UIDVALIDITY for the header cache */
else if (mutt_str_startswith(pc, "OK [UIDVALIDITY", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox UIDVALIDITY\n");
pc += 3;
pc = imap_next_word(pc);
if (mutt_str_atoui(pc, &mdata->uidvalidity) < 0)
goto fail;
}
else if (mutt_str_startswith(pc, "OK [UIDNEXT", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox UIDNEXT\n");
pc += 3;
pc = imap_next_word(pc);
if (mutt_str_atoui(pc, &mdata->uid_next) < 0)
goto fail;
}
else if (mutt_str_startswith(pc, "OK [HIGHESTMODSEQ", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox HIGHESTMODSEQ\n");
pc += 3;
pc = imap_next_word(pc);
if (mutt_str_atoull(pc, &mdata->modseq) < 0)
goto fail;
}
else if (mutt_str_startswith(pc, "OK [NOMODSEQ", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Mailbox has NOMODSEQ set\n");
mdata->modseq = 0;
}
else
{
pc = imap_next_word(pc);
if (mutt_str_startswith(pc, "EXISTS", CASE_IGNORE))
{
count = mdata->new_mail_count;
mdata->new_mail_count = 0;
}
}
} while (rc == IMAP_RES_CONTINUE);
if (rc == IMAP_RES_NO)
{
char *s = imap_next_word(adata->buf); /* skip seq */
s = imap_next_word(s); /* Skip response */
mutt_error("%s", s);
goto fail;
}
if (rc != IMAP_RES_OK)
goto fail;
/* check for READ-ONLY notification */
if (mutt_str_startswith(imap_get_qualifier(adata->buf), "[READ-ONLY]", CASE_IGNORE) &&
!(adata->capabilities & IMAP_CAP_ACL))
{
mutt_debug(LL_DEBUG2, "Mailbox is read-only\n");
m->readonly = true;
}
/* dump the mailbox flags we've found */
if (C_DebugLevel > LL_DEBUG2)
{
if (STAILQ_EMPTY(&mdata->flags))
mutt_debug(LL_DEBUG3, "No folder flags found\n");
else
{
struct ListNode *np = NULL;
struct Buffer flag_buffer;
mutt_buffer_init(&flag_buffer);
mutt_buffer_printf(&flag_buffer, "Mailbox flags: ");
STAILQ_FOREACH(np, &mdata->flags, entries)
{
mutt_buffer_add_printf(&flag_buffer, "[%s] ", np->data);
}
mutt_debug(LL_DEBUG3, "%s\n", flag_buffer.data);
FREE(&flag_buffer.data);
}
}
if (!((m->rights & MUTT_ACL_DELETE) || (m->rights & MUTT_ACL_SEEN) ||
(m->rights & MUTT_ACL_WRITE) || (m->rights & MUTT_ACL_INSERT)))
{
m->readonly = true;
}
while (m->email_max < count)
mx_alloc_memory(m);
m->msg_count = 0;
m->msg_unread = 0;
m->msg_flagged = 0;
m->msg_new = 0;
m->msg_deleted = 0;
m->size = 0;
m->vcount = 0;
if (count && (imap_read_headers(m, 1, count, true) < 0))
{
mutt_error(_("Error opening mailbox"));
goto fail;
}
mutt_debug(LL_DEBUG2, "msg_count is %d\n", m->msg_count);
return 0;
fail:
if (adata->state == IMAP_SELECTED)
adata->state = IMAP_AUTHENTICATED;
return -1;
}
/**
* imap_mbox_open_append - Open a Mailbox for appending - Implements MxOps::mbox_open_append()
*/
static int imap_mbox_open_append(struct Mailbox *m, OpenMailboxFlags flags)
{
if (!m || !m->account)
return -1;
/* in APPEND mode, we appear to hijack an existing IMAP connection -
* ctx is brand new and mostly empty */
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
int rc = imap_mailbox_status(m, false);
if (rc >= 0)
return 0;
if (rc == -1)
return -1;
char buf[PATH_MAX + 64];
snprintf(buf, sizeof(buf), _("Create %s?"), mdata->name);
if (C_Confirmcreate && (mutt_yesorno(buf, MUTT_YES) != MUTT_YES))
return -1;
if (imap_create_mailbox(adata, mdata->name) < 0)
return -1;
return 0;
}
/**
* imap_mbox_check - Check for new mail - Implements MxOps::mbox_check()
* @param m Mailbox
* @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 Mailbox *m, int *index_hint)
{
if (!m)
return -1;
imap_allow_reopen(m);
int rc = imap_check_mailbox(m, false);
/* NOTE - ctx might have been changed at this point. In particular,
* m could be NULL. Beware. */
imap_disallow_reopen(m);
return rc;
}
/**
* imap_mbox_close - Close a Mailbox - Implements MxOps::mbox_close()
*/
static int imap_mbox_close(struct Mailbox *m)
{
if (!m)
return -1;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
/* Check to see if the mailbox is actually open */
if (!adata || !mdata)
return 0;
/* imap_mbox_open_append() borrows the struct ImapAccountData temporarily,
* just for the connection.
*
* So when these are equal, it means we are actually closing the
* mailbox and should clean up adata. Otherwise, we don't want to
* touch adata - it's still being used. */
if (m == adata->mailbox)
{
if ((adata->status != IMAP_FATAL) && (adata->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 (m->msg_deleted == 0)
{
adata->closing = true;
imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE);
}
adata->state = IMAP_AUTHENTICATED;
}
mutt_debug(LL_DEBUG3, "closing %s, restoring %s\n", m->pathbuf.data,
(adata->prev_mailbox ? adata->prev_mailbox->pathbuf.data : "(none)"));
adata->mailbox = adata->prev_mailbox;
imap_mbox_select(adata->prev_mailbox);
imap_mdata_cache_reset(m->mdata);
}
return 0;
}
/**
* imap_msg_open_new - Open a new message in a Mailbox - Implements MxOps::msg_open_new()
*/
static int imap_msg_open_new(struct Mailbox *m, struct Message *msg, struct Email *e)
{
int rc = -1;
struct Buffer *tmp = mutt_buffer_pool_get();
mutt_buffer_mktemp(tmp);
msg->fp = mutt_file_fopen(mutt_b2s(tmp), "w");
if (!msg->fp)
{
mutt_perror(mutt_b2s(tmp));
goto cleanup;
}
msg->path = mutt_buffer_strdup(tmp);
rc = 0;
cleanup:
mutt_buffer_pool_release(&tmp);
return rc;
}
/**
* imap_tags_edit - Prompt and validate new messages tags - Implements MxOps::tags_edit()
*/
static int imap_tags_edit(struct Mailbox *m, const char *tags, char *buf, size_t buflen)
{
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!mdata)
return -1;
char *new_tag = NULL;
char *checker = NULL;
/* Check for \* flags capability */
if (!imap_has_flag(&mdata->flags, NULL))
{
mutt_error(_("IMAP server doesn't support custom flags"));
return -1;
}
*buf = '\0';
if (tags)
mutt_str_strfcpy(buf, tags, buflen);
if (mutt_get_field("Tags: ", buf, buflen, MUTT_COMP_NO_FLAGS) != 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_tag = 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[0] == ' ') && (checker[1] == ' '))
checker++;
/* copy char to new_tag and go the next one */
*new_tag++ = *checker++;
}
*new_tag = '\0';
new_tag = buf; /* rewind */
mutt_str_remove_trailing_ws(new_tag);
if (mutt_str_strcmp(tags, buf) == 0)
return 0;
return 1;
}
/**
* imap_tags_commit - Save the tags to a message - 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 Mailbox *m, struct Email *e, char *buf)
{
if (!m)
return -1;
char uid[11];
struct ImapAccountData *adata = imap_adata_get(m);
if (*buf == '\0')
buf = NULL;
if (!(adata->mailbox->rights & MUTT_ACL_WRITE))
return 0;
snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid);
/* Remove old custom flags */
if (imap_edata_get(e)->flags_remote)
{
struct Buffer cmd = mutt_buffer_make(128); // just a guess
mutt_buffer_addstr(&cmd, "UID STORE ");
mutt_buffer_addstr(&cmd, uid);
mutt_buffer_addstr(&cmd, " -FLAGS.SILENT (");
mutt_buffer_addstr(&cmd, imap_edata_get(e)->flags_remote);
mutt_buffer_addstr(&cmd, ")");
/* Should we return here, or we are fine and we could
* continue to add new flags */
int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS);
mutt_buffer_dealloc(&cmd);
if (rc != IMAP_EXEC_SUCCESS)
{
return -1;
}
}
/* Add new custom flags */
if (buf)
{
struct Buffer cmd = mutt_buffer_make(128); // just a guess
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, ")");
int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS);
mutt_buffer_dealloc(&cmd);
if (rc != IMAP_EXEC_SUCCESS)
{
mutt_debug(LL_DEBUG1, "fail to add new flags\n");
return -1;
}
}
/* We are good sync them */
mutt_debug(LL_DEBUG1, "NEW TAGS: %s\n", buf);
driver_tags_replace(&e->tags, buf);
FREE(&imap_edata_get(e)->flags_remote);
imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags);
return 0;
}
/**
* imap_path_probe - Is this an IMAP Mailbox? - Implements MxOps::path_probe()
*/
enum MailboxType imap_path_probe(const char *path, const struct stat *st)
{
if (!path)
return MUTT_UNKNOWN;
if (mutt_str_startswith(path, "imap://", CASE_IGNORE))
return MUTT_IMAP;
if (mutt_str_startswith(path, "imaps://", CASE_IGNORE))
return MUTT_IMAP;
return MUTT_UNKNOWN;
}
/**
* imap_path_canon - Canonicalise a Mailbox path - Implements MxOps::path_canon()
*/
int imap_path_canon(char *buf, size_t buflen)
{
if (!buf)
return -1;
struct Url *url = url_parse(buf);
if (!url)
return 0;
char tmp[PATH_MAX];
char tmp2[PATH_MAX];
imap_fix_path('\0', url->path, tmp, sizeof(tmp));
url->path = tmp;
url_tostring(url, tmp2, sizeof(tmp2), 0);
mutt_str_strfcpy(buf, tmp2, buflen);
url_free(&url);
return 0;
}
/**
* imap_expand_path - Buffer wrapper around imap_path_canon()
* @param buf Path to expand
* @retval 0 Success
* @retval -1 Failure
*
* @note The path is expanded in place
*/
int imap_expand_path(struct Buffer *buf)
{
mutt_buffer_alloc(buf, PATH_MAX);
return imap_path_canon(buf->data, PATH_MAX);
}
/**
* imap_path_pretty - Abbreviate a Mailbox path - Implements MxOps::path_pretty()
*/
static int imap_path_pretty(char *buf, size_t buflen, const char *folder)
{
if (!buf || !folder)
return -1;
imap_pretty_mailbox(buf, buflen, folder);
return 0;
}
/**
* imap_path_parent - Find the parent of a Mailbox path - Implements MxOps::path_parent()
*/
static int imap_path_parent(char *buf, size_t buflen)
{
char tmp[PATH_MAX] = { 0 };
imap_get_parent_path(buf, tmp, sizeof(tmp));
mutt_str_strfcpy(buf, tmp, buflen);
return 0;
}
// clang-format off
/**
* MxImapOps - IMAP Mailbox - Implements ::MxOps
*/
struct MxOps MxImapOps = {
.type = MUTT_IMAP,
.name = "imap",
.is_local = false,
.ac_find = imap_ac_find,
.ac_add = imap_ac_add,
.mbox_open = imap_mbox_open,
.mbox_open_append = imap_mbox_open_append,
.mbox_check = imap_mbox_check,
.mbox_check_stats = imap_mbox_check_stats,
.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,
.msg_padding_size = NULL,
.msg_save_hcache = imap_msg_save_hcache,
.tags_edit = imap_tags_edit,
.tags_commit = imap_tags_commit,
.path_probe = imap_path_probe,
.path_canon = imap_path_canon,
.path_pretty = imap_path_pretty,
.path_parent = imap_path_parent,
};
// clang-format on
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_4069_3 |
crossvul-cpp_data_bad_1205_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
/* packet thinks it is in the wrong direction, flip it */
StreamTcpPacketSwitchDir(ssn, p);
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permited on SYN packet", ssn);
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if (ack_indicates_missed_3whs_ack_packet &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadGrow(ssn_pool,
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1205_0 |
crossvul-cpp_data_good_1906_2 | /*
* Copyright © 2014-2019 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <gio/gdesktopappinfo.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/vfs.h>
#include <sys/personality.h>
#include <grp.h>
#include <unistd.h>
#include <gio/gunixfdlist.h>
#ifdef HAVE_DCONF
#include <dconf/dconf.h>
#endif
#ifdef HAVE_LIBMALCONTENT
#include <libmalcontent/malcontent.h>
#endif
#ifdef ENABLE_SECCOMP
#include <seccomp.h>
#endif
#ifdef ENABLE_XAUTH
#include <X11/Xauth.h>
#endif
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include "libglnx/libglnx.h"
#include "flatpak-run-private.h"
#include "flatpak-proxy.h"
#include "flatpak-utils-base-private.h"
#include "flatpak-dir-private.h"
#include "flatpak-instance-private.h"
#include "flatpak-systemd-dbus-generated.h"
#include "flatpak-document-dbus-generated.h"
#include "flatpak-error.h"
#define DEFAULT_SHELL "/bin/sh"
const char * const abs_usrmerged_dirs[] =
{
"/bin",
"/lib",
"/lib32",
"/lib64",
"/sbin",
NULL
};
const char * const *flatpak_abs_usrmerged_dirs = abs_usrmerged_dirs;
static char *
extract_unix_path_from_dbus_address (const char *address)
{
const char *path, *path_end;
if (address == NULL)
return NULL;
if (!g_str_has_prefix (address, "unix:"))
return NULL;
path = strstr (address, "path=");
if (path == NULL)
return NULL;
path += strlen ("path=");
path_end = path;
while (*path_end != 0 && *path_end != ',')
path_end++;
return g_strndup (path, path_end - path);
}
#ifdef ENABLE_XAUTH
static gboolean
auth_streq (char *str,
char *au_str,
int au_len)
{
return au_len == strlen (str) && memcmp (str, au_str, au_len) == 0;
}
static gboolean
xauth_entry_should_propagate (Xauth *xa,
char *hostname,
char *number)
{
/* ensure entry isn't for remote access */
if (xa->family != FamilyLocal && xa->family != FamilyWild)
return FALSE;
/* ensure entry is for this machine */
if (xa->family == FamilyLocal && !auth_streq (hostname, xa->address, xa->address_length))
return FALSE;
/* ensure entry is for this session */
if (xa->number != NULL && !auth_streq (number, xa->number, xa->number_length))
return FALSE;
return TRUE;
}
static void
write_xauth (char *number, FILE *output)
{
Xauth *xa, local_xa;
char *filename;
FILE *f;
struct utsname unames;
if (uname (&unames))
{
g_warning ("uname failed");
return;
}
filename = XauFileName ();
f = fopen (filename, "rb");
if (f == NULL)
return;
while (TRUE)
{
xa = XauReadAuth (f);
if (xa == NULL)
break;
if (xauth_entry_should_propagate (xa, unames.nodename, number))
{
local_xa = *xa;
if (local_xa.number)
{
local_xa.number = "99";
local_xa.number_length = 2;
}
if (!XauWriteAuth (output, &local_xa))
g_warning ("xauth write error");
}
XauDisposeAuth (xa);
}
fclose (f);
}
#endif /* ENABLE_XAUTH */
static void
flatpak_run_add_x11_args (FlatpakBwrap *bwrap,
gboolean allowed)
{
g_autofree char *x11_socket = NULL;
const char *display;
/* Always cover /tmp/.X11-unix, that way we never see the host one in case
* we have access to the host /tmp. If you request X access we'll put the right
* thing in this anyway.
*/
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/tmp/.X11-unix",
NULL);
if (!allowed)
{
flatpak_bwrap_unset_env (bwrap, "DISPLAY");
return;
}
g_debug ("Allowing x11 access");
display = g_getenv ("DISPLAY");
if (display && display[0] == ':' && g_ascii_isdigit (display[1]))
{
const char *display_nr = &display[1];
const char *display_nr_end = display_nr;
g_autofree char *d = NULL;
while (g_ascii_isdigit (*display_nr_end))
display_nr_end++;
d = g_strndup (display_nr, display_nr_end - display_nr);
x11_socket = g_strdup_printf ("/tmp/.X11-unix/X%s", d);
flatpak_bwrap_add_args (bwrap,
"--ro-bind", x11_socket, "/tmp/.X11-unix/X99",
NULL);
flatpak_bwrap_set_env (bwrap, "DISPLAY", ":99.0", TRUE);
#ifdef ENABLE_XAUTH
g_auto(GLnxTmpfile) xauth_tmpf = { 0, };
if (glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, "/tmp", &xauth_tmpf, NULL))
{
FILE *output = fdopen (xauth_tmpf.fd, "wb");
if (output != NULL)
{
/* fd is now owned by output, steal it from the tmpfile */
int tmp_fd = dup (glnx_steal_fd (&xauth_tmpf.fd));
if (tmp_fd != -1)
{
g_autofree char *dest = g_strdup_printf ("/run/user/%d/Xauthority", getuid ());
write_xauth (d, output);
flatpak_bwrap_add_args_data_fd (bwrap, "--ro-bind-data", tmp_fd, dest);
flatpak_bwrap_set_env (bwrap, "XAUTHORITY", dest, TRUE);
}
fclose (output);
if (tmp_fd != -1)
lseek (tmp_fd, 0, SEEK_SET);
}
}
#endif
}
else
{
flatpak_bwrap_unset_env (bwrap, "DISPLAY");
}
}
static gboolean
flatpak_run_add_wayland_args (FlatpakBwrap *bwrap)
{
const char *wayland_display;
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *wayland_socket = NULL;
g_autofree char *sandbox_wayland_socket = NULL;
gboolean res = FALSE;
struct stat statbuf;
wayland_display = g_getenv ("WAYLAND_DISPLAY");
if (!wayland_display)
wayland_display = "wayland-0";
wayland_socket = g_build_filename (user_runtime_dir, wayland_display, NULL);
sandbox_wayland_socket = g_strdup_printf ("/run/user/%d/%s", getuid (), wayland_display);
if (stat (wayland_socket, &statbuf) == 0 &&
(statbuf.st_mode & S_IFMT) == S_IFSOCK)
{
res = TRUE;
flatpak_bwrap_add_args (bwrap,
"--ro-bind", wayland_socket, sandbox_wayland_socket,
NULL);
}
return res;
}
static void
flatpak_run_add_ssh_args (FlatpakBwrap *bwrap)
{
const char * auth_socket;
g_autofree char * sandbox_auth_socket = NULL;
auth_socket = g_getenv ("SSH_AUTH_SOCK");
if (!auth_socket)
return; /* ssh agent not present */
if (!g_file_test (auth_socket, G_FILE_TEST_EXISTS))
{
/* Let's clean it up, so that the application will not try to connect */
flatpak_bwrap_unset_env (bwrap, "SSH_AUTH_SOCK");
return;
}
sandbox_auth_socket = g_strdup_printf ("/run/user/%d/ssh-auth", getuid ());
flatpak_bwrap_add_args (bwrap,
"--ro-bind", auth_socket, sandbox_auth_socket,
NULL);
flatpak_bwrap_set_env (bwrap, "SSH_AUTH_SOCK", sandbox_auth_socket, TRUE);
}
static void
flatpak_run_add_pcsc_args (FlatpakBwrap *bwrap)
{
const char * pcsc_socket;
const char * sandbox_pcsc_socket = "/run/pcscd/pcscd.comm";
pcsc_socket = g_getenv ("PCSCLITE_CSOCK_NAME");
if (pcsc_socket)
{
if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_unset_env (bwrap, "PCSCLITE_CSOCK_NAME");
return;
}
}
else
{
pcsc_socket = "/run/pcscd/pcscd.comm";
if (!g_file_test (pcsc_socket, G_FILE_TEST_EXISTS))
return;
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", pcsc_socket, sandbox_pcsc_socket,
NULL);
flatpak_bwrap_set_env (bwrap, "PCSCLITE_CSOCK_NAME", sandbox_pcsc_socket, TRUE);
}
static gboolean
flatpak_run_cups_check_server_is_socket (const char *server)
{
if (g_str_has_prefix (server, "/") && strstr (server, ":") == NULL)
return TRUE;
return FALSE;
}
/* Try to find a default server from a cups confguration file */
static char *
flatpak_run_get_cups_server_name_config (const char *path)
{
g_autoptr(GFile) file = g_file_new_for_path (path);
g_autoptr(GError) my_error = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
size_t len;
input_stream = g_file_read (file, NULL, &my_error);
if (my_error)
{
g_debug ("CUPS configuration file '%s': %s", path, my_error->message);
return NULL;
}
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);
if (line == NULL)
break;
g_strchug (line);
if ((*line == '\0') || (*line == '#'))
continue;
g_auto(GStrv) tokens = g_strsplit (line, " ", 2);
if ((tokens[0] != NULL) && (tokens[1] != NULL))
{
if (strcmp ("ServerName", tokens[0]) == 0)
{
g_strchug (tokens[1]);
if (flatpak_run_cups_check_server_is_socket (tokens[1]))
return g_strdup (tokens[1]);
}
}
}
return NULL;
}
static char *
flatpak_run_get_cups_server_name (void)
{
g_autofree char * cups_server = NULL;
g_autofree char * cups_config_path = NULL;
/* TODO
* we don't currently support cups servers located on the network, if such
* server is detected, we simply ignore it and in the worst case we fallback
* to the default socket
*/
cups_server = g_strdup (g_getenv ("CUPS_SERVER"));
if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))
return g_steal_pointer (&cups_server);
g_clear_pointer (&cups_server, g_free);
cups_config_path = g_build_filename (g_get_home_dir (), ".cups/client.conf", NULL);
cups_server = flatpak_run_get_cups_server_name_config (cups_config_path);
if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))
return g_steal_pointer (&cups_server);
g_clear_pointer (&cups_server, g_free);
cups_server = flatpak_run_get_cups_server_name_config ("/etc/cups/client.conf");
if (cups_server && flatpak_run_cups_check_server_is_socket (cups_server))
return g_steal_pointer (&cups_server);
// Fallback to default socket
return g_strdup ("/var/run/cups/cups.sock");
}
static void
flatpak_run_add_cups_args (FlatpakBwrap *bwrap)
{
g_autofree char * sandbox_server_name = g_strdup ("/var/run/cups/cups.sock");
g_autofree char * cups_server_name = flatpak_run_get_cups_server_name ();
if (!g_file_test (cups_server_name, G_FILE_TEST_EXISTS))
{
g_debug ("Could not find CUPS server");
return;
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", cups_server_name, sandbox_server_name,
NULL);
}
/* Try to find a default server from a pulseaudio confguration file */
static char *
flatpak_run_get_pulseaudio_server_user_config (const char *path)
{
g_autoptr(GFile) file = g_file_new_for_path (path);
g_autoptr(GError) my_error = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
size_t len;
input_stream = g_file_read (file, NULL, &my_error);
if (my_error)
{
g_debug ("Pulseaudio user configuration file '%s': %s", path, my_error->message);
return NULL;
}
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line (data_stream, &len, NULL, NULL);
if (line == NULL)
break;
g_strchug (line);
if ((*line == '\0') || (*line == ';') || (*line == '#'))
continue;
if (g_str_has_prefix (line, ".include "))
{
g_autofree char *rec_path = g_strdup (line + 9);
g_strstrip (rec_path);
char *found = flatpak_run_get_pulseaudio_server_user_config (rec_path);
if (found)
return found;
}
else if (g_str_has_prefix (line, "["))
{
return NULL;
}
else
{
g_auto(GStrv) tokens = g_strsplit (line, "=", 2);
if ((tokens[0] != NULL) && (tokens[1] != NULL))
{
g_strchomp (tokens[0]);
if (strcmp ("default-server", tokens[0]) == 0)
{
g_strstrip (tokens[1]);
g_debug ("Found pulseaudio socket from configuration file '%s': %s", path, tokens[1]);
return g_strdup (tokens[1]);
}
}
}
}
return NULL;
}
static char *
flatpak_run_get_pulseaudio_server (void)
{
const char * pulse_clientconfig;
char *pulse_server;
g_autofree char *pulse_user_config = NULL;
pulse_server = g_strdup (g_getenv ("PULSE_SERVER"));
if (pulse_server)
return pulse_server;
pulse_clientconfig = g_getenv ("PULSE_CLIENTCONFIG");
if (pulse_clientconfig)
return flatpak_run_get_pulseaudio_server_user_config (pulse_clientconfig);
pulse_user_config = g_build_filename (g_get_user_config_dir (), "pulse/client.conf", NULL);
pulse_server = flatpak_run_get_pulseaudio_server_user_config (pulse_user_config);
if (pulse_server)
return pulse_server;
pulse_server = flatpak_run_get_pulseaudio_server_user_config ("/etc/pulse/client.conf");
if (pulse_server)
return pulse_server;
return NULL;
}
static char *
flatpak_run_parse_pulse_server (const char *value)
{
g_auto(GStrv) servers = g_strsplit (value, " ", 0);
gsize i;
for (i = 0; servers[i] != NULL; i++)
{
const char *server = servers[i];
if (g_str_has_prefix (server, "{"))
{
const char * closing = strstr (server, "}");
if (closing == NULL)
continue;
server = closing + 1;
}
if (g_str_has_prefix (server, "unix:"))
return g_strdup (server + 5);
}
return NULL;
}
/*
* Get the machine ID as used by PulseAudio. This is the systemd/D-Bus
* machine ID, or failing that, the hostname.
*/
static char *
flatpak_run_get_pulse_machine_id (void)
{
static const char * const machine_ids[] =
{
"/etc/machine-id",
"/var/lib/dbus/machine-id",
};
gsize i;
for (i = 0; i < G_N_ELEMENTS (machine_ids); i++)
{
g_autofree char *ret = NULL;
if (g_file_get_contents (machine_ids[i], &ret, NULL, NULL))
{
gsize j;
g_strstrip (ret);
for (j = 0; ret[j] != '\0'; j++)
{
if (!g_ascii_isxdigit (ret[j]))
break;
}
if (ret[0] != '\0' && ret[j] == '\0')
return g_steal_pointer (&ret);
}
}
return g_strdup (g_get_host_name ());
}
/*
* Get the directory used by PulseAudio for its configuration.
*/
static char *
flatpak_run_get_pulse_home (void)
{
/* Legacy path ~/.pulse is tried first, for compatibility */
{
const char *parent = g_get_home_dir ();
g_autofree char *ret = g_build_filename (parent, ".pulse", NULL);
if (g_file_test (ret, G_FILE_TEST_IS_DIR))
return g_steal_pointer (&ret);
}
/* The more modern path, usually ~/.config/pulse */
{
const char *parent = g_get_user_config_dir ();
/* Usually ~/.config/pulse */
g_autofree char *ret = g_build_filename (parent, "pulse", NULL);
if (g_file_test (ret, G_FILE_TEST_IS_DIR))
return g_steal_pointer (&ret);
}
return NULL;
}
/*
* Get the runtime directory used by PulseAudio for its socket.
*/
static char *
flatpak_run_get_pulse_runtime_dir (void)
{
const char *val = NULL;
val = g_getenv ("PULSE_RUNTIME_PATH");
if (val != NULL)
return realpath (val, NULL);
{
const char *user_runtime_dir = g_get_user_runtime_dir ();
if (user_runtime_dir != NULL)
{
g_autofree char *dir = g_build_filename (user_runtime_dir, "pulse", NULL);
if (g_file_test (dir, G_FILE_TEST_IS_DIR))
return realpath (dir, NULL);
}
}
{
g_autofree char *pulse_home = flatpak_run_get_pulse_home ();
g_autofree char *machine_id = flatpak_run_get_pulse_machine_id ();
if (pulse_home != NULL && machine_id != NULL)
{
/* This is usually a symlink, but we take its realpath() anyway */
g_autofree char *dir = g_strdup_printf ("%s/%s-runtime", pulse_home, machine_id);
if (g_file_test (dir, G_FILE_TEST_IS_DIR))
return realpath (dir, NULL);
}
}
return NULL;
}
static void
flatpak_run_add_pulseaudio_args (FlatpakBwrap *bwrap)
{
g_autofree char *pulseaudio_server = flatpak_run_get_pulseaudio_server ();
g_autofree char *pulseaudio_socket = NULL;
g_autofree char *pulse_runtime_dir = flatpak_run_get_pulse_runtime_dir ();
if (pulseaudio_server)
pulseaudio_socket = flatpak_run_parse_pulse_server (pulseaudio_server);
if (!pulseaudio_socket)
{
pulseaudio_socket = g_build_filename (pulse_runtime_dir, "native", NULL);
if (!g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))
g_clear_pointer (&pulseaudio_socket, g_free);
}
if (!pulseaudio_socket)
{
pulseaudio_socket = realpath ("/var/run/pulse/native", NULL);
if (pulseaudio_socket && !g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))
g_clear_pointer (&pulseaudio_socket, g_free);
}
flatpak_bwrap_unset_env (bwrap, "PULSE_SERVER");
if (pulseaudio_socket && g_file_test (pulseaudio_socket, G_FILE_TEST_EXISTS))
{
gboolean share_shm = FALSE; /* TODO: When do we add this? */
g_autofree char *client_config = g_strdup_printf ("enable-shm=%s\n", share_shm ? "yes" : "no");
g_autofree char *sandbox_socket_path = g_strdup_printf ("/run/user/%d/pulse/native", getuid ());
g_autofree char *pulse_server = g_strdup_printf ("unix:/run/user/%d/pulse/native", getuid ());
g_autofree char *config_path = g_strdup_printf ("/run/user/%d/pulse/config", getuid ());
/* FIXME - error handling */
if (!flatpak_bwrap_add_args_data (bwrap, "pulseaudio", client_config, -1, config_path, NULL))
return;
flatpak_bwrap_add_args (bwrap,
"--ro-bind", pulseaudio_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (bwrap, "PULSE_SERVER", pulse_server, TRUE);
flatpak_bwrap_set_env (bwrap, "PULSE_CLIENTCONFIG", config_path, TRUE);
}
else
g_debug ("Could not find pulseaudio socket");
/* Also allow ALSA access. This was added in 1.8, and is not ideally named. However,
* since the practical permission of ALSA and PulseAudio are essentially the same, and
* since we don't want to add more permissions for something we plan to replace with
* portals/pipewire going forward we reinterpret pulseaudio to also mean ALSA.
*/
if (g_file_test ("/dev/snd", G_FILE_TEST_IS_DIR))
flatpak_bwrap_add_args (bwrap, "--dev-bind", "/dev/snd", "/dev/snd", NULL);
}
static void
flatpak_run_add_resolved_args (FlatpakBwrap *bwrap)
{
const char *resolved_socket = "/run/systemd/resolve/io.systemd.Resolve";
if (g_file_test (resolved_socket, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--bind", resolved_socket, resolved_socket, NULL);
}
static void
flatpak_run_add_journal_args (FlatpakBwrap *bwrap)
{
g_autofree char *journal_socket_socket = g_strdup ("/run/systemd/journal/socket");
g_autofree char *journal_stdout_socket = g_strdup ("/run/systemd/journal/stdout");
if (g_file_test (journal_socket_socket, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", journal_socket_socket, journal_socket_socket,
NULL);
}
if (g_file_test (journal_stdout_socket, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", journal_stdout_socket, journal_stdout_socket,
NULL);
}
}
static char *
create_proxy_socket (char *template)
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, ".dbus-proxy", NULL);
g_autofree char *proxy_socket = g_build_filename (proxy_socket_dir, template, NULL);
int fd;
if (!glnx_shutil_mkdir_p_at (AT_FDCWD, proxy_socket_dir, 0755, NULL, NULL))
return NULL;
fd = g_mkstemp (proxy_socket);
if (fd == -1)
return NULL;
close (fd);
return g_steal_pointer (&proxy_socket);
}
static gboolean
flatpak_run_add_system_dbus_args (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
FlatpakContext *context,
FlatpakRunFlags flags)
{
gboolean unrestricted, no_proxy;
const char *dbus_address = g_getenv ("DBUS_SYSTEM_BUS_ADDRESS");
g_autofree char *real_dbus_address = NULL;
g_autofree char *dbus_system_socket = NULL;
unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) != 0;
if (unrestricted)
g_debug ("Allowing system-dbus access");
no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY) != 0;
if (dbus_address != NULL)
dbus_system_socket = extract_unix_path_from_dbus_address (dbus_address);
else if (g_file_test ("/var/run/dbus/system_bus_socket", G_FILE_TEST_EXISTS))
dbus_system_socket = g_strdup ("/var/run/dbus/system_bus_socket");
if (dbus_system_socket != NULL && unrestricted)
{
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", dbus_system_socket, "/run/dbus/system_bus_socket",
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SYSTEM_BUS_ADDRESS", "unix:path=/run/dbus/system_bus_socket", TRUE);
return TRUE;
}
else if (!no_proxy && flatpak_context_get_needs_system_bus_proxy (context))
{
g_autofree char *proxy_socket = create_proxy_socket ("system-bus-proxy-XXXXXX");
if (proxy_socket == NULL)
return FALSE;
if (dbus_address)
real_dbus_address = g_strdup (dbus_address);
else
real_dbus_address = g_strdup_printf ("unix:path=%s", dbus_system_socket);
flatpak_bwrap_add_args (proxy_arg_bwrap, real_dbus_address, proxy_socket, NULL);
if (!unrestricted)
flatpak_context_add_bus_filters (context, NULL, FALSE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);
if ((flags & FLATPAK_RUN_FLAG_LOG_SYSTEM_BUS) != 0)
flatpak_bwrap_add_args (proxy_arg_bwrap, "--log", NULL);
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", proxy_socket, "/run/dbus/system_bus_socket",
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SYSTEM_BUS_ADDRESS", "unix:path=/run/dbus/system_bus_socket", TRUE);
return TRUE;
}
return FALSE;
}
static gboolean
flatpak_run_add_session_dbus_args (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
FlatpakContext *context,
FlatpakRunFlags flags,
const char *app_id)
{
gboolean unrestricted, no_proxy;
const char *dbus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
g_autofree char *dbus_session_socket = NULL;
g_autofree char *sandbox_socket_path = g_strdup_printf ("/run/user/%d/bus", getuid ());
g_autofree char *sandbox_dbus_address = g_strdup_printf ("unix:path=/run/user/%d/bus", getuid ());
unrestricted = (context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) != 0;
if (dbus_address != NULL)
{
dbus_session_socket = extract_unix_path_from_dbus_address (dbus_address);
}
else
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
struct stat statbuf;
dbus_session_socket = g_build_filename (user_runtime_dir, "bus", NULL);
if (stat (dbus_session_socket, &statbuf) < 0
|| (statbuf.st_mode & S_IFMT) != S_IFSOCK
|| statbuf.st_uid != getuid ())
return FALSE;
}
if (unrestricted)
g_debug ("Allowing session-dbus access");
no_proxy = (flags & FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY) != 0;
if (dbus_session_socket != NULL && unrestricted)
{
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", dbus_session_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SESSION_BUS_ADDRESS", sandbox_dbus_address, TRUE);
return TRUE;
}
else if (!no_proxy && dbus_address != NULL)
{
g_autofree char *proxy_socket = create_proxy_socket ("session-bus-proxy-XXXXXX");
if (proxy_socket == NULL)
return FALSE;
flatpak_bwrap_add_args (proxy_arg_bwrap, dbus_address, proxy_socket, NULL);
if (!unrestricted)
{
flatpak_context_add_bus_filters (context, app_id, TRUE, flags & FLATPAK_RUN_FLAG_SANDBOX, proxy_arg_bwrap);
/* Allow calling any interface+method on all portals, but only receive broadcasts under /org/desktop/portal */
flatpak_bwrap_add_arg (proxy_arg_bwrap,
"--call=org.freedesktop.portal.*=*");
flatpak_bwrap_add_arg (proxy_arg_bwrap,
"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*");
}
if ((flags & FLATPAK_RUN_FLAG_LOG_SESSION_BUS) != 0)
flatpak_bwrap_add_args (proxy_arg_bwrap, "--log", NULL);
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", proxy_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (app_bwrap, "DBUS_SESSION_BUS_ADDRESS", sandbox_dbus_address, TRUE);
return TRUE;
}
return FALSE;
}
static gboolean
flatpak_run_add_a11y_dbus_args (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
FlatpakContext *context,
FlatpakRunFlags flags)
{
g_autoptr(GDBusConnection) session_bus = NULL;
g_autofree char *a11y_address = NULL;
g_autoptr(GError) local_error = NULL;
g_autoptr(GDBusMessage) reply = NULL;
g_autoptr(GDBusMessage) msg = NULL;
g_autofree char *proxy_socket = NULL;
if ((flags & FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY) != 0)
return FALSE;
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
if (session_bus == NULL)
return FALSE;
msg = g_dbus_message_new_method_call ("org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus", "GetAddress");
g_dbus_message_set_body (msg, g_variant_new ("()"));
reply =
g_dbus_connection_send_message_with_reply_sync (session_bus, msg,
G_DBUS_SEND_MESSAGE_FLAGS_NONE,
30000,
NULL,
NULL,
NULL);
if (reply)
{
if (g_dbus_message_to_gerror (reply, &local_error))
{
if (!g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))
g_message ("Can't find a11y bus: %s", local_error->message);
}
else
{
g_variant_get (g_dbus_message_get_body (reply),
"(s)", &a11y_address);
}
}
if (!a11y_address)
return FALSE;
proxy_socket = create_proxy_socket ("a11y-bus-proxy-XXXXXX");
if (proxy_socket == NULL)
return FALSE;
g_autofree char *sandbox_socket_path = g_strdup_printf ("/run/user/%d/at-spi-bus", getuid ());
g_autofree char *sandbox_dbus_address = g_strdup_printf ("unix:path=/run/user/%d/at-spi-bus", getuid ());
flatpak_bwrap_add_args (proxy_arg_bwrap,
a11y_address,
proxy_socket, "--filter", "--sloppy-names",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Embed@/org/a11y/atspi/accessible/root",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.Socket.Unembed@/org/a11y/atspi/accessible/root",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.Registry.GetRegisteredEvents@/org/a11y/atspi/registry",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetKeystrokeListeners@/org/a11y/atspi/registry/deviceeventcontroller",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.GetDeviceEventListeners@/org/a11y/atspi/registry/deviceeventcontroller",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersSync@/org/a11y/atspi/registry/deviceeventcontroller",
"--call=org.a11y.atspi.Registry=org.a11y.atspi.DeviceEventController.NotifyListenersAsync@/org/a11y/atspi/registry/deviceeventcontroller",
NULL);
if ((flags & FLATPAK_RUN_FLAG_LOG_A11Y_BUS) != 0)
flatpak_bwrap_add_args (proxy_arg_bwrap, "--log", NULL);
flatpak_bwrap_add_args (app_bwrap,
"--ro-bind", proxy_socket, sandbox_socket_path,
NULL);
flatpak_bwrap_set_env (app_bwrap, "AT_SPI_BUS_ADDRESS", sandbox_dbus_address, TRUE);
return TRUE;
}
/* This wraps the argv in a bwrap call, primary to allow the
command to be run with a proper /.flatpak-info with data
taken from app_info_path */
static gboolean
add_bwrap_wrapper (FlatpakBwrap *bwrap,
const char *app_info_path,
GError **error)
{
glnx_autofd int app_info_fd = -1;
g_auto(GLnxDirFdIterator) dir_iter = { 0 };
struct dirent *dent;
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *proxy_socket_dir = g_build_filename (user_runtime_dir, ".dbus-proxy/", NULL);
app_info_fd = open (app_info_path, O_RDONLY | O_CLOEXEC);
if (app_info_fd == -1)
return glnx_throw_errno_prefix (error, _("Failed to open app info file"));
if (!glnx_dirfd_iterator_init_at (AT_FDCWD, "/", FALSE, &dir_iter, error))
return FALSE;
flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());
while (TRUE)
{
glnx_autofd int o_path_fd = -1;
struct statfs stfs;
if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dir_iter, &dent, NULL, error))
return FALSE;
if (dent == NULL)
break;
if (strcmp (dent->d_name, ".flatpak-info") == 0)
continue;
/* O_PATH + fstatfs is the magic that we need to statfs without automounting the target */
o_path_fd = openat (dir_iter.fd, dent->d_name, O_PATH | O_NOFOLLOW | O_CLOEXEC);
if (o_path_fd == -1 || fstatfs (o_path_fd, &stfs) != 0 || stfs.f_type == AUTOFS_SUPER_MAGIC)
continue; /* AUTOFS mounts are risky and can cause us to block (see issue #1633), so ignore it. Its unlikely the proxy needs such a directory. */
if (dent->d_type == DT_DIR)
{
if (strcmp (dent->d_name, "tmp") == 0 ||
strcmp (dent->d_name, "var") == 0 ||
strcmp (dent->d_name, "run") == 0)
flatpak_bwrap_add_arg (bwrap, "--bind");
else
flatpak_bwrap_add_arg (bwrap, "--ro-bind");
flatpak_bwrap_add_arg_printf (bwrap, "/%s", dent->d_name);
flatpak_bwrap_add_arg_printf (bwrap, "/%s", dent->d_name);
}
else if (dent->d_type == DT_LNK)
{
g_autofree gchar *target = NULL;
target = glnx_readlinkat_malloc (dir_iter.fd, dent->d_name,
NULL, error);
if (target == NULL)
return FALSE;
flatpak_bwrap_add_args (bwrap, "--symlink", target, NULL);
flatpak_bwrap_add_arg_printf (bwrap, "/%s", dent->d_name);
}
}
flatpak_bwrap_add_args (bwrap, "--bind", proxy_socket_dir, proxy_socket_dir, NULL);
/* This is a file rather than a bind mount, because it will then
not be unmounted from the namespace when the namespace dies. */
flatpak_bwrap_add_args_data_fd (bwrap, "--file", glnx_steal_fd (&app_info_fd), "/.flatpak-info");
if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))
return FALSE;
return TRUE;
}
static gboolean
start_dbus_proxy (FlatpakBwrap *app_bwrap,
FlatpakBwrap *proxy_arg_bwrap,
const char *app_info_path,
GError **error)
{
char x = 'x';
const char *proxy;
g_autofree char *commandline = NULL;
g_autoptr(FlatpakBwrap) proxy_bwrap = NULL;
int sync_fds[2] = {-1, -1};
int proxy_start_index;
g_auto(GStrv) minimal_envp = NULL;
minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);
proxy_bwrap = flatpak_bwrap_new (NULL);
if (!add_bwrap_wrapper (proxy_bwrap, app_info_path, error))
return FALSE;
proxy = g_getenv ("FLATPAK_DBUSPROXY");
if (proxy == NULL)
proxy = DBUSPROXY;
flatpak_bwrap_add_arg (proxy_bwrap, proxy);
proxy_start_index = proxy_bwrap->argv->len;
if (pipe2 (sync_fds, O_CLOEXEC) < 0)
{
g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),
_("Unable to create sync pipe"));
return FALSE;
}
/* read end goes to app */
flatpak_bwrap_add_args_data_fd (app_bwrap, "--sync-fd", sync_fds[0], NULL);
/* write end goes to proxy */
flatpak_bwrap_add_fd (proxy_bwrap, sync_fds[1]);
flatpak_bwrap_add_arg_printf (proxy_bwrap, "--fd=%d", sync_fds[1]);
/* Note: This steals the fds from proxy_arg_bwrap */
flatpak_bwrap_append_bwrap (proxy_bwrap, proxy_arg_bwrap);
if (!flatpak_bwrap_bundle_args (proxy_bwrap, proxy_start_index, -1, TRUE, error))
return FALSE;
flatpak_bwrap_finish (proxy_bwrap);
commandline = flatpak_quote_argv ((const char **) proxy_bwrap->argv->pdata, -1);
g_debug ("Running '%s'", commandline);
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_async (NULL,
(char **) proxy_bwrap->argv->pdata,
NULL,
G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
flatpak_bwrap_child_setup_cb, proxy_bwrap->fds,
NULL, error))
return FALSE;
/* The write end can be closed now, otherwise the read below will hang of xdg-dbus-proxy
fails to start. */
g_clear_pointer (&proxy_bwrap, flatpak_bwrap_free);
/* Sync with proxy, i.e. wait until its listening on the sockets */
if (read (sync_fds[0], &x, 1) != 1)
{
g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),
_("Failed to sync with dbus proxy"));
return FALSE;
}
return TRUE;
}
static int
flatpak_extension_compare_by_path (gconstpointer _a,
gconstpointer _b)
{
const FlatpakExtension *a = _a;
const FlatpakExtension *b = _b;
return g_strcmp0 (a->directory, b->directory);
}
gboolean
flatpak_run_add_extension_args (FlatpakBwrap *bwrap,
GKeyFile *metakey,
FlatpakDecomposed *ref,
gboolean use_ld_so_cache,
char **extensions_out,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GString) used_extensions = g_string_new ("");
GList *extensions, *path_sorted_extensions, *l;
g_autoptr(GString) ld_library_path = g_string_new ("");
int count = 0;
g_autoptr(GHashTable) mounted_tmpfs =
g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
g_autoptr(GHashTable) created_symlink =
g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
g_autofree char *arch = flatpak_decomposed_dup_arch (ref);
const char *branch = flatpak_decomposed_get_branch (ref);
gboolean is_app = flatpak_decomposed_is_app (ref);
extensions = flatpak_list_extensions (metakey, arch, branch);
/* First we apply all the bindings, they are sorted alphabetically in order for parent directory
to be mounted before child directories */
path_sorted_extensions = g_list_copy (extensions);
path_sorted_extensions = g_list_sort (path_sorted_extensions, flatpak_extension_compare_by_path);
for (l = path_sorted_extensions; l != NULL; l = l->next)
{
FlatpakExtension *ext = l->data;
g_autofree char *directory = g_build_filename (is_app ? "/app" : "/usr", ext->directory, NULL);
g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);
g_autofree char *ref_file = g_build_filename (full_directory, ".ref", NULL);
g_autofree char *real_ref = g_build_filename (ext->files_path, ext->directory, ".ref", NULL);
if (ext->needs_tmpfs)
{
g_autofree char *parent = g_path_get_dirname (directory);
if (g_hash_table_lookup (mounted_tmpfs, parent) == NULL)
{
flatpak_bwrap_add_args (bwrap,
"--tmpfs", parent,
NULL);
g_hash_table_insert (mounted_tmpfs, g_steal_pointer (&parent), "mounted");
}
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", ext->files_path, full_directory,
NULL);
if (g_file_test (real_ref, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--lock-file", ref_file,
NULL);
}
g_list_free (path_sorted_extensions);
/* Then apply library directories and file merging, in extension prio order */
for (l = extensions; l != NULL; l = l->next)
{
FlatpakExtension *ext = l->data;
g_autofree char *directory = g_build_filename (is_app ? "/app" : "/usr", ext->directory, NULL);
g_autofree char *full_directory = g_build_filename (directory, ext->subdir_suffix, NULL);
int i;
if (used_extensions->len > 0)
g_string_append (used_extensions, ";");
g_string_append (used_extensions, ext->installed_id);
g_string_append (used_extensions, "=");
if (ext->commit != NULL)
g_string_append (used_extensions, ext->commit);
else
g_string_append (used_extensions, "local");
if (ext->add_ld_path)
{
g_autofree char *ld_path = g_build_filename (full_directory, ext->add_ld_path, NULL);
if (use_ld_so_cache)
{
g_autofree char *contents = g_strconcat (ld_path, "\n", NULL);
/* We prepend app or runtime and a counter in order to get the include order correct for the conf files */
g_autofree char *ld_so_conf_file = g_strdup_printf ("%s-%03d-%s.conf", flatpak_decomposed_get_kind_str (ref), ++count, ext->installed_id);
g_autofree char *ld_so_conf_file_path = g_build_filename ("/run/flatpak/ld.so.conf.d", ld_so_conf_file, NULL);
if (!flatpak_bwrap_add_args_data (bwrap, "ld-so-conf",
contents, -1, ld_so_conf_file_path, error))
return FALSE;
}
else
{
if (ld_library_path->len != 0)
g_string_append (ld_library_path, ":");
g_string_append (ld_library_path, ld_path);
}
}
for (i = 0; ext->merge_dirs != NULL && ext->merge_dirs[i] != NULL; i++)
{
g_autofree char *parent = g_path_get_dirname (directory);
g_autofree char *merge_dir = g_build_filename (parent, ext->merge_dirs[i], NULL);
g_autofree char *source_dir = g_build_filename (ext->files_path, ext->merge_dirs[i], NULL);
g_auto(GLnxDirFdIterator) source_iter = { 0 };
struct dirent *dent;
if (glnx_dirfd_iterator_init_at (AT_FDCWD, source_dir, TRUE, &source_iter, NULL))
{
while (glnx_dirfd_iterator_next_dent (&source_iter, &dent, NULL, NULL) && dent != NULL)
{
g_autofree char *symlink_path = g_build_filename (merge_dir, dent->d_name, NULL);
/* Only create the first, because extensions are listed in prio order */
if (g_hash_table_lookup (created_symlink, symlink_path) == NULL)
{
g_autofree char *symlink = g_build_filename (directory, ext->merge_dirs[i], dent->d_name, NULL);
flatpak_bwrap_add_args (bwrap,
"--symlink", symlink, symlink_path,
NULL);
g_hash_table_insert (created_symlink, g_steal_pointer (&symlink_path), "created");
}
}
}
}
}
g_list_free_full (extensions, (GDestroyNotify) flatpak_extension_free);
if (ld_library_path->len != 0)
{
const gchar *old_ld_path = g_environ_getenv (bwrap->envp, "LD_LIBRARY_PATH");
if (old_ld_path != NULL && *old_ld_path != 0)
{
if (is_app)
{
g_string_append (ld_library_path, ":");
g_string_append (ld_library_path, old_ld_path);
}
else
{
g_string_prepend (ld_library_path, ":");
g_string_prepend (ld_library_path, old_ld_path);
}
}
flatpak_bwrap_set_env (bwrap, "LD_LIBRARY_PATH", ld_library_path->str, TRUE);
}
if (extensions_out)
*extensions_out = g_string_free (g_steal_pointer (&used_extensions), FALSE);
return TRUE;
}
gboolean
flatpak_run_add_environment_args (FlatpakBwrap *bwrap,
const char *app_info_path,
FlatpakRunFlags flags,
const char *app_id,
FlatpakContext *context,
GFile *app_id_dir,
GPtrArray *previous_app_id_dirs,
FlatpakExports **exports_out,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GError) my_error = NULL;
g_autoptr(FlatpakExports) exports = NULL;
g_autoptr(FlatpakBwrap) proxy_arg_bwrap = flatpak_bwrap_new (flatpak_bwrap_empty_env);
gboolean has_wayland = FALSE;
gboolean allow_x11 = FALSE;
if ((context->shares & FLATPAK_CONTEXT_SHARED_IPC) == 0)
{
g_debug ("Disallowing ipc access");
flatpak_bwrap_add_args (bwrap, "--unshare-ipc", NULL);
}
if ((context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) == 0)
{
g_debug ("Disallowing network access");
flatpak_bwrap_add_args (bwrap, "--unshare-net", NULL);
}
if (context->devices & FLATPAK_CONTEXT_DEVICE_ALL)
{
flatpak_bwrap_add_args (bwrap,
"--dev-bind", "/dev", "/dev",
NULL);
/* Don't expose the host /dev/shm, just the device nodes, unless explicitly allowed */
if (g_file_test ("/dev/shm", G_FILE_TEST_IS_DIR))
{
if ((context->devices & FLATPAK_CONTEXT_DEVICE_SHM) == 0)
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/dev/shm",
NULL);
}
else if (g_file_test ("/dev/shm", G_FILE_TEST_IS_SYMLINK))
{
g_autofree char *link = flatpak_readlink ("/dev/shm", NULL);
/* On debian (with sysv init) the host /dev/shm is a symlink to /run/shm, so we can't
mount on top of it. */
if (g_strcmp0 (link, "/run/shm") == 0)
{
if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM &&
g_file_test ("/run/shm", G_FILE_TEST_IS_DIR))
flatpak_bwrap_add_args (bwrap,
"--bind", "/run/shm", "/run/shm",
NULL);
else
flatpak_bwrap_add_args (bwrap,
"--dir", "/run/shm",
NULL);
}
else
g_warning ("Unexpected /dev/shm symlink %s", link);
}
}
else
{
flatpak_bwrap_add_args (bwrap,
"--dev", "/dev",
NULL);
if (context->devices & FLATPAK_CONTEXT_DEVICE_DRI)
{
g_debug ("Allowing dri access");
int i;
char *dri_devices[] = {
"/dev/dri",
/* mali */
"/dev/mali",
"/dev/mali0",
"/dev/umplock",
/* nvidia */
"/dev/nvidiactl",
"/dev/nvidia-modeset",
/* nvidia OpenCL/CUDA */
"/dev/nvidia-uvm",
"/dev/nvidia-uvm-tools",
};
for (i = 0; i < G_N_ELEMENTS (dri_devices); i++)
{
if (g_file_test (dri_devices[i], G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--dev-bind", dri_devices[i], dri_devices[i], NULL);
}
/* Each Nvidia card gets its own device.
This is a fairly arbitrary limit but ASUS sells mining boards supporting 20 in theory. */
char nvidia_dev[14]; /* /dev/nvidia plus up to 2 digits */
for (i = 0; i < 20; i++)
{
g_snprintf (nvidia_dev, sizeof (nvidia_dev), "/dev/nvidia%d", i);
if (g_file_test (nvidia_dev, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--dev-bind", nvidia_dev, nvidia_dev, NULL);
}
}
if (context->devices & FLATPAK_CONTEXT_DEVICE_KVM)
{
g_debug ("Allowing kvm access");
if (g_file_test ("/dev/kvm", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--dev-bind", "/dev/kvm", "/dev/kvm", NULL);
}
if (context->devices & FLATPAK_CONTEXT_DEVICE_SHM)
{
/* This is a symlink to /run/shm on debian, so bind to real target */
g_autofree char *real_dev_shm = realpath ("/dev/shm", NULL);
g_debug ("Allowing /dev/shm access (as %s)", real_dev_shm);
if (real_dev_shm != NULL)
flatpak_bwrap_add_args (bwrap, "--bind", real_dev_shm, "/dev/shm", NULL);
}
}
flatpak_context_append_bwrap_filesystem (context, bwrap, app_id, app_id_dir, previous_app_id_dirs, &exports);
if (context->sockets & FLATPAK_CONTEXT_SOCKET_WAYLAND)
{
g_debug ("Allowing wayland access");
has_wayland = flatpak_run_add_wayland_args (bwrap);
}
if ((context->sockets & FLATPAK_CONTEXT_SOCKET_FALLBACK_X11) != 0)
allow_x11 = !has_wayland;
else
allow_x11 = (context->sockets & FLATPAK_CONTEXT_SOCKET_X11) != 0;
flatpak_run_add_x11_args (bwrap, allow_x11);
if (context->sockets & FLATPAK_CONTEXT_SOCKET_SSH_AUTH)
{
flatpak_run_add_ssh_args (bwrap);
}
if (context->sockets & FLATPAK_CONTEXT_SOCKET_PULSEAUDIO)
{
g_debug ("Allowing pulseaudio access");
flatpak_run_add_pulseaudio_args (bwrap);
}
if (context->sockets & FLATPAK_CONTEXT_SOCKET_PCSC)
{
flatpak_run_add_pcsc_args (bwrap);
}
if (context->sockets & FLATPAK_CONTEXT_SOCKET_CUPS)
{
flatpak_run_add_cups_args (bwrap);
}
flatpak_run_add_session_dbus_args (bwrap, proxy_arg_bwrap, context, flags, app_id);
flatpak_run_add_system_dbus_args (bwrap, proxy_arg_bwrap, context, flags);
flatpak_run_add_a11y_dbus_args (bwrap, proxy_arg_bwrap, context, flags);
/* Must run this before spawning the dbus proxy, to ensure it
ends up in the app cgroup */
if (!flatpak_run_in_transient_unit (app_id, &my_error))
{
/* We still run along even if we don't get a cgroup, as nothing
really depends on it. Its just nice to have */
g_debug ("Failed to run in transient scope: %s", my_error->message);
g_clear_error (&my_error);
}
if (!flatpak_bwrap_is_empty (proxy_arg_bwrap) &&
!start_dbus_proxy (bwrap, proxy_arg_bwrap, app_info_path, error))
return FALSE;
if (exports_out)
*exports_out = g_steal_pointer (&exports);
return TRUE;
}
typedef struct
{
const char *env;
const char *val;
} ExportData;
static const ExportData default_exports[] = {
{"PATH", "/app/bin:/usr/bin"},
/* We always want to unset LD_LIBRARY_PATH to avoid inheriting weird
* dependencies from the host. But if not using ld.so.cache this is
* later set. */
{"LD_LIBRARY_PATH", NULL},
{"XDG_CONFIG_DIRS", "/app/etc/xdg:/etc/xdg"},
{"XDG_DATA_DIRS", "/app/share:/usr/share"},
{"SHELL", "/bin/sh"},
{"TMPDIR", NULL}, /* Unset TMPDIR as it may not exist in the sandbox */
/* Some env vars are common enough and will affect the sandbox badly
if set on the host. We clear these always. */
{"PYTHONPATH", NULL},
{"PERLLIB", NULL},
{"PERL5LIB", NULL},
{"XCURSOR_PATH", NULL},
};
static const ExportData no_ld_so_cache_exports[] = {
{"LD_LIBRARY_PATH", "/app/lib"},
};
static const ExportData devel_exports[] = {
{"ACLOCAL_PATH", "/app/share/aclocal"},
{"C_INCLUDE_PATH", "/app/include"},
{"CPLUS_INCLUDE_PATH", "/app/include"},
{"LDFLAGS", "-L/app/lib "},
{"PKG_CONFIG_PATH", "/app/lib/pkgconfig:/app/share/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig"},
{"LC_ALL", "en_US.utf8"},
};
static void
add_exports (GPtrArray *env_array,
const ExportData *exports,
gsize n_exports)
{
int i;
for (i = 0; i < n_exports; i++)
{
if (exports[i].val)
g_ptr_array_add (env_array, g_strdup_printf ("%s=%s", exports[i].env, exports[i].val));
}
}
char **
flatpak_run_get_minimal_env (gboolean devel, gboolean use_ld_so_cache)
{
GPtrArray *env_array;
static const char * const copy[] = {
"PWD",
"GDMSESSION",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"DESKTOP_SESSION",
"EMAIL_ADDRESS",
"HOME",
"HOSTNAME",
"LOGNAME",
"REAL_NAME",
"TERM",
"USER",
"USERNAME",
};
static const char * const copy_nodevel[] = {
"LANG",
"LANGUAGE",
"LC_ALL",
"LC_ADDRESS",
"LC_COLLATE",
"LC_CTYPE",
"LC_IDENTIFICATION",
"LC_MEASUREMENT",
"LC_MESSAGES",
"LC_MONETARY",
"LC_NAME",
"LC_NUMERIC",
"LC_PAPER",
"LC_TELEPHONE",
"LC_TIME",
};
int i;
env_array = g_ptr_array_new_with_free_func (g_free);
add_exports (env_array, default_exports, G_N_ELEMENTS (default_exports));
if (!use_ld_so_cache)
add_exports (env_array, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));
if (devel)
add_exports (env_array, devel_exports, G_N_ELEMENTS (devel_exports));
for (i = 0; i < G_N_ELEMENTS (copy); i++)
{
const char *current = g_getenv (copy[i]);
if (current)
g_ptr_array_add (env_array, g_strdup_printf ("%s=%s", copy[i], current));
}
if (!devel)
{
for (i = 0; i < G_N_ELEMENTS (copy_nodevel); i++)
{
const char *current = g_getenv (copy_nodevel[i]);
if (current)
g_ptr_array_add (env_array, g_strdup_printf ("%s=%s", copy_nodevel[i], current));
}
}
g_ptr_array_add (env_array, NULL);
return (char **) g_ptr_array_free (env_array, FALSE);
}
static char **
apply_exports (char **envp,
const ExportData *exports,
gsize n_exports)
{
int i;
for (i = 0; i < n_exports; i++)
{
const char *value = exports[i].val;
if (value)
envp = g_environ_setenv (envp, exports[i].env, value, TRUE);
else
envp = g_environ_unsetenv (envp, exports[i].env);
}
return envp;
}
void
flatpak_run_apply_env_default (FlatpakBwrap *bwrap, gboolean use_ld_so_cache)
{
bwrap->envp = apply_exports (bwrap->envp, default_exports, G_N_ELEMENTS (default_exports));
if (!use_ld_so_cache)
bwrap->envp = apply_exports (bwrap->envp, no_ld_so_cache_exports, G_N_ELEMENTS (no_ld_so_cache_exports));
}
static void
flatpak_run_apply_env_prompt (FlatpakBwrap *bwrap, const char *app_id)
{
/* A custom shell prompt. FLATPAK_ID is always set.
* PS1 can be overwritten by runtime metadata or by --env overrides
*/
flatpak_bwrap_set_env (bwrap, "FLATPAK_ID", app_id, TRUE);
flatpak_bwrap_set_env (bwrap, "PS1", "[📦 $FLATPAK_ID \\W]\\$ ", FALSE);
}
void
flatpak_run_apply_env_appid (FlatpakBwrap *bwrap,
GFile *app_dir)
{
g_autoptr(GFile) app_dir_data = NULL;
g_autoptr(GFile) app_dir_config = NULL;
g_autoptr(GFile) app_dir_cache = NULL;
app_dir_data = g_file_get_child (app_dir, "data");
app_dir_config = g_file_get_child (app_dir, "config");
app_dir_cache = g_file_get_child (app_dir, "cache");
flatpak_bwrap_set_env (bwrap, "XDG_DATA_HOME", flatpak_file_get_path_cached (app_dir_data), TRUE);
flatpak_bwrap_set_env (bwrap, "XDG_CONFIG_HOME", flatpak_file_get_path_cached (app_dir_config), TRUE);
flatpak_bwrap_set_env (bwrap, "XDG_CACHE_HOME", flatpak_file_get_path_cached (app_dir_cache), TRUE);
if (g_getenv ("XDG_DATA_HOME"))
flatpak_bwrap_set_env (bwrap, "HOST_XDG_DATA_HOME", g_getenv ("XDG_DATA_HOME"), TRUE);
if (g_getenv ("XDG_CONFIG_HOME"))
flatpak_bwrap_set_env (bwrap, "HOST_XDG_CONFIG_HOME", g_getenv ("XDG_CONFIG_HOME"), TRUE);
if (g_getenv ("XDG_CACHE_HOME"))
flatpak_bwrap_set_env (bwrap, "HOST_XDG_CACHE_HOME", g_getenv ("XDG_CACHE_HOME"), TRUE);
}
void
flatpak_run_apply_env_vars (FlatpakBwrap *bwrap, FlatpakContext *context)
{
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init (&iter, context->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *var = key;
const char *val = value;
if (val && val[0] != 0)
flatpak_bwrap_set_env (bwrap, var, val, TRUE);
else
flatpak_bwrap_unset_env (bwrap, var);
}
}
GFile *
flatpak_get_data_dir (const char *app_id)
{
g_autoptr(GFile) home = g_file_new_for_path (g_get_home_dir ());
g_autoptr(GFile) var_app = g_file_resolve_relative_path (home, ".var/app");
return g_file_get_child (var_app, app_id);
}
gboolean
flatpak_ensure_data_dir (GFile *app_id_dir,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GFile) data_dir = g_file_get_child (app_id_dir, "data");
g_autoptr(GFile) cache_dir = g_file_get_child (app_id_dir, "cache");
g_autoptr(GFile) fontconfig_cache_dir = g_file_get_child (cache_dir, "fontconfig");
g_autoptr(GFile) tmp_dir = g_file_get_child (cache_dir, "tmp");
g_autoptr(GFile) config_dir = g_file_get_child (app_id_dir, "config");
if (!flatpak_mkdir_p (data_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (cache_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (fontconfig_cache_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (tmp_dir, cancellable, error))
return FALSE;
if (!flatpak_mkdir_p (config_dir, cancellable, error))
return FALSE;
return TRUE;
}
struct JobData
{
char *job;
GMainLoop *main_loop;
};
static void
job_removed_cb (SystemdManager *manager,
guint32 id,
char *job,
char *unit,
char *result,
struct JobData *data)
{
if (strcmp (job, data->job) == 0)
g_main_loop_quit (data->main_loop);
}
static gchar *
systemd_unit_name_escape (const gchar *in)
{
/* Adapted from systemd source */
GString * const str = g_string_sized_new (strlen (in));
for (; *in; in++)
{
if (g_ascii_isalnum (*in) || *in == ':' || *in == '_' || *in == '.')
g_string_append_c (str, *in);
else
g_string_append_printf (str, "\\x%02x", *in);
}
return g_string_free (str, FALSE);
}
gboolean
flatpak_run_in_transient_unit (const char *appid, GError **error)
{
g_autoptr(GDBusConnection) conn = NULL;
g_autofree char *path = NULL;
g_autofree char *address = NULL;
g_autofree char *name = NULL;
g_autofree char *appid_escaped = NULL;
g_autofree char *job = NULL;
SystemdManager *manager = NULL;
GVariantBuilder builder;
GVariant *properties = NULL;
GVariant *aux = NULL;
guint32 pid;
GMainLoop *main_loop = NULL;
struct JobData data;
gboolean res = FALSE;
g_autoptr(GMainContextPopDefault) main_context = NULL;
path = g_strdup_printf ("/run/user/%d/systemd/private", getuid ());
if (!g_file_test (path, G_FILE_TEST_EXISTS))
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,
_("No systemd user session available, cgroups not available"));
main_context = flatpak_main_context_new_default ();
main_loop = g_main_loop_new (main_context, FALSE);
address = g_strconcat ("unix:path=", path, NULL);
conn = g_dbus_connection_new_for_address_sync (address,
G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
NULL,
NULL, error);
if (!conn)
goto out;
manager = systemd_manager_proxy_new_sync (conn,
G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
NULL,
"/org/freedesktop/systemd1",
NULL, error);
if (!manager)
goto out;
appid_escaped = systemd_unit_name_escape (appid);
name = g_strdup_printf ("app-flatpak-%s-%d.scope", appid_escaped, getpid ());
g_variant_builder_init (&builder, G_VARIANT_TYPE ("a(sv)"));
pid = getpid ();
g_variant_builder_add (&builder, "(sv)",
"PIDs",
g_variant_new_fixed_array (G_VARIANT_TYPE ("u"),
&pid, 1, sizeof (guint32))
);
properties = g_variant_builder_end (&builder);
aux = g_variant_new_array (G_VARIANT_TYPE ("(sa(sv))"), NULL, 0);
if (!systemd_manager_call_start_transient_unit_sync (manager,
name,
"fail",
properties,
aux,
&job,
NULL,
error))
goto out;
data.job = job;
data.main_loop = main_loop;
g_signal_connect (manager, "job-removed", G_CALLBACK (job_removed_cb), &data);
g_main_loop_run (main_loop);
res = TRUE;
out:
if (main_loop)
g_main_loop_unref (main_loop);
if (manager)
g_object_unref (manager);
return res;
}
static void
add_font_path_args (FlatpakBwrap *bwrap)
{
g_autoptr(GString) xml_snippet = g_string_new ("");
gchar *path_build_tmp = NULL;
g_autoptr(GFile) user_font1 = NULL;
g_autoptr(GFile) user_font2 = NULL;
g_autoptr(GFile) user_font_cache = NULL;
g_auto(GStrv) system_cache_dirs = NULL;
gboolean found_cache = FALSE;
int i;
g_string_append (xml_snippet,
"<?xml version=\"1.0\"?>\n"
"<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n"
"<fontconfig>\n");
if (g_file_test (SYSTEM_FONTS_DIR, G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", SYSTEM_FONTS_DIR, "/run/host/fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/fonts</remap-dir>\n",
SYSTEM_FONTS_DIR);
}
if (g_file_test ("/usr/local/share/fonts", G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/usr/local/share/fonts", "/run/host/local-fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/local-fonts</remap-dir>\n",
"/usr/local/share/fonts");
}
system_cache_dirs = g_strsplit (SYSTEM_FONT_CACHE_DIRS, ":", 0);
for (i = 0; system_cache_dirs[i] != NULL; i++)
{
if (g_file_test (system_cache_dirs[i], G_FILE_TEST_EXISTS))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", system_cache_dirs[i], "/run/host/fonts-cache",
NULL);
found_cache = TRUE;
break;
}
}
if (!found_cache)
{
/* We ensure these directories are never writable, or fontconfig
will use them to write the default cache */
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/run/host/fonts-cache",
"--remount-ro", "/run/host/fonts-cache",
NULL);
}
path_build_tmp = g_build_filename (g_get_user_data_dir (), "fonts", NULL);
user_font1 = g_file_new_for_path (path_build_tmp);
g_clear_pointer (&path_build_tmp, g_free);
path_build_tmp = g_build_filename (g_get_home_dir (), ".fonts", NULL);
user_font2 = g_file_new_for_path (path_build_tmp);
g_clear_pointer (&path_build_tmp, g_free);
if (g_file_query_exists (user_font1, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_font1), "/run/host/user-fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/user-fonts</remap-dir>\n",
flatpak_file_get_path_cached (user_font1));
}
else if (g_file_query_exists (user_font2, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_font2), "/run/host/user-fonts",
NULL);
g_string_append_printf (xml_snippet,
"\t<remap-dir as-path=\"%s\">/run/host/user-fonts</remap-dir>\n",
flatpak_file_get_path_cached (user_font2));
}
path_build_tmp = g_build_filename (g_get_user_cache_dir (), "fontconfig", NULL);
user_font_cache = g_file_new_for_path (path_build_tmp);
g_clear_pointer (&path_build_tmp, g_free);
if (g_file_query_exists (user_font_cache, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_font_cache), "/run/host/user-fonts-cache",
NULL);
}
else
{
/* We ensure these directories are never writable, or fontconfig
will use them to write the default cache */
flatpak_bwrap_add_args (bwrap,
"--tmpfs", "/run/host/user-fonts-cache",
"--remount-ro", "/run/host/user-fonts-cache",
NULL);
}
g_string_append (xml_snippet,
"</fontconfig>\n");
if (!flatpak_bwrap_add_args_data (bwrap, "font-dirs.xml", xml_snippet->str, xml_snippet->len, "/run/host/font-dirs.xml", NULL))
g_warning ("Unable to add fontconfig data snippet");
}
static void
add_icon_path_args (FlatpakBwrap *bwrap)
{
g_autofree gchar *user_icons_path = NULL;
g_autoptr(GFile) user_icons = NULL;
if (g_file_test ("/usr/share/icons", G_FILE_TEST_IS_DIR))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/usr/share/icons", "/run/host/share/icons",
NULL);
}
user_icons_path = g_build_filename (g_get_user_data_dir (), "icons", NULL);
user_icons = g_file_new_for_path (user_icons_path);
if (g_file_query_exists (user_icons, NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (user_icons), "/run/host/user-share/icons",
NULL);
}
}
FlatpakContext *
flatpak_app_compute_permissions (GKeyFile *app_metadata,
GKeyFile *runtime_metadata,
GError **error)
{
g_autoptr(FlatpakContext) app_context = NULL;
app_context = flatpak_context_new ();
if (runtime_metadata != NULL)
{
if (!flatpak_context_load_metadata (app_context, runtime_metadata, error))
return NULL;
/* Don't inherit any permissions from the runtime, only things like env vars. */
flatpak_context_reset_permissions (app_context);
}
if (app_metadata != NULL &&
!flatpak_context_load_metadata (app_context, app_metadata, error))
return NULL;
return g_steal_pointer (&app_context);
}
static void
flatpak_run_gc_ids (void)
{
flatpak_instance_iterate_all_and_gc (NULL);
}
static char *
flatpak_run_allocate_id (int *lock_fd_out)
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *base_dir = g_build_filename (user_runtime_dir, ".flatpak", NULL);
int count;
g_mkdir_with_parents (base_dir, 0755);
flatpak_run_gc_ids ();
for (count = 0; count < 1000; count++)
{
g_autofree char *instance_id = NULL;
g_autofree char *instance_dir = NULL;
instance_id = g_strdup_printf ("%u", g_random_int ());
instance_dir = g_build_filename (base_dir, instance_id, NULL);
/* We use an atomic mkdir to ensure the instance id is unique */
if (mkdir (instance_dir, 0755) == 0)
{
g_autofree char *lock_file = g_build_filename (instance_dir, ".ref", NULL);
glnx_autofd int lock_fd = -1;
struct flock l = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
/* Then we take a file lock inside the dir, hold that during
* setup and in bwrap. Anyone trying to clean up unused
* directories need to first verify that there is a .ref
* file and take a write lock on .ref to ensure its not in
* use. */
lock_fd = open (lock_file, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
/* There is a tiny race here between the open creating the file and the lock succeeding.
We work around that by only gc:ing "old" .ref files */
if (lock_fd != -1 && fcntl (lock_fd, F_SETLK, &l) == 0)
{
*lock_fd_out = glnx_steal_fd (&lock_fd);
g_debug ("Allocated instance id %s", instance_id);
return g_steal_pointer (&instance_id);
}
}
}
return NULL;
}
#ifdef HAVE_DCONF
static void
add_dconf_key_to_keyfile (GKeyFile *keyfile,
DConfClient *client,
const char *key,
DConfReadFlags flags)
{
g_autofree char *group = g_path_get_dirname (key);
g_autofree char *k = g_path_get_basename (key);
GVariant *value = dconf_client_read_full (client, key, flags, NULL);
if (value)
{
g_autofree char *val = g_variant_print (value, TRUE);
g_key_file_set_value (keyfile, group + 1, k, val);
}
}
static void
add_dconf_dir_to_keyfile (GKeyFile *keyfile,
DConfClient *client,
const char *dir,
DConfReadFlags flags)
{
g_auto(GStrv) keys = NULL;
int i;
keys = dconf_client_list (client, dir, NULL);
for (i = 0; keys[i]; i++)
{
g_autofree char *k = g_strconcat (dir, keys[i], NULL);
if (dconf_is_dir (k, NULL))
add_dconf_dir_to_keyfile (keyfile, client, k, flags);
else if (dconf_is_key (k, NULL))
add_dconf_key_to_keyfile (keyfile, client, k, flags);
}
}
static void
add_dconf_locks_to_list (GString *s,
DConfClient *client,
const char *dir)
{
g_auto(GStrv) locks = NULL;
int i;
locks = dconf_client_list_locks (client, dir, NULL);
for (i = 0; locks[i]; i++)
{
g_string_append (s, locks[i]);
g_string_append_c (s, '\n');
}
}
#endif /* HAVE_DCONF */
static void
get_dconf_data (const char *app_id,
const char **paths,
const char *migrate_path,
char **defaults,
gsize *defaults_size,
char **values,
gsize *values_size,
char **locks,
gsize *locks_size)
{
#ifdef HAVE_DCONF
DConfClient *client = NULL;
g_autofree char *prefix = NULL;
#endif
g_autoptr(GKeyFile) defaults_data = NULL;
g_autoptr(GKeyFile) values_data = NULL;
g_autoptr(GString) locks_data = NULL;
defaults_data = g_key_file_new ();
values_data = g_key_file_new ();
locks_data = g_string_new ("");
#ifdef HAVE_DCONF
client = dconf_client_new ();
prefix = flatpak_dconf_path_for_app_id (app_id);
if (migrate_path)
{
g_debug ("Add values in dir '%s', prefix is '%s'", migrate_path, prefix);
if (flatpak_dconf_path_is_similar (migrate_path, prefix))
add_dconf_dir_to_keyfile (values_data, client, migrate_path, DCONF_READ_USER_VALUE);
else
g_warning ("Ignoring D-Conf migrate-path setting %s", migrate_path);
}
g_debug ("Add defaults in dir %s", prefix);
add_dconf_dir_to_keyfile (defaults_data, client, prefix, DCONF_READ_DEFAULT_VALUE);
g_debug ("Add locks in dir %s", prefix);
add_dconf_locks_to_list (locks_data, client, prefix);
/* We allow extra paths for defaults and locks, but not for user values */
if (paths)
{
int i;
for (i = 0; paths[i]; i++)
{
if (dconf_is_dir (paths[i], NULL))
{
g_debug ("Add defaults in dir %s", paths[i]);
add_dconf_dir_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);
g_debug ("Add locks in dir %s", paths[i]);
add_dconf_locks_to_list (locks_data, client, paths[i]);
}
else if (dconf_is_key (paths[i], NULL))
{
g_debug ("Add individual key %s", paths[i]);
add_dconf_key_to_keyfile (defaults_data, client, paths[i], DCONF_READ_DEFAULT_VALUE);
add_dconf_key_to_keyfile (values_data, client, paths[i], DCONF_READ_USER_VALUE);
}
else
{
g_warning ("Ignoring settings path '%s': neither dir nor key", paths[i]);
}
}
}
#endif
*defaults = g_key_file_to_data (defaults_data, defaults_size, NULL);
*values = g_key_file_to_data (values_data, values_size, NULL);
*locks_size = locks_data->len;
*locks = g_string_free (g_steal_pointer (&locks_data), FALSE);
#ifdef HAVE_DCONF
g_object_unref (client);
#endif
}
static gboolean
flatpak_run_add_dconf_args (FlatpakBwrap *bwrap,
const char *app_id,
GKeyFile *metakey,
GError **error)
{
g_auto(GStrv) paths = NULL;
g_autofree char *migrate_path = NULL;
g_autofree char *defaults = NULL;
g_autofree char *values = NULL;
g_autofree char *locks = NULL;
gsize defaults_size;
gsize values_size;
gsize locks_size;
if (metakey)
{
paths = g_key_file_get_string_list (metakey,
FLATPAK_METADATA_GROUP_DCONF,
FLATPAK_METADATA_KEY_DCONF_PATHS,
NULL, NULL);
migrate_path = g_key_file_get_string (metakey,
FLATPAK_METADATA_GROUP_DCONF,
FLATPAK_METADATA_KEY_DCONF_MIGRATE_PATH,
NULL);
}
get_dconf_data (app_id,
(const char **) paths,
migrate_path,
&defaults, &defaults_size,
&values, &values_size,
&locks, &locks_size);
if (defaults_size != 0 &&
!flatpak_bwrap_add_args_data (bwrap,
"dconf-defaults",
defaults, defaults_size,
"/etc/glib-2.0/settings/defaults",
error))
return FALSE;
if (locks_size != 0 &&
!flatpak_bwrap_add_args_data (bwrap,
"dconf-locks",
locks, locks_size,
"/etc/glib-2.0/settings/locks",
error))
return FALSE;
/* We do a one-time conversion of existing dconf settings to a keyfile.
* Only do that once the app stops requesting dconf access.
*/
if (migrate_path)
{
g_autofree char *filename = NULL;
filename = g_build_filename (g_get_home_dir (),
".var/app", app_id,
"config/glib-2.0/settings/keyfile",
NULL);
g_debug ("writing D-Conf values to %s", filename);
if (values_size != 0 && !g_file_test (filename, G_FILE_TEST_EXISTS))
{
g_autofree char *dir = g_path_get_dirname (filename);
if (g_mkdir_with_parents (dir, 0700) == -1)
{
g_warning ("failed creating dirs for %s", filename);
return FALSE;
}
if (!g_file_set_contents (filename, values, values_size, error))
{
g_warning ("failed writing %s", filename);
return FALSE;
}
}
}
return TRUE;
}
gboolean
flatpak_run_add_app_info_args (FlatpakBwrap *bwrap,
GFile *app_files,
GBytes *app_deploy_data,
const char *app_extensions,
GFile *runtime_files,
GBytes *runtime_deploy_data,
const char *runtime_extensions,
const char *app_id,
const char *app_branch,
FlatpakDecomposed *runtime_ref,
GFile *app_id_dir,
FlatpakContext *final_app_context,
FlatpakContext *cmdline_context,
gboolean sandbox,
gboolean build,
gboolean devel,
char **app_info_path_out,
int instance_id_fd,
char **instance_id_host_dir_out,
GError **error)
{
g_autofree char *info_path = NULL;
g_autofree char *bwrapinfo_path = NULL;
int fd, fd2, fd3;
g_autoptr(GKeyFile) keyfile = NULL;
g_autofree char *runtime_path = NULL;
g_autofree char *old_dest = g_strdup_printf ("/run/user/%d/flatpak-info", getuid ());
const char *group;
g_autofree char *instance_id = NULL;
glnx_autofd int lock_fd = -1;
g_autofree char *instance_id_host_dir = NULL;
g_autofree char *instance_id_sandbox_dir = NULL;
g_autofree char *instance_id_lock_file = NULL;
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *arch = flatpak_decomposed_dup_arch (runtime_ref);
instance_id = flatpak_run_allocate_id (&lock_fd);
if (instance_id == NULL)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Unable to allocate instance id"));
instance_id_host_dir = g_build_filename (user_runtime_dir, ".flatpak", instance_id, NULL);
instance_id_sandbox_dir = g_strdup_printf ("/run/user/%d/.flatpak/%s", getuid (), instance_id);
instance_id_lock_file = g_build_filename (instance_id_sandbox_dir, ".ref", NULL);
flatpak_bwrap_add_args (bwrap,
"--ro-bind",
instance_id_host_dir,
instance_id_sandbox_dir,
"--lock-file",
instance_id_lock_file,
NULL);
/* Keep the .ref lock held until we've started bwrap to avoid races */
flatpak_bwrap_add_noinherit_fd (bwrap, glnx_steal_fd (&lock_fd));
info_path = g_build_filename (instance_id_host_dir, "info", NULL);
keyfile = g_key_file_new ();
if (app_files)
group = FLATPAK_METADATA_GROUP_APPLICATION;
else
group = FLATPAK_METADATA_GROUP_RUNTIME;
g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_NAME, app_id);
g_key_file_set_string (keyfile, group, FLATPAK_METADATA_KEY_RUNTIME,
flatpak_decomposed_get_ref (runtime_ref));
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_ID, instance_id);
if (app_id_dir)
{
g_autofree char *instance_path = g_file_get_path (app_id_dir);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_PATH, instance_path);
}
if (app_files)
{
g_autofree char *app_path = g_file_get_path (app_files);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_PATH, app_path);
}
if (app_deploy_data)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_COMMIT, flatpak_deploy_data_get_commit (app_deploy_data));
if (app_extensions && *app_extensions != 0)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_EXTENSIONS, app_extensions);
runtime_path = g_file_get_path (runtime_files);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_PATH, runtime_path);
if (runtime_deploy_data)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_COMMIT, flatpak_deploy_data_get_commit (runtime_deploy_data));
if (runtime_extensions && *runtime_extensions != 0)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_EXTENSIONS, runtime_extensions);
if (app_branch != NULL)
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BRANCH, app_branch);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_ARCH, arch);
g_key_file_set_string (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_FLATPAK_VERSION, PACKAGE_VERSION);
if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SESSION_BUS) == 0)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_SESSION_BUS_PROXY, TRUE);
if ((final_app_context->sockets & FLATPAK_CONTEXT_SOCKET_SYSTEM_BUS) == 0)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_SYSTEM_BUS_PROXY, TRUE);
if (sandbox)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_SANDBOX, TRUE);
if (build)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BUILD, TRUE);
if (devel)
g_key_file_set_boolean (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_DEVEL, TRUE);
if (cmdline_context)
{
g_autoptr(GPtrArray) cmdline_args = g_ptr_array_new_with_free_func (g_free);
flatpak_context_to_args (cmdline_context, cmdline_args);
if (cmdline_args->len > 0)
{
g_key_file_set_string_list (keyfile, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_EXTRA_ARGS,
(const char * const *) cmdline_args->pdata,
cmdline_args->len);
}
}
flatpak_context_save_metadata (final_app_context, TRUE, keyfile);
if (!g_key_file_save_to_file (keyfile, info_path, error))
return FALSE;
/* We want to create a file on /.flatpak-info that the app cannot modify, which
we do by creating a read-only bind mount. This way one can openat()
/proc/$pid/root, and if that succeeds use openat via that to find the
unfakable .flatpak-info file. However, there is a tiny race in that if
you manage to open /proc/$pid/root, but then the pid dies, then
every mount but the root is unmounted in the namespace, so the
.flatpak-info will be empty. We fix this by first creating a real file
with the real info in, then bind-mounting on top of that, the same info.
This way even if the bind-mount is unmounted we can find the real data.
*/
fd = open (info_path, O_RDONLY);
if (fd == -1)
{
int errsv = errno;
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to open flatpak-info file: %s"), g_strerror (errsv));
return FALSE;
}
fd2 = open (info_path, O_RDONLY);
if (fd2 == -1)
{
close (fd);
int errsv = errno;
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to open flatpak-info file: %s"), g_strerror (errsv));
return FALSE;
}
flatpak_bwrap_add_args_data_fd (bwrap,
"--file", fd, "/.flatpak-info");
flatpak_bwrap_add_args_data_fd (bwrap,
"--ro-bind-data", fd2, "/.flatpak-info");
flatpak_bwrap_add_args (bwrap,
"--symlink", "../../../.flatpak-info", old_dest,
NULL);
/* Tell the application that it's running under Flatpak in a generic way. */
flatpak_bwrap_add_args (bwrap,
"--setenv", "container", "flatpak",
NULL);
if (!flatpak_bwrap_add_args_data (bwrap,
"container-manager",
"flatpak\n", -1,
"/run/host/container-manager",
error))
return FALSE;
bwrapinfo_path = g_build_filename (instance_id_host_dir, "bwrapinfo.json", NULL);
fd3 = open (bwrapinfo_path, O_RDWR | O_CREAT, 0644);
if (fd3 == -1)
{
close (fd);
close (fd2);
int errsv = errno;
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to open bwrapinfo.json file: %s"), g_strerror (errsv));
return FALSE;
}
/* NOTE: It is important that this takes place after bwrapinfo.json is created,
otherwise start notifications in the portal may not work. */
if (instance_id_fd != -1)
{
gsize instance_id_position = 0;
gsize instance_id_size = strlen (instance_id);
while (instance_id_size > 0)
{
gssize bytes_written = write (instance_id_fd, instance_id + instance_id_position, instance_id_size);
if (G_UNLIKELY (bytes_written <= 0))
{
int errsv = bytes_written == -1 ? errno : ENOSPC;
if (errsv == EINTR)
continue;
close (fd);
close (fd2);
close (fd3);
g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
_("Failed to write to instance id fd: %s"), g_strerror (errsv));
return FALSE;
}
instance_id_position += bytes_written;
instance_id_size -= bytes_written;
}
close (instance_id_fd);
}
flatpak_bwrap_add_args_data_fd (bwrap, "--info-fd", fd3, NULL);
if (app_info_path_out != NULL)
*app_info_path_out = g_strdup_printf ("/proc/self/fd/%d", fd);
if (instance_id_host_dir_out != NULL)
*instance_id_host_dir_out = g_steal_pointer (&instance_id_host_dir);
return TRUE;
}
static void
add_tzdata_args (FlatpakBwrap *bwrap,
GFile *runtime_files)
{
g_autofree char *raw_timezone = flatpak_get_timezone ();
g_autofree char *timezone_content = g_strdup_printf ("%s\n", raw_timezone);
g_autofree char *localtime_content = g_strconcat ("../usr/share/zoneinfo/", raw_timezone, NULL);
g_autoptr(GFile) runtime_zoneinfo = NULL;
if (runtime_files)
runtime_zoneinfo = g_file_resolve_relative_path (runtime_files, "share/zoneinfo");
/* Check for runtime /usr/share/zoneinfo */
if (runtime_zoneinfo != NULL && g_file_query_exists (runtime_zoneinfo, NULL))
{
/* Check for host /usr/share/zoneinfo */
if (g_file_test ("/usr/share/zoneinfo", G_FILE_TEST_IS_DIR))
{
/* Here we assume the host timezone file exist in the host data */
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/usr/share/zoneinfo", "/usr/share/zoneinfo",
"--symlink", localtime_content, "/etc/localtime",
NULL);
}
else
{
g_autoptr(GFile) runtime_tzfile = g_file_resolve_relative_path (runtime_zoneinfo, raw_timezone);
/* Check if host timezone file exist in the runtime tzdata */
if (g_file_query_exists (runtime_tzfile, NULL))
flatpak_bwrap_add_args (bwrap,
"--symlink", localtime_content, "/etc/localtime",
NULL);
}
}
flatpak_bwrap_add_args_data (bwrap, "timezone",
timezone_content, -1, "/etc/timezone",
NULL);
}
static void
add_monitor_path_args (gboolean use_session_helper,
FlatpakBwrap *bwrap)
{
g_autoptr(AutoFlatpakSessionHelper) session_helper = NULL;
g_autofree char *monitor_path = NULL;
g_autofree char *pkcs11_socket_path = NULL;
g_autoptr(GVariant) session_data = NULL;
if (use_session_helper)
{
session_helper =
flatpak_session_helper_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
"org.freedesktop.Flatpak",
"/org/freedesktop/Flatpak/SessionHelper",
NULL, NULL);
}
if (session_helper &&
flatpak_session_helper_call_request_session_sync (session_helper,
&session_data,
NULL, NULL))
{
if (g_variant_lookup (session_data, "path", "s", &monitor_path))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", monitor_path, "/run/host/monitor",
"--symlink", "/run/host/monitor/resolv.conf", "/etc/resolv.conf",
"--symlink", "/run/host/monitor/host.conf", "/etc/host.conf",
"--symlink", "/run/host/monitor/hosts", "/etc/hosts",
NULL);
if (g_variant_lookup (session_data, "pkcs11-socket", "s", &pkcs11_socket_path))
{
g_autofree char *sandbox_pkcs11_socket_path = g_strdup_printf ("/run/user/%d/p11-kit/pkcs11", getuid ());
const char *trusted_module_contents =
"# This overrides the runtime p11-kit-trusted module with a client one talking to the trust module on the host\n"
"module: p11-kit-client.so\n";
if (flatpak_bwrap_add_args_data (bwrap, "p11-kit-trust.module",
trusted_module_contents, -1,
"/etc/pkcs11/modules/p11-kit-trust.module", NULL))
{
flatpak_bwrap_add_args (bwrap,
"--ro-bind", pkcs11_socket_path, sandbox_pkcs11_socket_path,
NULL);
flatpak_bwrap_unset_env (bwrap, "P11_KIT_SERVER_ADDRESS");
}
}
}
else
{
if (g_file_test ("/etc/resolv.conf", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf",
NULL);
if (g_file_test ("/etc/host.conf", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/etc/host.conf", "/etc/host.conf",
NULL);
if (g_file_test ("/etc/hosts", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap,
"--ro-bind", "/etc/hosts", "/etc/hosts",
NULL);
}
}
static void
add_document_portal_args (FlatpakBwrap *bwrap,
const char *app_id,
char **out_mount_path)
{
g_autoptr(GDBusConnection) session_bus = NULL;
g_autofree char *doc_mount_path = NULL;
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
if (session_bus)
{
g_autoptr(GError) local_error = NULL;
g_autoptr(GDBusMessage) reply = NULL;
g_autoptr(GDBusMessage) msg =
g_dbus_message_new_method_call ("org.freedesktop.portal.Documents",
"/org/freedesktop/portal/documents",
"org.freedesktop.portal.Documents",
"GetMountPoint");
g_dbus_message_set_body (msg, g_variant_new ("()"));
reply =
g_dbus_connection_send_message_with_reply_sync (session_bus, msg,
G_DBUS_SEND_MESSAGE_FLAGS_NONE,
30000,
NULL,
NULL,
NULL);
if (reply)
{
if (g_dbus_message_to_gerror (reply, &local_error))
{
if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN))
g_debug ("Document portal not available, not mounting /run/user/%d/doc", getuid ());
else
g_message ("Can't get document portal: %s", local_error->message);
}
else
{
g_autofree char *src_path = NULL;
g_autofree char *dst_path = NULL;
g_variant_get (g_dbus_message_get_body (reply),
"(^ay)", &doc_mount_path);
src_path = g_strdup_printf ("%s/by-app/%s",
doc_mount_path, app_id);
dst_path = g_strdup_printf ("/run/user/%d/doc", getuid ());
flatpak_bwrap_add_args (bwrap, "--bind", src_path, dst_path, NULL);
}
}
}
*out_mount_path = g_steal_pointer (&doc_mount_path);
}
#ifdef ENABLE_SECCOMP
static const uint32_t seccomp_x86_64_extra_arches[] = { SCMP_ARCH_X86, 0, };
#ifdef SCMP_ARCH_AARCH64
static const uint32_t seccomp_aarch64_extra_arches[] = { SCMP_ARCH_ARM, 0 };
#endif
static inline void
cleanup_seccomp (void *p)
{
scmp_filter_ctx *pp = (scmp_filter_ctx *) p;
if (*pp)
seccomp_release (*pp);
}
static gboolean
setup_seccomp (FlatpakBwrap *bwrap,
const char *arch,
gulong allowed_personality,
FlatpakRunFlags run_flags,
GError **error)
{
gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;
gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;
__attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;
/**** BEGIN NOTE ON CODE SHARING
*
* There are today a number of different Linux container
* implementations. That will likely continue for long into the
* future. But we can still try to share code, and it's important
* to do so because it affects what library and application writers
* can do, and we should support code portability between different
* container tools.
*
* This syscall blocklist is copied from linux-user-chroot, which was in turn
* clearly influenced by the Sandstorm.io blocklist.
*
* If you make any changes here, I suggest sending the changes along
* to other sandbox maintainers. Using the libseccomp list is also
* an appropriate venue:
* https://groups.google.com/forum/#!forum/libseccomp
*
* A non-exhaustive list of links to container tooling that might
* want to share this blocklist:
*
* https://github.com/sandstorm-io/sandstorm
* in src/sandstorm/supervisor.c++
* https://github.com/flatpak/flatpak.git
* in common/flatpak-run.c
* https://git.gnome.org/browse/linux-user-chroot
* in src/setup-seccomp.c
*
**** END NOTE ON CODE SHARING
*/
struct
{
int scall;
struct scmp_arg_cmp *arg;
} syscall_blocklist[] = {
/* Block dmesg */
{SCMP_SYS (syslog)},
/* Useless old syscall */
{SCMP_SYS (uselib)},
/* Don't allow disabling accounting */
{SCMP_SYS (acct)},
/* 16-bit code is unnecessary in the sandbox, and modify_ldt is a
historic source of interesting information leaks. */
{SCMP_SYS (modify_ldt)},
/* Don't allow reading current quota use */
{SCMP_SYS (quotactl)},
/* Don't allow access to the kernel keyring */
{SCMP_SYS (add_key)},
{SCMP_SYS (keyctl)},
{SCMP_SYS (request_key)},
/* Scary VM/NUMA ops */
{SCMP_SYS (move_pages)},
{SCMP_SYS (mbind)},
{SCMP_SYS (get_mempolicy)},
{SCMP_SYS (set_mempolicy)},
{SCMP_SYS (migrate_pages)},
/* Don't allow subnamespace setups: */
{SCMP_SYS (unshare)},
{SCMP_SYS (mount)},
{SCMP_SYS (pivot_root)},
#if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)
/* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack
* and flags arguments are reversed so the flags come second */
{SCMP_SYS (clone), &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},
#else
/* Normally the flags come first */
{SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},
#endif
/* Don't allow faking input to the controlling tty (CVE-2017-5226) */
{SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)},
};
struct
{
int scall;
struct scmp_arg_cmp *arg;
} syscall_nondevel_blocklist[] = {
/* Profiling operations; we expect these to be done by tools from outside
* the sandbox. In particular perf has been the source of many CVEs.
*/
{SCMP_SYS (perf_event_open)},
/* Don't allow you to switch to bsd emulation or whatnot */
{SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},
{SCMP_SYS (ptrace)}
};
/* Blocklist all but unix, inet, inet6 and netlink */
struct
{
int family;
FlatpakRunFlags flags_mask;
} socket_family_allowlist[] = {
/* NOTE: Keep in numerical order */
{ AF_UNSPEC, 0 },
{ AF_LOCAL, 0 },
{ AF_INET, 0 },
{ AF_INET6, 0 },
{ AF_NETLINK, 0 },
{ AF_CAN, FLATPAK_RUN_FLAG_CANBUS },
{ AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },
};
int last_allowed_family;
int i, r;
g_auto(GLnxTmpfile) seccomp_tmpf = { 0, };
seccomp = seccomp_init (SCMP_ACT_ALLOW);
if (!seccomp)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Initialize seccomp failed"));
if (arch != NULL)
{
uint32_t arch_id = 0;
const uint32_t *extra_arches = NULL;
if (strcmp (arch, "i386") == 0)
{
arch_id = SCMP_ARCH_X86;
}
else if (strcmp (arch, "x86_64") == 0)
{
arch_id = SCMP_ARCH_X86_64;
extra_arches = seccomp_x86_64_extra_arches;
}
else if (strcmp (arch, "arm") == 0)
{
arch_id = SCMP_ARCH_ARM;
}
#ifdef SCMP_ARCH_AARCH64
else if (strcmp (arch, "aarch64") == 0)
{
arch_id = SCMP_ARCH_AARCH64;
extra_arches = seccomp_aarch64_extra_arches;
}
#endif
/* We only really need to handle arches on multiarch systems.
* If only one arch is supported the default is fine */
if (arch_id != 0)
{
/* This *adds* the target arch, instead of replacing the
native one. This is not ideal, because we'd like to only
allow the target arch, but we can't really disallow the
native arch at this point, because then bubblewrap
couldn't continue running. */
r = seccomp_arch_add (seccomp, arch_id);
if (r < 0 && r != -EEXIST)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add architecture to seccomp filter"));
if (multiarch && extra_arches != NULL)
{
for (i = 0; extra_arches[i] != 0; i++)
{
r = seccomp_arch_add (seccomp, extra_arches[i]);
if (r < 0 && r != -EEXIST)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add multiarch architecture to seccomp filter"));
}
}
}
}
/* TODO: Should we filter the kernel keyring syscalls in some way?
* We do want them to be used by desktop apps, but they could also perhaps
* leak system stuff or secrets from other apps.
*/
for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++)
{
int scall = syscall_blocklist[i].scall;
if (syscall_blocklist[i].arg)
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blocklist[i].arg);
else
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);
if (r < 0 && r == -EFAULT /* unknown syscall */)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall);
}
if (!devel)
{
for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++)
{
int scall = syscall_nondevel_blocklist[i].scall;
if (syscall_nondevel_blocklist[i].arg)
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blocklist[i].arg);
else
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);
if (r < 0 && r == -EFAULT /* unknown syscall */)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall);
}
}
/* Socket filtering doesn't work on e.g. i386, so ignore failures here
* However, we need to user seccomp_rule_add_exact to avoid libseccomp doing
* something else: https://github.com/seccomp/libseccomp/issues/8 */
last_allowed_family = -1;
for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++)
{
int family = socket_family_allowlist[i].family;
int disallowed;
if (socket_family_allowlist[i].flags_mask != 0 &&
(socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask)
continue;
for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)
{
/* Blocklist the in-between valid families */
seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));
}
last_allowed_family = family;
}
/* Blocklist the rest */
seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));
if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, "/tmp", &seccomp_tmpf, error))
return FALSE;
if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to export bpf"));
lseek (seccomp_tmpf.fd, 0, SEEK_SET);
flatpak_bwrap_add_args_data_fd (bwrap,
"--seccomp", glnx_steal_fd (&seccomp_tmpf.fd), NULL);
return TRUE;
}
#endif
static void
flatpak_run_setup_usr_links (FlatpakBwrap *bwrap,
GFile *runtime_files)
{
int i;
if (runtime_files == NULL)
return;
for (i = 0; flatpak_abs_usrmerged_dirs[i] != NULL; i++)
{
const char *subdir = flatpak_abs_usrmerged_dirs[i];
g_autoptr(GFile) runtime_subdir = NULL;
g_assert (subdir[0] == '/');
/* Skip the '/' when using as a subdirectory of the runtime */
runtime_subdir = g_file_get_child (runtime_files, subdir + 1);
if (g_file_query_exists (runtime_subdir, NULL))
{
g_autofree char *link = g_strconcat ("usr", subdir, NULL);
flatpak_bwrap_add_args (bwrap,
"--symlink", link, subdir,
NULL);
}
}
}
gboolean
flatpak_run_setup_base_argv (FlatpakBwrap *bwrap,
GFile *runtime_files,
GFile *app_id_dir,
const char *arch,
FlatpakRunFlags flags,
GError **error)
{
g_autofree char *run_dir = NULL;
g_autofree char *passwd_contents = NULL;
g_autoptr(GString) group_contents = NULL;
const char *pkcs11_conf_contents = NULL;
struct group *g;
gulong pers;
gid_t gid = getgid ();
g_autoptr(GFile) etc = NULL;
run_dir = g_strdup_printf ("/run/user/%d", getuid ());
passwd_contents = g_strdup_printf ("%s:x:%d:%d:%s:%s:%s\n"
"nfsnobody:x:65534:65534:Unmapped user:/:/sbin/nologin\n",
g_get_user_name (),
getuid (), gid,
g_get_real_name (),
g_get_home_dir (),
DEFAULT_SHELL);
group_contents = g_string_new ("");
g = getgrgid (gid);
/* if NULL, the primary group is not known outside the container, so
* it might as well stay unknown inside the container... */
if (g != NULL)
g_string_append_printf (group_contents, "%s:x:%d:%s\n",
g->gr_name, gid, g_get_user_name ());
g_string_append (group_contents, "nfsnobody:x:65534:\n");
pkcs11_conf_contents =
"# Disable user pkcs11 config, because the host modules don't work in the runtime\n"
"user-config: none\n";
if ((flags & FLATPAK_RUN_FLAG_NO_PROC) == 0)
flatpak_bwrap_add_args (bwrap,
"--proc", "/proc",
NULL);
if (!(flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS))
flatpak_bwrap_add_arg (bwrap, "--unshare-pid");
flatpak_bwrap_add_args (bwrap,
"--dir", "/tmp",
"--dir", "/var/tmp",
"--dir", "/run/host",
"--dir", run_dir,
"--setenv", "XDG_RUNTIME_DIR", run_dir,
"--symlink", "../run", "/var/run",
"--ro-bind", "/sys/block", "/sys/block",
"--ro-bind", "/sys/bus", "/sys/bus",
"--ro-bind", "/sys/class", "/sys/class",
"--ro-bind", "/sys/dev", "/sys/dev",
"--ro-bind", "/sys/devices", "/sys/devices",
"--ro-bind-try", "/proc/self/ns/user", "/run/.userns",
/* glib uses this like /etc/timezone */
"--symlink", "/etc/timezone", "/var/db/zoneinfo",
NULL);
if (flags & FLATPAK_RUN_FLAG_DIE_WITH_PARENT)
flatpak_bwrap_add_args (bwrap,
"--die-with-parent",
NULL);
if (flags & FLATPAK_RUN_FLAG_WRITABLE_ETC)
flatpak_bwrap_add_args (bwrap,
"--dir", "/usr/etc",
"--symlink", "usr/etc", "/etc",
NULL);
if (!flatpak_bwrap_add_args_data (bwrap, "passwd", passwd_contents, -1, "/etc/passwd", error))
return FALSE;
if (!flatpak_bwrap_add_args_data (bwrap, "group", group_contents->str, -1, "/etc/group", error))
return FALSE;
if (!flatpak_bwrap_add_args_data (bwrap, "pkcs11.conf", pkcs11_conf_contents, -1, "/etc/pkcs11/pkcs11.conf", error))
return FALSE;
if (g_file_test ("/etc/machine-id", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--ro-bind", "/etc/machine-id", "/etc/machine-id", NULL);
else if (g_file_test ("/var/lib/dbus/machine-id", G_FILE_TEST_EXISTS))
flatpak_bwrap_add_args (bwrap, "--ro-bind", "/var/lib/dbus/machine-id", "/etc/machine-id", NULL);
if (runtime_files)
etc = g_file_get_child (runtime_files, "etc");
if (etc != NULL &&
(flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0 &&
g_file_query_exists (etc, NULL))
{
g_auto(GLnxDirFdIterator) dfd_iter = { 0, };
struct dirent *dent;
gboolean inited;
inited = glnx_dirfd_iterator_init_at (AT_FDCWD, flatpak_file_get_path_cached (etc), FALSE, &dfd_iter, NULL);
while (inited)
{
g_autofree char *src = NULL;
g_autofree char *dest = NULL;
if (!glnx_dirfd_iterator_next_dent_ensure_dtype (&dfd_iter, &dent, NULL, NULL) || dent == NULL)
break;
if (strcmp (dent->d_name, "passwd") == 0 ||
strcmp (dent->d_name, "group") == 0 ||
strcmp (dent->d_name, "machine-id") == 0 ||
strcmp (dent->d_name, "resolv.conf") == 0 ||
strcmp (dent->d_name, "host.conf") == 0 ||
strcmp (dent->d_name, "hosts") == 0 ||
strcmp (dent->d_name, "localtime") == 0 ||
strcmp (dent->d_name, "timezone") == 0 ||
strcmp (dent->d_name, "pkcs11") == 0)
continue;
src = g_build_filename (flatpak_file_get_path_cached (etc), dent->d_name, NULL);
dest = g_build_filename ("/etc", dent->d_name, NULL);
if (dent->d_type == DT_LNK)
{
g_autofree char *target = NULL;
target = glnx_readlinkat_malloc (dfd_iter.fd, dent->d_name,
NULL, error);
if (target == NULL)
return FALSE;
flatpak_bwrap_add_args (bwrap, "--symlink", target, dest, NULL);
}
else
{
flatpak_bwrap_add_args (bwrap, "--ro-bind", src, dest, NULL);
}
}
}
if (app_id_dir != NULL)
{
g_autoptr(GFile) app_cache_dir = g_file_get_child (app_id_dir, "cache");
g_autoptr(GFile) app_tmp_dir = g_file_get_child (app_cache_dir, "tmp");
g_autoptr(GFile) app_data_dir = g_file_get_child (app_id_dir, "data");
g_autoptr(GFile) app_config_dir = g_file_get_child (app_id_dir, "config");
flatpak_bwrap_add_args (bwrap,
/* These are nice to have as a fixed path */
"--bind", flatpak_file_get_path_cached (app_cache_dir), "/var/cache",
"--bind", flatpak_file_get_path_cached (app_data_dir), "/var/data",
"--bind", flatpak_file_get_path_cached (app_config_dir), "/var/config",
"--bind", flatpak_file_get_path_cached (app_tmp_dir), "/var/tmp",
NULL);
}
flatpak_run_setup_usr_links (bwrap, runtime_files);
add_tzdata_args (bwrap, runtime_files);
pers = PER_LINUX;
if ((flags & FLATPAK_RUN_FLAG_SET_PERSONALITY) &&
flatpak_is_linux32_arch (arch))
{
g_debug ("Setting personality linux32");
pers = PER_LINUX32;
}
/* Always set the personallity, and clear all weird flags */
personality (pers);
#ifdef ENABLE_SECCOMP
if (!setup_seccomp (bwrap, arch, pers, flags, error))
return FALSE;
#endif
if ((flags & FLATPAK_RUN_FLAG_WRITABLE_ETC) == 0)
add_monitor_path_args ((flags & FLATPAK_RUN_FLAG_NO_SESSION_HELPER) == 0, bwrap);
return TRUE;
}
static gboolean
forward_file (XdpDbusDocuments *documents,
const char *app_id,
const char *file,
char **out_doc_id,
GError **error)
{
int fd, fd_id;
g_autofree char *doc_id = NULL;
g_autoptr(GUnixFDList) fd_list = NULL;
const char *perms[] = { "read", "write", NULL };
fd = open (file, O_PATH | O_CLOEXEC);
if (fd == -1)
return flatpak_fail (error, _("Failed to open ‘%s’"), file);
fd_list = g_unix_fd_list_new ();
fd_id = g_unix_fd_list_append (fd_list, fd, error);
close (fd);
if (!xdp_dbus_documents_call_add_sync (documents,
g_variant_new ("h", fd_id),
TRUE, /* reuse */
FALSE, /* not persistent */
fd_list,
&doc_id,
NULL,
NULL,
error))
{
if (error)
g_dbus_error_strip_remote_error (*error);
return FALSE;
}
if (!xdp_dbus_documents_call_grant_permissions_sync (documents,
doc_id,
app_id,
perms,
NULL,
error))
{
if (error)
g_dbus_error_strip_remote_error (*error);
return FALSE;
}
*out_doc_id = g_steal_pointer (&doc_id);
return TRUE;
}
static gboolean
add_rest_args (FlatpakBwrap *bwrap,
const char *app_id,
FlatpakExports *exports,
gboolean file_forwarding,
const char *doc_mount_path,
char *args[],
int n_args,
GError **error)
{
g_autoptr(XdpDbusDocuments) documents = NULL;
gboolean forwarding = FALSE;
gboolean forwarding_uri = FALSE;
gboolean can_forward = TRUE;
int i;
if (file_forwarding && doc_mount_path == NULL)
{
g_message ("Can't get document portal mount path");
can_forward = FALSE;
}
else if (file_forwarding)
{
g_autoptr(GError) local_error = NULL;
documents = xdp_dbus_documents_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION, 0,
"org.freedesktop.portal.Documents",
"/org/freedesktop/portal/documents",
NULL,
&local_error);
if (documents == NULL)
{
g_message ("Can't get document portal: %s", local_error->message);
can_forward = FALSE;
}
}
for (i = 0; i < n_args; i++)
{
g_autoptr(GFile) file = NULL;
if (file_forwarding &&
(strcmp (args[i], "@@") == 0 ||
strcmp (args[i], "@@u") == 0))
{
forwarding_uri = strcmp (args[i], "@@u") == 0;
forwarding = !forwarding;
continue;
}
if (can_forward && forwarding)
{
if (forwarding_uri)
{
if (g_str_has_prefix (args[i], "file:"))
file = g_file_new_for_uri (args[i]);
else if (G_IS_DIR_SEPARATOR (args[i][0]))
file = g_file_new_for_path (args[i]);
}
else
file = g_file_new_for_path (args[i]);
}
if (file && !flatpak_exports_path_is_visible (exports,
flatpak_file_get_path_cached (file)))
{
g_autofree char *doc_id = NULL;
g_autofree char *basename = NULL;
g_autofree char *doc_path = NULL;
if (!forward_file (documents, app_id, flatpak_file_get_path_cached (file),
&doc_id, error))
return FALSE;
basename = g_file_get_basename (file);
doc_path = g_build_filename (doc_mount_path, doc_id, basename, NULL);
if (forwarding_uri)
{
g_autofree char *path = doc_path;
doc_path = g_filename_to_uri (path, NULL, NULL);
/* This should never fail */
g_assert (doc_path != NULL);
}
g_debug ("Forwarding file '%s' as '%s' to %s", args[i], doc_path, app_id);
flatpak_bwrap_add_arg (bwrap, doc_path);
}
else
flatpak_bwrap_add_arg (bwrap, args[i]);
}
return TRUE;
}
FlatpakContext *
flatpak_context_load_for_deploy (FlatpakDeploy *deploy,
GError **error)
{
g_autoptr(FlatpakContext) context = NULL;
g_autoptr(FlatpakContext) overrides = NULL;
g_autoptr(GKeyFile) metakey = NULL;
metakey = flatpak_deploy_get_metadata (deploy);
context = flatpak_app_compute_permissions (metakey, NULL, error);
if (context == NULL)
return NULL;
overrides = flatpak_deploy_get_overrides (deploy);
flatpak_context_merge (context, overrides);
return g_steal_pointer (&context);
}
static char *
calculate_ld_cache_checksum (GBytes *app_deploy_data,
GBytes *runtime_deploy_data,
const char *app_extensions,
const char *runtime_extensions)
{
g_autoptr(GChecksum) ld_so_checksum = g_checksum_new (G_CHECKSUM_SHA256);
if (app_deploy_data)
g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (app_deploy_data), -1);
g_checksum_update (ld_so_checksum, (guchar *) flatpak_deploy_data_get_commit (runtime_deploy_data), -1);
if (app_extensions)
g_checksum_update (ld_so_checksum, (guchar *) app_extensions, -1);
if (runtime_extensions)
g_checksum_update (ld_so_checksum, (guchar *) runtime_extensions, -1);
return g_strdup (g_checksum_get_string (ld_so_checksum));
}
static gboolean
add_ld_so_conf (FlatpakBwrap *bwrap,
GError **error)
{
const char *contents =
"include /run/flatpak/ld.so.conf.d/app-*.conf\n"
"include /app/etc/ld.so.conf\n"
"/app/lib\n"
"include /run/flatpak/ld.so.conf.d/runtime-*.conf\n";
return flatpak_bwrap_add_args_data (bwrap, "ld-so-conf",
contents, -1, "/etc/ld.so.conf", error);
}
static int
regenerate_ld_cache (GPtrArray *base_argv_array,
GArray *base_fd_array,
GFile *app_id_dir,
const char *checksum,
GFile *runtime_files,
gboolean generate_ld_so_conf,
GCancellable *cancellable,
GError **error)
{
g_autoptr(FlatpakBwrap) bwrap = NULL;
g_autoptr(GArray) combined_fd_array = NULL;
g_autoptr(GFile) ld_so_cache = NULL;
g_autoptr(GFile) ld_so_cache_tmp = NULL;
g_autofree char *sandbox_cache_path = NULL;
g_autofree char *tmp_basename = NULL;
g_auto(GStrv) minimal_envp = NULL;
g_autofree char *commandline = NULL;
int exit_status;
glnx_autofd int ld_so_fd = -1;
g_autoptr(GFile) ld_so_dir = NULL;
if (app_id_dir)
ld_so_dir = g_file_get_child (app_id_dir, ".ld.so");
else
{
g_autoptr(GFile) base_dir = g_file_new_for_path (g_get_user_cache_dir ());
ld_so_dir = g_file_resolve_relative_path (base_dir, "flatpak/ld.so");
}
ld_so_cache = g_file_get_child (ld_so_dir, checksum);
ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache), O_RDONLY);
if (ld_so_fd >= 0)
return glnx_steal_fd (&ld_so_fd);
g_debug ("Regenerating ld.so.cache %s", flatpak_file_get_path_cached (ld_so_cache));
if (!flatpak_mkdir_p (ld_so_dir, cancellable, error))
return FALSE;
minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);
bwrap = flatpak_bwrap_new (minimal_envp);
flatpak_bwrap_append_args (bwrap, base_argv_array);
flatpak_run_setup_usr_links (bwrap, runtime_files);
if (generate_ld_so_conf)
{
if (!add_ld_so_conf (bwrap, error))
return -1;
}
else
flatpak_bwrap_add_args (bwrap,
"--symlink", "../usr/etc/ld.so.conf", "/etc/ld.so.conf",
NULL);
tmp_basename = g_strconcat (checksum, ".XXXXXX", NULL);
glnx_gen_temp_name (tmp_basename);
sandbox_cache_path = g_build_filename ("/run/ld-so-cache-dir", tmp_basename, NULL);
ld_so_cache_tmp = g_file_get_child (ld_so_dir, tmp_basename);
flatpak_bwrap_add_args (bwrap,
"--unshare-pid",
"--unshare-ipc",
"--unshare-net",
"--proc", "/proc",
"--dev", "/dev",
"--bind", flatpak_file_get_path_cached (ld_so_dir), "/run/ld-so-cache-dir",
NULL);
if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))
return -1;
flatpak_bwrap_add_args (bwrap,
"ldconfig", "-X", "-C", sandbox_cache_path, NULL);
flatpak_bwrap_finish (bwrap);
commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);
g_debug ("Running: '%s'", commandline);
combined_fd_array = g_array_new (FALSE, TRUE, sizeof (int));
g_array_append_vals (combined_fd_array, base_fd_array->data, base_fd_array->len);
g_array_append_vals (combined_fd_array, bwrap->fds->data, bwrap->fds->len);
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_sync (NULL,
(char **) bwrap->argv->pdata,
bwrap->envp,
G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
flatpak_bwrap_child_setup_cb, combined_fd_array,
NULL, NULL,
&exit_status,
error))
return -1;
if (!WIFEXITED (exit_status) || WEXITSTATUS (exit_status) != 0)
{
flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED,
_("ldconfig failed, exit status %d"), exit_status);
return -1;
}
ld_so_fd = open (flatpak_file_get_path_cached (ld_so_cache_tmp), O_RDONLY);
if (ld_so_fd < 0)
{
flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Can't open generated ld.so.cache"));
return -1;
}
if (app_id_dir == NULL)
{
/* For runs without an app id dir we always regenerate the ld.so.cache */
unlink (flatpak_file_get_path_cached (ld_so_cache_tmp));
}
else
{
g_autoptr(GFile) active = g_file_get_child (ld_so_dir, "active");
/* For app-dirs we keep one checksum alive, by pointing the active symlink to it */
/* Rename to known name, possibly overwriting existing ref if race */
if (rename (flatpak_file_get_path_cached (ld_so_cache_tmp), flatpak_file_get_path_cached (ld_so_cache)) == -1)
{
glnx_set_error_from_errno (error);
return -1;
}
if (!flatpak_switch_symlink_and_remove (flatpak_file_get_path_cached (active),
checksum, error))
return -1;
}
return glnx_steal_fd (&ld_so_fd);
}
/* Check that this user is actually allowed to run this app. When running
* from the gnome-initial-setup session, an app filter might not be available. */
static gboolean
check_parental_controls (FlatpakDecomposed *app_ref,
FlatpakDeploy *deploy,
GCancellable *cancellable,
GError **error)
{
#ifdef HAVE_LIBMALCONTENT
g_autoptr(MctManager) manager = NULL;
g_autoptr(MctAppFilter) app_filter = NULL;
g_autoptr(GAsyncResult) app_filter_result = NULL;
g_autoptr(GDBusConnection) system_bus = NULL;
g_autoptr(GError) local_error = NULL;
g_autoptr(GDesktopAppInfo) app_info = NULL;
gboolean allowed = FALSE;
system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
if (system_bus == NULL)
return FALSE;
manager = mct_manager_new (system_bus);
app_filter = mct_manager_get_app_filter (manager, getuid (),
MCT_GET_APP_FILTER_FLAGS_INTERACTIVE,
cancellable, &local_error);
if (g_error_matches (local_error, MCT_APP_FILTER_ERROR, MCT_APP_FILTER_ERROR_DISABLED))
{
g_debug ("Skipping parental controls check for %s since parental "
"controls are disabled globally", flatpak_decomposed_get_ref (app_ref));
return TRUE;
}
else if (g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN) ||
g_error_matches (local_error, G_DBUS_ERROR, G_DBUS_ERROR_NAME_HAS_NO_OWNER))
{
g_debug ("Skipping parental controls check for %s since a required "
"service was not found", flatpak_decomposed_get_ref (app_ref));
return TRUE;
}
else if (local_error != NULL)
{
g_propagate_error (error, g_steal_pointer (&local_error));
return FALSE;
}
/* Always filter by app ID. Additionally, filter by app info (which runs
* multiple checks, including whether the app ID, executable path and
* content types are allowed) if available. If the flatpak contains
* multiple .desktop files, we use the main one. The app ID check is
* always done, as the binary executed by `flatpak run` isn’t necessarily
* extracted from a .desktop file. */
allowed = mct_app_filter_is_flatpak_ref_allowed (app_filter, flatpak_decomposed_get_ref (app_ref));
/* Look up the app’s main .desktop file. */
if (deploy != NULL && allowed)
{
g_autoptr(GFile) deploy_dir = NULL;
const char *deploy_path;
g_autofree char *desktop_file_name = NULL;
g_autofree char *desktop_file_path = NULL;
g_autofree char *app_id = flatpak_decomposed_dup_id (app_ref);
deploy_dir = flatpak_deploy_get_dir (deploy);
deploy_path = flatpak_file_get_path_cached (deploy_dir);
desktop_file_name = g_strconcat (app_id, ".desktop", NULL);
desktop_file_path = g_build_path (G_DIR_SEPARATOR_S,
deploy_path,
"export",
"share",
"applications",
desktop_file_name,
NULL);
app_info = g_desktop_app_info_new_from_filename (desktop_file_path);
}
if (app_info != NULL)
allowed = allowed && mct_app_filter_is_appinfo_allowed (app_filter,
G_APP_INFO (app_info));
if (!allowed)
return flatpak_fail_error (error, FLATPAK_ERROR_PERMISSION_DENIED,
/* Translators: The placeholder is for an app ref. */
_("Running %s is not allowed by the policy set by your administrator"),
flatpak_decomposed_get_ref (app_ref));
#endif /* HAVE_LIBMALCONTENT */
return TRUE;
}
static int
open_namespace_fd_if_needed (const char *path,
const char *other_path) {
struct stat s, other_s;
if (stat (path, &s) != 0)
return -1; /* No such namespace, ignore */
if (stat (other_path, &other_s) != 0)
return -1; /* No such namespace, ignore */
/* setns calls fail if the process is already in the desired namespace, hence the
check here to ensure the namespaces are different. */
if (s.st_ino != other_s.st_ino)
return open (path, O_RDONLY|O_CLOEXEC);
return -1;
}
static gboolean
check_sudo (GError **error)
{
const char *sudo_command_env = g_getenv ("SUDO_COMMAND");
g_auto(GStrv) split_command = NULL;
/* This check exists to stop accidental usage of `sudo flatpak run`
and is not to prevent running as root.
*/
if (!sudo_command_env)
return TRUE;
/* SUDO_COMMAND could be a value like `/usr/bin/flatpak run foo` */
split_command = g_strsplit (sudo_command_env, " ", 2);
if (g_str_has_suffix (split_command[0], "flatpak"))
return flatpak_fail_error (error, FLATPAK_ERROR, _("\"flatpak run\" is not intended to be ran with sudo"));
return TRUE;
}
gboolean
flatpak_run_app (FlatpakDecomposed *app_ref,
FlatpakDeploy *app_deploy,
FlatpakContext *extra_context,
const char *custom_runtime,
const char *custom_runtime_version,
const char *custom_runtime_commit,
int parent_pid,
FlatpakRunFlags flags,
const char *cwd,
const char *custom_command,
char *args[],
int n_args,
int instance_id_fd,
char **instance_dir_out,
GCancellable *cancellable,
GError **error)
{
g_autoptr(FlatpakDeploy) runtime_deploy = NULL;
g_autoptr(GBytes) runtime_deploy_data = NULL;
g_autoptr(GBytes) app_deploy_data = NULL;
g_autoptr(GFile) app_files = NULL;
g_autoptr(GFile) runtime_files = NULL;
g_autoptr(GFile) bin_ldconfig = NULL;
g_autoptr(GFile) app_id_dir = NULL;
g_autoptr(GFile) real_app_id_dir = NULL;
g_autofree char *default_runtime_pref = NULL;
g_autoptr(FlatpakDecomposed) default_runtime = NULL;
g_autofree char *default_command = NULL;
g_autoptr(GKeyFile) metakey = NULL;
g_autoptr(GKeyFile) runtime_metakey = NULL;
g_autoptr(FlatpakBwrap) bwrap = NULL;
const char *command = "/bin/sh";
g_autoptr(GError) my_error = NULL;
g_autoptr(FlatpakDecomposed) runtime_ref = NULL;
int i;
g_autoptr(GPtrArray) previous_app_id_dirs = NULL;
g_autofree char *app_id = NULL;
g_autofree char *app_arch = NULL;
g_autofree char *app_info_path = NULL;
g_autofree char *instance_id_host_dir = NULL;
g_autoptr(FlatpakContext) app_context = NULL;
g_autoptr(FlatpakContext) overrides = NULL;
g_autoptr(FlatpakExports) exports = NULL;
g_autofree char *commandline = NULL;
g_autofree char *doc_mount_path = NULL;
g_autofree char *app_extensions = NULL;
g_autofree char *runtime_extensions = NULL;
g_autofree char *checksum = NULL;
int ld_so_fd = -1;
g_autoptr(GFile) runtime_ld_so_conf = NULL;
gboolean generate_ld_so_conf = TRUE;
gboolean use_ld_so_cache = TRUE;
gboolean sandboxed = (flags & FLATPAK_RUN_FLAG_SANDBOX) != 0;
gboolean parent_expose_pids = (flags & FLATPAK_RUN_FLAG_PARENT_EXPOSE_PIDS) != 0;
gboolean parent_share_pids = (flags & FLATPAK_RUN_FLAG_PARENT_SHARE_PIDS) != 0;
struct stat s;
if (!check_sudo (error))
return FALSE;
app_id = flatpak_decomposed_dup_id (app_ref);
app_arch = flatpak_decomposed_dup_arch (app_ref);
/* Check the user is allowed to run this flatpak. */
if (!check_parental_controls (app_ref, app_deploy, cancellable, error))
return FALSE;
/* Construct the bwrap context. */
bwrap = flatpak_bwrap_new (NULL);
flatpak_bwrap_add_arg (bwrap, flatpak_get_bwrap ());
if (app_deploy == NULL)
{
g_assert (flatpak_decomposed_is_runtime (app_ref));
default_runtime_pref = flatpak_decomposed_dup_pref (app_ref);
}
else
{
const gchar *key;
app_deploy_data = flatpak_deploy_get_deploy_data (app_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);
if (app_deploy_data == NULL)
return FALSE;
if ((flags & FLATPAK_RUN_FLAG_DEVEL) != 0)
key = FLATPAK_METADATA_KEY_SDK;
else
key = FLATPAK_METADATA_KEY_RUNTIME;
metakey = flatpak_deploy_get_metadata (app_deploy);
default_runtime_pref = g_key_file_get_string (metakey,
FLATPAK_METADATA_GROUP_APPLICATION,
key, &my_error);
if (my_error)
{
g_propagate_error (error, g_steal_pointer (&my_error));
return FALSE;
}
}
default_runtime = flatpak_decomposed_new_from_pref (FLATPAK_KINDS_RUNTIME, default_runtime_pref, error);
if (default_runtime == NULL)
return FALSE;
if (custom_runtime != NULL || custom_runtime_version != NULL)
{
g_auto(GStrv) custom_runtime_parts = NULL;
const char *custom_runtime_id = NULL;
const char *custom_runtime_arch = NULL;
if (custom_runtime)
{
custom_runtime_parts = g_strsplit (custom_runtime, "/", 0);
for (i = 0; i < 3 && custom_runtime_parts[i] != NULL; i++)
{
if (strlen (custom_runtime_parts[i]) > 0)
{
if (i == 0)
custom_runtime_id = custom_runtime_parts[i];
if (i == 1)
custom_runtime_arch = custom_runtime_parts[i];
if (i == 2 && custom_runtime_version == NULL)
custom_runtime_version = custom_runtime_parts[i];
}
}
}
runtime_ref = flatpak_decomposed_new_from_decomposed (default_runtime,
FLATPAK_KINDS_RUNTIME,
custom_runtime_id,
custom_runtime_arch,
custom_runtime_version,
error);
if (runtime_ref == NULL)
return FALSE;
}
else
runtime_ref = flatpak_decomposed_ref (default_runtime);
runtime_deploy = flatpak_find_deploy_for_ref (flatpak_decomposed_get_ref (runtime_ref), custom_runtime_commit, NULL, cancellable, error);
if (runtime_deploy == NULL)
return FALSE;
runtime_deploy_data = flatpak_deploy_get_deploy_data (runtime_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);
if (runtime_deploy_data == NULL)
return FALSE;
runtime_metakey = flatpak_deploy_get_metadata (runtime_deploy);
app_context = flatpak_app_compute_permissions (metakey, runtime_metakey, error);
if (app_context == NULL)
return FALSE;
if (app_deploy != NULL)
{
overrides = flatpak_deploy_get_overrides (app_deploy);
flatpak_context_merge (app_context, overrides);
}
if (sandboxed)
flatpak_context_make_sandboxed (app_context);
if (extra_context)
flatpak_context_merge (app_context, extra_context);
runtime_files = flatpak_deploy_get_files (runtime_deploy);
bin_ldconfig = g_file_resolve_relative_path (runtime_files, "bin/ldconfig");
if (!g_file_query_exists (bin_ldconfig, NULL))
use_ld_so_cache = FALSE;
if (app_deploy != NULL)
{
g_autofree const char **previous_ids = NULL;
gsize len = 0;
gboolean do_migrate;
real_app_id_dir = flatpak_get_data_dir (app_id);
app_files = flatpak_deploy_get_files (app_deploy);
previous_app_id_dirs = g_ptr_array_new_with_free_func (g_object_unref);
previous_ids = flatpak_deploy_data_get_previous_ids (app_deploy_data, &len);
do_migrate = !g_file_query_exists (real_app_id_dir, cancellable);
/* When migrating, find most recent old existing source and rename that to
* the new name.
*
* We ignore other names than that. For more recent names that don't exist
* we never ran them so nothing will even reference them. For older names
* either they were not used, or they were used but then the more recent
* name was used and a symlink to it was created.
*
* This means we may end up with a chain of symlinks: oldest -> old -> current.
* This is unfortunate but not really a problem, but for robustness reasons we
* don't want to mess with user files unnecessary. For example, the app dir could
* actually be a symlink for other reasons. Imagine for instance that you want to put the
* steam games somewhere else so you leave the app dir as a symlink to /mnt/steam.
*/
for (i = len - 1; i >= 0; i--)
{
g_autoptr(GFile) previous_app_id_dir = NULL;
g_autoptr(GFileInfo) previous_app_id_dir_info = NULL;
g_autoptr(GError) local_error = NULL;
previous_app_id_dir = flatpak_get_data_dir (previous_ids[i]);
previous_app_id_dir_info = g_file_query_info (previous_app_id_dir,
G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK ","
G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
cancellable,
&local_error);
/* Warn about the migration failures, but don't make them fatal, then you can never run the app */
if (previous_app_id_dir_info == NULL)
{
if (!g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND) && do_migrate)
{
g_warning (_("Failed to migrate from %s: %s"), flatpak_file_get_path_cached (previous_app_id_dir),
local_error->message);
do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to the thing that we failed on */
}
g_clear_error (&local_error);
continue;
}
if (do_migrate)
{
do_migrate = FALSE; /* Don't migrate older things, they are likely symlinks to this dir */
if (!flatpak_file_rename (previous_app_id_dir, real_app_id_dir, cancellable, &local_error))
{
g_warning (_("Failed to migrate old app data directory %s to new name %s: %s"),
flatpak_file_get_path_cached (previous_app_id_dir), app_id,
local_error->message);
}
else
{
/* Leave a symlink in place of the old data dir */
if (!g_file_make_symbolic_link (previous_app_id_dir, app_id, cancellable, &local_error))
{
g_warning (_("Failed to create symlink while migrating %s: %s"),
flatpak_file_get_path_cached (previous_app_id_dir),
local_error->message);
}
}
}
/* Give app access to this old dir */
g_ptr_array_add (previous_app_id_dirs, g_steal_pointer (&previous_app_id_dir));
}
if (!flatpak_ensure_data_dir (real_app_id_dir, cancellable, error))
return FALSE;
if (!sandboxed)
app_id_dir = g_object_ref (real_app_id_dir);
}
flatpak_run_apply_env_default (bwrap, use_ld_so_cache);
flatpak_run_apply_env_vars (bwrap, app_context);
flatpak_run_apply_env_prompt (bwrap, app_id);
if (real_app_id_dir)
{
g_autoptr(GFile) sandbox_dir = g_file_get_child (real_app_id_dir, "sandbox");
flatpak_bwrap_set_env (bwrap, "FLATPAK_SANDBOX_DIR", flatpak_file_get_path_cached (sandbox_dir), TRUE);
}
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (runtime_files), "/usr",
"--lock-file", "/usr/.ref",
NULL);
if (app_files != NULL)
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (app_files), "/app",
"--lock-file", "/app/.ref",
NULL);
else
flatpak_bwrap_add_args (bwrap,
"--dir", "/app",
NULL);
if (metakey != NULL &&
!flatpak_run_add_extension_args (bwrap, metakey, app_ref, use_ld_so_cache, &app_extensions, cancellable, error))
return FALSE;
if (!flatpak_run_add_extension_args (bwrap, runtime_metakey, runtime_ref, use_ld_so_cache, &runtime_extensions, cancellable, error))
return FALSE;
runtime_ld_so_conf = g_file_resolve_relative_path (runtime_files, "etc/ld.so.conf");
if (lstat (flatpak_file_get_path_cached (runtime_ld_so_conf), &s) == 0)
generate_ld_so_conf = S_ISREG (s.st_mode) && s.st_size == 0;
/* At this point we have the minimal argv set up, with just the app, runtime and extensions.
We can reuse this to generate the ld.so.cache (if needed) */
if (use_ld_so_cache)
{
checksum = calculate_ld_cache_checksum (app_deploy_data, runtime_deploy_data,
app_extensions, runtime_extensions);
ld_so_fd = regenerate_ld_cache (bwrap->argv,
bwrap->fds,
app_id_dir,
checksum,
runtime_files,
generate_ld_so_conf,
cancellable, error);
if (ld_so_fd == -1)
return FALSE;
flatpak_bwrap_add_fd (bwrap, ld_so_fd);
}
flags |= flatpak_context_get_run_flags (app_context);
if (!flatpak_run_setup_base_argv (bwrap, runtime_files, app_id_dir, app_arch, flags, error))
return FALSE;
if (generate_ld_so_conf)
{
if (!add_ld_so_conf (bwrap, error))
return FALSE;
}
if (ld_so_fd != -1)
{
/* Don't add to fd_array, its already there */
flatpak_bwrap_add_arg (bwrap, "--ro-bind-data");
flatpak_bwrap_add_arg_printf (bwrap, "%d", ld_so_fd);
flatpak_bwrap_add_arg (bwrap, "/etc/ld.so.cache");
}
if (!flatpak_run_add_app_info_args (bwrap,
app_files, app_deploy_data, app_extensions,
runtime_files, runtime_deploy_data, runtime_extensions,
app_id, flatpak_decomposed_get_branch (app_ref),
runtime_ref, app_id_dir, app_context, extra_context,
sandboxed, FALSE, flags & FLATPAK_RUN_FLAG_DEVEL,
&app_info_path, instance_id_fd, &instance_id_host_dir,
error))
return FALSE;
if (!flatpak_run_add_dconf_args (bwrap, app_id, metakey, error))
return FALSE;
if (!sandboxed && !(flags & FLATPAK_RUN_FLAG_NO_DOCUMENTS_PORTAL))
add_document_portal_args (bwrap, app_id, &doc_mount_path);
if (!flatpak_run_add_environment_args (bwrap, app_info_path, flags,
app_id, app_context, app_id_dir, previous_app_id_dirs,
&exports, cancellable, error))
return FALSE;
if ((app_context->shares & FLATPAK_CONTEXT_SHARED_NETWORK) != 0)
flatpak_run_add_resolved_args (bwrap);
flatpak_run_add_journal_args (bwrap);
add_font_path_args (bwrap);
add_icon_path_args (bwrap);
flatpak_bwrap_add_args (bwrap,
/* Not in base, because we don't want this for flatpak build */
"--symlink", "/app/lib/debug/source", "/run/build",
"--symlink", "/usr/lib/debug/source", "/run/build-runtime",
NULL);
if (cwd)
flatpak_bwrap_add_args (bwrap, "--chdir", cwd, NULL);
if (parent_expose_pids || parent_share_pids)
{
g_autofree char *userns_path = NULL;
g_autofree char *pidns_path = NULL;
g_autofree char *userns2_path = NULL;
int userns_fd, userns2_fd, pidns_fd;
if (parent_pid == 0)
return flatpak_fail (error, "No parent pid specified");
userns_path = g_strdup_printf ("/proc/%d/root/run/.userns", parent_pid);
userns_fd = open_namespace_fd_if_needed (userns_path, "/proc/self/ns/user");
if (userns_fd != -1)
{
flatpak_bwrap_add_args_data_fd (bwrap, "--userns", userns_fd, NULL);
userns2_path = g_strdup_printf ("/proc/%d/ns/user", parent_pid);
userns2_fd = open_namespace_fd_if_needed (userns2_path, userns_path);
if (userns2_fd != -1)
flatpak_bwrap_add_args_data_fd (bwrap, "--userns2", userns2_fd, NULL);
}
pidns_path = g_strdup_printf ("/proc/%d/ns/pid", parent_pid);
pidns_fd = open (pidns_path, O_RDONLY|O_CLOEXEC);
if (pidns_fd != -1)
flatpak_bwrap_add_args_data_fd (bwrap, "--pidns", pidns_fd, NULL);
}
if (custom_command)
{
command = custom_command;
}
else if (metakey)
{
default_command = g_key_file_get_string (metakey,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_COMMAND,
&my_error);
if (my_error)
{
g_propagate_error (error, g_steal_pointer (&my_error));
return FALSE;
}
command = default_command;
}
flatpak_bwrap_envp_to_args (bwrap);
if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))
return FALSE;
flatpak_bwrap_add_arg (bwrap, command);
if (!add_rest_args (bwrap, app_id,
exports, (flags & FLATPAK_RUN_FLAG_FILE_FORWARDING) != 0,
doc_mount_path,
args, n_args, error))
return FALSE;
flatpak_bwrap_finish (bwrap);
commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata, -1);
g_debug ("Running '%s'", commandline);
if ((flags & FLATPAK_RUN_FLAG_BACKGROUND) != 0)
{
GPid child_pid;
char pid_str[64];
g_autofree char *pid_path = NULL;
GSpawnFlags spawn_flags;
spawn_flags = G_SPAWN_SEARCH_PATH;
if (flags & FLATPAK_RUN_FLAG_DO_NOT_REAP)
spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
/* flatpak_bwrap_envp_to_args() moved the environment variables to
* be set into --setenv instructions in argv, so the environment
* in which the bwrap command runs must be empty. */
g_assert (bwrap->envp != NULL);
g_assert (bwrap->envp[0] == NULL);
if (!g_spawn_async (NULL,
(char **) bwrap->argv->pdata,
bwrap->envp,
spawn_flags,
flatpak_bwrap_child_setup_cb, bwrap->fds,
&child_pid,
error))
return FALSE;
g_snprintf (pid_str, sizeof (pid_str), "%d", child_pid);
pid_path = g_build_filename (instance_id_host_dir, "pid", NULL);
g_file_set_contents (pid_path, pid_str, -1, NULL);
}
else
{
char pid_str[64];
g_autofree char *pid_path = NULL;
g_snprintf (pid_str, sizeof (pid_str), "%d", getpid ());
pid_path = g_build_filename (instance_id_host_dir, "pid", NULL);
g_file_set_contents (pid_path, pid_str, -1, NULL);
/* Ensure we unset O_CLOEXEC for marked fds and rewind fds as needed.
* Note that this does not close fds that are not already marked O_CLOEXEC, because
* we do want to allow inheriting fds into flatpak run. */
flatpak_bwrap_child_setup (bwrap->fds, FALSE);
/* flatpak_bwrap_envp_to_args() moved the environment variables to
* be set into --setenv instructions in argv, so the environment
* in which the bwrap command runs must be empty. */
g_assert (bwrap->envp != NULL);
g_assert (bwrap->envp[0] == NULL);
if (execvpe (flatpak_get_bwrap (), (char **) bwrap->argv->pdata, bwrap->envp) == -1)
{
g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),
_("Unable to start app"));
return FALSE;
}
/* Not actually reached... */
}
if (instance_dir_out)
*instance_dir_out = g_steal_pointer (&instance_id_host_dir);
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1906_2 |
crossvul-cpp_data_bad_1906_1 | /*
* Copyright © 2014-2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/personality.h>
#include <grp.h>
#include <unistd.h>
#include <gio/gunixfdlist.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include "libglnx/libglnx.h"
#include "flatpak-bwrap-private.h"
#include "flatpak-utils-private.h"
#include "flatpak-utils-base-private.h"
static void
clear_fd (gpointer data)
{
int *fd_p = data;
if (fd_p != NULL && *fd_p != -1)
close (*fd_p);
}
char *flatpak_bwrap_empty_env[] = { NULL };
FlatpakBwrap *
flatpak_bwrap_new (char **env)
{
FlatpakBwrap *bwrap = g_new0 (FlatpakBwrap, 1);
bwrap->argv = g_ptr_array_new_with_free_func (g_free);
bwrap->noinherit_fds = g_array_new (FALSE, TRUE, sizeof (int));
g_array_set_clear_func (bwrap->noinherit_fds, clear_fd);
bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));
g_array_set_clear_func (bwrap->fds, clear_fd);
if (env)
bwrap->envp = g_strdupv (env);
else
bwrap->envp = g_get_environ ();
return bwrap;
}
void
flatpak_bwrap_free (FlatpakBwrap *bwrap)
{
g_ptr_array_unref (bwrap->argv);
g_array_unref (bwrap->noinherit_fds);
g_array_unref (bwrap->fds);
g_strfreev (bwrap->envp);
g_free (bwrap);
}
gboolean
flatpak_bwrap_is_empty (FlatpakBwrap *bwrap)
{
return bwrap->argv->len == 0;
}
void
flatpak_bwrap_set_env (FlatpakBwrap *bwrap,
const char *variable,
const char *value,
gboolean overwrite)
{
bwrap->envp = g_environ_setenv (bwrap->envp, variable, value, overwrite);
}
void
flatpak_bwrap_unset_env (FlatpakBwrap *bwrap,
const char *variable)
{
bwrap->envp = g_environ_unsetenv (bwrap->envp, variable);
}
void
flatpak_bwrap_add_arg (FlatpakBwrap *bwrap, const char *arg)
{
g_ptr_array_add (bwrap->argv, g_strdup (arg));
}
void
flatpak_bwrap_finish (FlatpakBwrap *bwrap)
{
g_ptr_array_add (bwrap->argv, NULL);
}
void
flatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,
int fd)
{
g_array_append_val (bwrap->noinherit_fds, fd);
}
void
flatpak_bwrap_add_fd (FlatpakBwrap *bwrap,
int fd)
{
g_array_append_val (bwrap->fds, fd);
}
void
flatpak_bwrap_add_arg_printf (FlatpakBwrap *bwrap, const char *format, ...)
{
va_list args;
va_start (args, format);
g_ptr_array_add (bwrap->argv, g_strdup_vprintf (format, args));
va_end (args);
}
void
flatpak_bwrap_add_args (FlatpakBwrap *bwrap, ...)
{
va_list args;
const gchar *arg;
va_start (args, bwrap);
while ((arg = va_arg (args, const gchar *)))
flatpak_bwrap_add_arg (bwrap, arg);
va_end (args);
}
void
flatpak_bwrap_append_argsv (FlatpakBwrap *bwrap,
char **args,
int len)
{
int i;
if (len < 0)
len = g_strv_length (args);
for (i = 0; i < len; i++)
g_ptr_array_add (bwrap->argv, g_strdup (args[i]));
}
void
flatpak_bwrap_append_args (FlatpakBwrap *bwrap,
GPtrArray *other_array)
{
flatpak_bwrap_append_argsv (bwrap,
(char **) other_array->pdata,
other_array->len);
}
static int *
flatpak_bwrap_steal_fds (FlatpakBwrap *bwrap,
gsize *len_out)
{
gsize len = bwrap->fds->len;
int *res = (int *) g_array_free (bwrap->fds, FALSE);
bwrap->fds = g_array_new (FALSE, TRUE, sizeof (int));
*len_out = len;
return res;
}
void
flatpak_bwrap_append_bwrap (FlatpakBwrap *bwrap,
FlatpakBwrap *other)
{
g_autofree int *fds = NULL;
gsize n_fds, i;
fds = flatpak_bwrap_steal_fds (other, &n_fds);
for (i = 0; i < n_fds; i++)
flatpak_bwrap_add_fd (bwrap, fds[i]);
flatpak_bwrap_append_argsv (bwrap,
(char **) other->argv->pdata,
other->argv->len);
for (i = 0; other->envp[i] != NULL; i++)
{
char *key_val = other->envp[i];
char *eq = strchr (key_val, '=');
if (eq)
{
g_autofree char *key = g_strndup (key_val, eq - key_val);
flatpak_bwrap_set_env (bwrap,
key, eq + 1, TRUE);
}
}
}
void
flatpak_bwrap_add_args_data_fd (FlatpakBwrap *bwrap,
const char *op,
int fd,
const char *path_optional)
{
g_autofree char *fd_str = g_strdup_printf ("%d", fd);
flatpak_bwrap_add_fd (bwrap, fd);
flatpak_bwrap_add_args (bwrap,
op, fd_str, path_optional,
NULL);
}
/* Given a buffer @content of size @content_size, generate a fd (memfd if available)
* of the data. The @name parameter is used by memfd_create() as a debugging aid;
* it has no semantic meaning. The bwrap command line will inject it into the target
* container as @path.
*/
gboolean
flatpak_bwrap_add_args_data (FlatpakBwrap *bwrap,
const char *name,
const char *content,
gssize content_size,
const char *path,
GError **error)
{
g_auto(GLnxTmpfile) args_tmpf = { 0, };
if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, name, content, content_size, error))
return FALSE;
flatpak_bwrap_add_args_data_fd (bwrap, "--ro-bind-data", glnx_steal_fd (&args_tmpf.fd), path);
return TRUE;
}
/* This resolves the target here rather than in bwrap, because it may
* not resolve in bwrap setup due to absolute symlinks conflicting
* with /newroot root. For example, dest could be inside
* ~/.var/app/XXX where XXX is an absolute symlink. However, in the
* usecases here the destination file often doesn't exist, so we
* only resolve the directory part.
*/
void
flatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,
const char *type,
const char *src,
const char *dest)
{
g_autofree char *dest_dirname = g_path_get_dirname (dest);
g_autofree char *dest_dirname_real = realpath (dest_dirname, NULL);
if (dest_dirname_real)
{
g_autofree char *dest_basename = g_path_get_basename (dest);
g_autofree char *dest_real = g_build_filename (dest_dirname_real, dest_basename, NULL);
flatpak_bwrap_add_args (bwrap, type, src, dest_real, NULL);
}
}
gboolean
flatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,
int start,
int end,
gboolean one_arg,
GError **error)
{
g_autofree gchar *data = NULL;
gchar *ptr;
gint i;
gsize data_len = 0;
int fd;
g_auto(GLnxTmpfile) args_tmpf = { 0, };
if (end == -1)
end = bwrap->argv->len;
for (i = start; i < end; i++)
data_len += strlen (bwrap->argv->pdata[i]) + 1;
data = g_new (gchar, data_len);
ptr = data;
for (i = start; i < end; i++)
ptr = g_stpcpy (ptr, bwrap->argv->pdata[i]) + 1;
if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&args_tmpf, "bwrap-args", data, data_len, error))
return FALSE;
fd = glnx_steal_fd (&args_tmpf.fd);
{
g_autofree char *commandline = flatpak_quote_argv ((const char **) bwrap->argv->pdata + start, end - start);
flatpak_debug2 ("bwrap --args %d = %s", fd, commandline);
}
flatpak_bwrap_add_fd (bwrap, fd);
g_ptr_array_remove_range (bwrap->argv, start, end - start);
if (one_arg)
{
g_ptr_array_insert (bwrap->argv, start, g_strdup_printf ("--args=%d", fd));
}
else
{
g_ptr_array_insert (bwrap->argv, start, g_strdup ("--args"));
g_ptr_array_insert (bwrap->argv, start + 1, g_strdup_printf ("%d", fd));
}
return TRUE;
}
void
flatpak_bwrap_child_setup (GArray *fd_array,
gboolean close_fd_workaround)
{
int i;
if (close_fd_workaround)
flatpak_close_fds_workaround (3);
/* If no fd_array was specified, don't care. */
if (fd_array == NULL)
return;
/* Otherwise, mark not - close-on-exec all the fds in the array */
for (i = 0; i < fd_array->len; i++)
{
int fd = g_array_index (fd_array, int, i);
/* We also seek all fds to the start, because this lets
us use the same fd_array multiple times */
if (lseek (fd, 0, SEEK_SET) < 0)
{
/* Ignore the error, this happens on e.g. pipe fds */
}
fcntl (fd, F_SETFD, 0);
}
}
/* Unset FD_CLOEXEC on the array of fds passed in @user_data */
void
flatpak_bwrap_child_setup_cb (gpointer user_data)
{
GArray *fd_array = user_data;
flatpak_bwrap_child_setup (fd_array, TRUE);
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1906_1 |
crossvul-cpp_data_bad_4069_2 | /**
* @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 (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "private.h"
#include "mutt/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "globals.h"
#include "init.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_logging.h"
#include "mutt_menu.h"
#include "mutt_socket.h"
#include "mx.h"
/* These Config Variables are only used in imap/command.c */
bool C_ImapServernoise; ///< Config: (imap) Display server warnings as error messages
#define IMAP_CMD_BUFSIZE 512
/**
* Capabilities - Server capabilities strings that we understand
*
* @note This must be kept in the same order as ImapCaps.
*/
static const char *const Capabilities[] = {
"IMAP4",
"IMAP4rev1",
"STATUS",
"ACL",
"NAMESPACE",
"AUTH=CRAM-MD5",
"AUTH=GSSAPI",
"AUTH=ANONYMOUS",
"AUTH=OAUTHBEARER",
"STARTTLS",
"LOGINDISABLED",
"IDLE",
"SASL-IR",
"ENABLE",
"CONDSTORE",
"QRESYNC",
"LIST-EXTENDED",
"COMPRESS=DEFLATE",
"X-GM-EXT-1",
NULL,
};
/**
* cmd_queue_full - Is the IMAP command queue full?
* @param adata Imap Account data
* @retval true Queue is full
*/
static bool cmd_queue_full(struct ImapAccountData *adata)
{
if (((adata->nextcmd + 1) % adata->cmdslots) == adata->lastcmd)
return true;
return false;
}
/**
* cmd_new - Create and queue a new command control block
* @param adata Imap Account data
* @retval NULL if the pipeline is full
* @retval ptr New command
*/
static struct ImapCommand *cmd_new(struct ImapAccountData *adata)
{
struct ImapCommand *cmd = NULL;
if (cmd_queue_full(adata))
{
mutt_debug(LL_DEBUG3, "IMAP command queue full\n");
return NULL;
}
cmd = adata->cmds + adata->nextcmd;
adata->nextcmd = (adata->nextcmd + 1) % adata->cmdslots;
snprintf(cmd->seq, sizeof(cmd->seq), "%c%04u", adata->seqid, adata->seqno++);
if (adata->seqno > 9999)
adata->seqno = 0;
cmd->state = IMAP_RES_NEW;
return cmd;
}
/**
* cmd_queue - Add a IMAP command to the queue
* @param adata Imap Account data
* @param cmdstr Command string
* @param flags Server flags, see #ImapCmdFlags
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*
* If the queue is full, attempts to drain it.
*/
static int cmd_queue(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)
{
if (cmd_queue_full(adata))
{
mutt_debug(LL_DEBUG3, "Draining IMAP command pipeline\n");
const int rc = imap_exec(adata, NULL, flags & IMAP_CMD_POLL);
if (rc == IMAP_EXEC_ERROR)
return IMAP_RES_BAD;
}
struct ImapCommand *cmd = cmd_new(adata);
if (!cmd)
return IMAP_RES_BAD;
if (mutt_buffer_add_printf(&adata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0)
return IMAP_RES_BAD;
return 0;
}
/**
* cmd_handle_fatal - When ImapAccountData is in fatal state, do what we can
* @param adata Imap Account data
*/
static void cmd_handle_fatal(struct ImapAccountData *adata)
{
adata->status = IMAP_FATAL;
if (!adata->mailbox)
return;
struct ImapMboxData *mdata = adata->mailbox->mdata;
if ((adata->state >= IMAP_SELECTED) && (mdata->reopen & IMAP_REOPEN_ALLOW))
{
mx_fastclose_mailbox(adata->mailbox);
mutt_socket_close(adata->conn);
mutt_error(_("Mailbox %s@%s closed"), adata->conn->account.user,
adata->conn->account.host);
adata->state = IMAP_DISCONNECTED;
}
imap_close_connection(adata);
if (!adata->recovering)
{
adata->recovering = true;
if (imap_login(adata))
mutt_clear_error();
adata->recovering = false;
}
}
/**
* cmd_start - Start a new IMAP command
* @param adata Imap Account data
* @param cmdstr Command string
* @param flags Command flags, see #ImapCmdFlags
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*/
static int cmd_start(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)
{
int rc;
if (adata->status == IMAP_FATAL)
{
cmd_handle_fatal(adata);
return -1;
}
if (cmdstr && ((rc = cmd_queue(adata, cmdstr, flags)) < 0))
return rc;
if (flags & IMAP_CMD_QUEUE)
return 0;
if (mutt_buffer_is_empty(&adata->cmdbuf))
return IMAP_RES_BAD;
rc = mutt_socket_send_d(adata->conn, adata->cmdbuf.data,
(flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD);
mutt_buffer_reset(&adata->cmdbuf);
/* unidle when command queue is flushed */
if (adata->state == IMAP_IDLE)
adata->state = IMAP_SELECTED;
return (rc < 0) ? IMAP_RES_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_RES_BAD
*/
static int cmd_status(const char *s)
{
s = imap_next_word((char *) s);
if (mutt_str_startswith(s, "OK", CASE_IGNORE))
return IMAP_RES_OK;
if (mutt_str_startswith(s, "NO", CASE_IGNORE))
return IMAP_RES_NO;
return IMAP_RES_BAD;
}
/**
* cmd_parse_expunge - Parse expunge command
* @param adata Imap Account data
* @param s String containing MSN of message to expunge
*
* cmd_parse_expunge: mark headers with new sequence ID and mark adata to be
* reopened at our earliest convenience
*/
static void cmd_parse_expunge(struct ImapAccountData *adata, const char *s)
{
unsigned int exp_msn;
struct Email *e = NULL;
mutt_debug(LL_DEBUG2, "Handling EXPUNGE\n");
struct ImapMboxData *mdata = adata->mailbox->mdata;
if ((mutt_str_atoui(s, &exp_msn) < 0) || (exp_msn < 1) || (exp_msn > mdata->max_msn))
return;
e = mdata->msn_index[exp_msn - 1];
if (e)
{
/* imap_expunge_mailbox() will rewrite e->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
e->index = INT_MAX;
imap_edata_get(e)->msn = 0;
}
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < mdata->max_msn; cur++)
{
e = mdata->msn_index[cur];
if (e)
imap_edata_get(e)->msn--;
mdata->msn_index[cur - 1] = e;
}
mdata->msn_index[mdata->max_msn - 1] = NULL;
mdata->max_msn--;
mdata->reopen |= IMAP_EXPUNGE_PENDING;
}
/**
* cmd_parse_vanished - Parse vanished command
* @param adata Imap Account data
* @param s String containing MSN of message to expunge
*
* Handle VANISHED (RFC7162), which is like expunge, but passes a seqset of UIDs.
* An optional (EARLIER) argument specifies not to decrement subsequent MSNs.
*/
static void cmd_parse_vanished(struct ImapAccountData *adata, char *s)
{
bool earlier = false;
int rc;
unsigned int uid = 0;
struct ImapMboxData *mdata = adata->mailbox->mdata;
mutt_debug(LL_DEBUG2, "Handling VANISHED\n");
if (mutt_str_startswith(s, "(EARLIER)", CASE_IGNORE))
{
/* The RFC says we should not decrement msns with the VANISHED EARLIER tag.
* My experimentation says that's crap. */
earlier = true;
s = imap_next_word(s);
}
char *end_of_seqset = s;
while (*end_of_seqset)
{
if (!strchr("0123456789:,", *end_of_seqset))
*end_of_seqset = '\0';
else
end_of_seqset++;
}
struct SeqsetIterator *iter = mutt_seqset_iterator_new(s);
if (!iter)
{
mutt_debug(LL_DEBUG2, "VANISHED: empty seqset [%s]?\n", s);
return;
}
while ((rc = mutt_seqset_iterator_next(iter, &uid)) == 0)
{
struct Email *e = mutt_hash_int_find(mdata->uid_hash, uid);
if (!e)
continue;
unsigned int exp_msn = imap_edata_get(e)->msn;
/* imap_expunge_mailbox() will rewrite e->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
e->index = INT_MAX;
imap_edata_get(e)->msn = 0;
if ((exp_msn < 1) || (exp_msn > mdata->max_msn))
{
mutt_debug(LL_DEBUG1, "VANISHED: msn for UID %u is incorrect\n", uid);
continue;
}
if (mdata->msn_index[exp_msn - 1] != e)
{
mutt_debug(LL_DEBUG1, "VANISHED: msn_index for UID %u is incorrect\n", uid);
continue;
}
mdata->msn_index[exp_msn - 1] = NULL;
if (!earlier)
{
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < mdata->max_msn; cur++)
{
e = mdata->msn_index[cur];
if (e)
imap_edata_get(e)->msn--;
mdata->msn_index[cur - 1] = e;
}
mdata->msn_index[mdata->max_msn - 1] = NULL;
mdata->max_msn--;
}
}
if (rc < 0)
mutt_debug(LL_DEBUG1, "VANISHED: illegal seqset %s\n", s);
mdata->reopen |= IMAP_EXPUNGE_PENDING;
mutt_seqset_iterator_free(&iter);
}
/**
* cmd_parse_fetch - Load fetch response into ImapAccountData
* @param adata Imap Account 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 ImapAccountData *adata, char *s)
{
unsigned int msn, uid;
struct Email *e = NULL;
char *flags = NULL;
int uid_checked = 0;
bool server_changes = false;
struct ImapMboxData *mdata = imap_mdata_get(adata->mailbox);
mutt_debug(LL_DEBUG3, "Handling FETCH\n");
if (mutt_str_atoui(s, &msn) < 0)
{
mutt_debug(LL_DEBUG3, "Skipping FETCH response - illegal MSN\n");
return;
}
if ((msn < 1) || (msn > mdata->max_msn))
{
mutt_debug(LL_DEBUG3, "Skipping FETCH response - MSN %u out of range\n", msn);
return;
}
e = mdata->msn_index[msn - 1];
if (!e || !e->active)
{
mutt_debug(LL_DEBUG3, "Skipping FETCH response - MSN %u not in msn_index\n", msn);
return;
}
mutt_debug(LL_DEBUG2, "Message UID %u updated\n", imap_edata_get(e)->uid);
/* skip FETCH */
s = imap_next_word(s);
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "Malformed FETCH response\n");
return;
}
s++;
while (*s)
{
SKIPWS(s);
size_t plen = mutt_str_startswith(s, "FLAGS", CASE_IGNORE);
if (plen != 0)
{
flags = s;
if (uid_checked)
break;
s += plen;
SKIPWS(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "bogus FLAGS response: %s\n", s);
return;
}
s++;
while (*s && (*s != ')'))
s++;
if (*s == ')')
s++;
else
{
mutt_debug(LL_DEBUG1, "Unterminated FLAGS response: %s\n", s);
return;
}
}
else if ((plen = mutt_str_startswith(s, "UID", CASE_IGNORE)))
{
s += plen;
SKIPWS(s);
if (mutt_str_atoui(s, &uid) < 0)
{
mutt_debug(LL_DEBUG1, "Illegal UID. Skipping update\n");
return;
}
if (uid != imap_edata_get(e)->uid)
{
mutt_debug(LL_DEBUG1, "UID vs MSN mismatch. Skipping update\n");
return;
}
uid_checked = 1;
if (flags)
break;
s = imap_next_word(s);
}
else if ((plen = mutt_str_startswith(s, "MODSEQ", CASE_IGNORE)))
{
s += plen;
SKIPWS(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "bogus MODSEQ response: %s\n", s);
return;
}
s++;
while (*s && (*s != ')'))
s++;
if (*s == ')')
s++;
else
{
mutt_debug(LL_DEBUG1, "Unterminated MODSEQ response: %s\n", s);
return;
}
}
else if (*s == ')')
break; /* end of request */
else if (*s)
{
mutt_debug(LL_DEBUG2, "Only handle FLAGS updates\n");
break;
}
}
if (flags)
{
imap_set_flags(adata->mailbox, e, flags, &server_changes);
if (server_changes)
{
/* If server flags could conflict with NeoMutt's flags, reopen the mailbox. */
if (e->changed)
mdata->reopen |= IMAP_EXPUNGE_PENDING;
else
mdata->check_status |= IMAP_FLAGS_PENDING;
}
}
}
/**
* cmd_parse_capability - set capability bits according to CAPABILITY response
* @param adata Imap Account data
* @param s Command string with capabilities
*/
static void cmd_parse_capability(struct ImapAccountData *adata, char *s)
{
mutt_debug(LL_DEBUG3, "Handling CAPABILITY\n");
s = imap_next_word(s);
char *bracket = strchr(s, ']');
if (bracket)
*bracket = '\0';
FREE(&adata->capstr);
adata->capstr = mutt_str_strdup(s);
adata->capabilities = 0;
while (*s)
{
for (size_t i = 0; Capabilities[i]; i++)
{
if (mutt_str_word_casecmp(Capabilities[i], s) == 0)
{
adata->capabilities |= (1 << i);
mutt_debug(LL_DEBUG3, " Found capability \"%s\": %lu\n", Capabilities[i], i);
break;
}
}
s = imap_next_word(s);
}
}
/**
* cmd_parse_list - Parse a server LIST command (list mailboxes)
* @param adata Imap Account data
* @param s Command string with folder list
*/
static void cmd_parse_list(struct ImapAccountData *adata, char *s)
{
struct ImapList *list = NULL;
struct ImapList lb = { 0 };
char delimbuf[5]; /* worst case: "\\"\0 */
unsigned int litlen;
if (adata->cmdresult)
list = adata->cmdresult;
else
list = &lb;
memset(list, 0, sizeof(struct ImapList));
/* flags */
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "Bad LIST response\n");
return;
}
s++;
while (*s)
{
if (mutt_str_startswith(s, "\\NoSelect", CASE_IGNORE))
list->noselect = true;
else if (mutt_str_startswith(s, "\\NonExistent", CASE_IGNORE)) /* rfc5258 */
list->noselect = true;
else if (mutt_str_startswith(s, "\\NoInferiors", CASE_IGNORE))
list->noinferiors = true;
else if (mutt_str_startswith(s, "\\HasNoChildren", CASE_IGNORE)) /* rfc5258*/
list->noinferiors = true;
s = imap_next_word(s);
if (*(s - 2) == ')')
break;
}
/* Delimiter */
if (!mutt_str_startswith(s, "NIL", CASE_IGNORE))
{
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(adata) != IMAP_RES_CONTINUE)
{
adata->status = IMAP_FATAL;
return;
}
if (strlen(adata->buf) < litlen)
{
mutt_debug(LL_DEBUG1, "Error parsing LIST mailbox\n");
return;
}
list->name = adata->buf;
s = list->name + litlen;
if (s[0] != '\0')
{
s[0] = '\0';
s++;
SKIPWS(s);
}
}
else
{
list->name = s;
/* Exclude rfc5258 RECURSIVEMATCH CHILDINFO suffix */
s = imap_next_word(s);
if (s[0] != '\0')
s[-1] = '\0';
imap_unmunge_mbox_name(adata->unicode, list->name);
}
if (list->name[0] == '\0')
{
adata->delim = list->delim;
mutt_debug(LL_DEBUG3, "Root delimiter: %c\n", adata->delim);
}
}
/**
* cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes)
* @param adata Imap Account data
* @param s Command string with folder list
*/
static void cmd_parse_lsub(struct ImapAccountData *adata, char *s)
{
char buf[256];
char quoted_name[256];
struct Buffer err;
struct Url url = { 0 };
struct ImapList list = { 0 };
if (adata->cmdresult)
{
/* caller will handle response itself */
cmd_parse_list(adata, s);
return;
}
if (!C_ImapCheckSubscribed)
return;
adata->cmdresult = &list;
cmd_parse_list(adata, s);
adata->cmdresult = NULL;
/* noselect is for a gmail quirk */
if (!list.name || list.noselect)
return;
mutt_debug(LL_DEBUG3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&adata->conn->account, &url);
/* escape \ and " */
imap_quote_string(quoted_name, sizeof(quoted_name), list.name, true);
url.path = quoted_name + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, C_ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&err);
err.dsize = 256;
err.data = mutt_mem_malloc(err.dsize);
if (mutt_parse_rc_line(buf, &err))
mutt_debug(LL_DEBUG1, "Error adding subscribed mailbox: %s\n", err.data);
FREE(&err.data);
}
/**
* cmd_parse_myrights - Set rights bits according to MYRIGHTS response
* @param adata Imap Account data
* @param s Command string with rights info
*/
static void cmd_parse_myrights(struct ImapAccountData *adata, const char *s)
{
mutt_debug(LL_DEBUG2, "Handling MYRIGHTS\n");
s = imap_next_word((char *) s);
s = imap_next_word((char *) s);
/* zero out current rights set */
adata->mailbox->rights = 0;
while (*s && !isspace((unsigned char) *s))
{
switch (*s)
{
case 'a':
adata->mailbox->rights |= MUTT_ACL_ADMIN;
break;
case 'e':
adata->mailbox->rights |= MUTT_ACL_EXPUNGE;
break;
case 'i':
adata->mailbox->rights |= MUTT_ACL_INSERT;
break;
case 'k':
adata->mailbox->rights |= MUTT_ACL_CREATE;
break;
case 'l':
adata->mailbox->rights |= MUTT_ACL_LOOKUP;
break;
case 'p':
adata->mailbox->rights |= MUTT_ACL_POST;
break;
case 'r':
adata->mailbox->rights |= MUTT_ACL_READ;
break;
case 's':
adata->mailbox->rights |= MUTT_ACL_SEEN;
break;
case 't':
adata->mailbox->rights |= MUTT_ACL_DELETE;
break;
case 'w':
adata->mailbox->rights |= MUTT_ACL_WRITE;
break;
case 'x':
adata->mailbox->rights |= MUTT_ACL_DELMX;
break;
/* obsolete rights */
case 'c':
adata->mailbox->rights |= MUTT_ACL_CREATE | MUTT_ACL_DELMX;
break;
case 'd':
adata->mailbox->rights |= MUTT_ACL_DELETE | MUTT_ACL_EXPUNGE;
break;
default:
mutt_debug(LL_DEBUG1, "Unknown right: %c\n", *s);
}
s++;
}
}
/**
* find_mailbox - Find a Mailbox by its name
* @param adata Imap Account data
* @param name Mailbox to find
* @retval ptr Mailbox
*/
static struct Mailbox *find_mailbox(struct ImapAccountData *adata, const char *name)
{
if (!adata || !adata->account || !name)
return NULL;
struct MailboxNode *np = NULL;
STAILQ_FOREACH(np, &adata->account->mailboxes, entries)
{
struct ImapMboxData *mdata = imap_mdata_get(np->mailbox);
if (mutt_str_strcmp(name, mdata->name) == 0)
return np->mailbox;
}
return NULL;
}
/**
* cmd_parse_status - Parse status from server
* @param adata Imap Account data
* @param s Command string with status info
*
* first cut: just do mailbox update. Later we may wish to cache all mailbox
* information, even that not desired by mailbox
*/
static void cmd_parse_status(struct ImapAccountData *adata, char *s)
{
unsigned int litlen = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(adata) != IMAP_RES_CONTINUE)
{
adata->status = IMAP_FATAL;
return;
}
if (strlen(adata->buf) < litlen)
{
mutt_debug(LL_DEBUG1, "Error parsing STATUS mailbox\n");
return;
}
mailbox = adata->buf;
s = mailbox + litlen;
s[0] = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
s[-1] = '\0';
imap_unmunge_mbox_name(adata->unicode, mailbox);
}
struct Mailbox *m = find_mailbox(adata, mailbox);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!mdata)
{
mutt_debug(LL_DEBUG3, "Received status for an unexpected mailbox: %s\n", mailbox);
return;
}
uint32_t olduv = mdata->uidvalidity;
unsigned int oldun = mdata->uid_next;
if (*s++ != '(')
{
mutt_debug(LL_DEBUG1, "Error parsing STATUS\n");
return;
}
while ((s[0] != '\0') && (s[0] != ')'))
{
char *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(LL_DEBUG1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_startswith(s, "MESSAGES", CASE_MATCH))
mdata->messages = count;
else if (mutt_str_startswith(s, "RECENT", CASE_MATCH))
mdata->recent = count;
else if (mutt_str_startswith(s, "UIDNEXT", CASE_MATCH))
mdata->uid_next = count;
else if (mutt_str_startswith(s, "UIDVALIDITY", CASE_MATCH))
mdata->uidvalidity = count;
else if (mutt_str_startswith(s, "UNSEEN", CASE_MATCH))
mdata->unseen = count;
s = value;
if ((s[0] != '\0') && (*s != ')'))
s = imap_next_word(s);
}
mutt_debug(LL_DEBUG3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
mdata->name, mdata->uidvalidity, mdata->uid_next, mdata->messages,
mdata->recent, mdata->unseen);
mutt_debug(LL_DEBUG3, "Running default STATUS handler\n");
mutt_debug(LL_DEBUG3, "Found %s in mailbox list (OV: %u ON: %u U: %d)\n",
mailbox, olduv, oldun, mdata->unseen);
bool new_mail = false;
if (C_MailCheckRecent)
{
if ((olduv != 0) && (olduv == mdata->uidvalidity))
{
if (oldun < mdata->uid_next)
new_mail = (mdata->unseen > 0);
}
else if ((olduv == 0) && (oldun == 0))
{
/* first check per session, use recent. might need a flag for this. */
new_mail = (mdata->recent > 0);
}
else
new_mail = (mdata->unseen > 0);
}
else
new_mail = (mdata->unseen > 0);
#ifdef USE_SIDEBAR
if ((m->has_new != new_mail) || (m->msg_count != mdata->messages) ||
(m->msg_unread != mdata->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
m->has_new = new_mail;
m->msg_count = mdata->messages;
m->msg_unread = mdata->unseen;
// force back to keep detecting new mail until the mailbox is opened
if (m->has_new)
mdata->uid_next = oldun;
}
/**
* cmd_parse_enabled - Record what the server has enabled
* @param adata Imap Account data
* @param s Command string containing acceptable encodings
*/
static void cmd_parse_enabled(struct ImapAccountData *adata, const char *s)
{
mutt_debug(LL_DEBUG2, "Handling ENABLED\n");
while ((s = imap_next_word((char *) s)) && (*s != '\0'))
{
if (mutt_str_startswith(s, "UTF8=ACCEPT", CASE_IGNORE) ||
mutt_str_startswith(s, "UTF8=ONLY", CASE_IGNORE))
{
adata->unicode = true;
}
if (mutt_str_startswith(s, "QRESYNC", CASE_IGNORE))
adata->qresync = true;
}
}
/**
* cmd_parse_exists - Parse EXISTS message from serer
* @param adata Imap Account data
* @param pn String containing the total number of messages for the selected mailbox
*/
static void cmd_parse_exists(struct ImapAccountData *adata, const char *pn)
{
unsigned int count = 0;
mutt_debug(LL_DEBUG2, "Handling EXISTS\n");
if (mutt_str_atoui(pn, &count) < 0)
{
mutt_debug(LL_DEBUG1, "Malformed EXISTS: '%s'\n", pn);
return;
}
struct ImapMboxData *mdata = adata->mailbox->mdata;
/* new mail arrived */
if (count < mdata->max_msn)
{
/* Notes 6.0.3 has a tendency to report fewer messages exist than
* it should. */
mutt_debug(LL_DEBUG1, "Message count is out of sync\n");
}
/* at least the InterChange server sends EXISTS messages freely,
* even when there is no new mail */
else if (count == mdata->max_msn)
mutt_debug(LL_DEBUG3, "superfluous EXISTS message\n");
else
{
mutt_debug(LL_DEBUG2, "New mail in %s - %d messages total\n", mdata->name, count);
mdata->reopen |= IMAP_NEWMAIL_PENDING;
mdata->new_mail_count = count;
}
}
/**
* cmd_handle_untagged - fallback parser for otherwise unhandled messages
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*/
static int cmd_handle_untagged(struct ImapAccountData *adata)
{
char *s = imap_next_word(adata->buf);
char *pn = imap_next_word(s);
if ((adata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s))
{
/* pn vs. s: need initial seqno */
pn = s;
s = imap_next_word(s);
/* EXISTS, EXPUNGE, FETCH are always related to the SELECTED mailbox */
if (mutt_str_startswith(s, "EXISTS", CASE_IGNORE))
cmd_parse_exists(adata, pn);
else if (mutt_str_startswith(s, "EXPUNGE", CASE_IGNORE))
cmd_parse_expunge(adata, pn);
else if (mutt_str_startswith(s, "FETCH", CASE_IGNORE))
cmd_parse_fetch(adata, pn);
}
else if ((adata->state >= IMAP_SELECTED) && mutt_str_startswith(s, "VANISHED", CASE_IGNORE))
cmd_parse_vanished(adata, pn);
else if (mutt_str_startswith(s, "CAPABILITY", CASE_IGNORE))
cmd_parse_capability(adata, s);
else if (mutt_str_startswith(s, "OK [CAPABILITY", CASE_IGNORE))
cmd_parse_capability(adata, pn);
else if (mutt_str_startswith(pn, "OK [CAPABILITY", CASE_IGNORE))
cmd_parse_capability(adata, imap_next_word(pn));
else if (mutt_str_startswith(s, "LIST", CASE_IGNORE))
cmd_parse_list(adata, s);
else if (mutt_str_startswith(s, "LSUB", CASE_IGNORE))
cmd_parse_lsub(adata, s);
else if (mutt_str_startswith(s, "MYRIGHTS", CASE_IGNORE))
cmd_parse_myrights(adata, s);
else if (mutt_str_startswith(s, "SEARCH", CASE_IGNORE))
cmd_parse_search(adata, s);
else if (mutt_str_startswith(s, "STATUS", CASE_IGNORE))
cmd_parse_status(adata, s);
else if (mutt_str_startswith(s, "ENABLED", CASE_IGNORE))
cmd_parse_enabled(adata, s);
else if (mutt_str_startswith(s, "BYE", CASE_IGNORE))
{
mutt_debug(LL_DEBUG2, "Handling BYE\n");
/* check if we're logging out */
if (adata->status == IMAP_BYE)
return 0;
/* server shut down our connection */
s += 3;
SKIPWS(s);
mutt_error("%s", s);
cmd_handle_fatal(adata);
return -1;
}
else if (C_ImapServernoise && mutt_str_startswith(s, "NO", CASE_IGNORE))
{
mutt_debug(LL_DEBUG2, "Handling untagged NO\n");
/* Display the warning message from the server */
mutt_error("%s", s + 2);
}
return 0;
}
/**
* imap_cmd_start - Given an IMAP command, send it to the server
* @param adata Imap Account data
* @param cmdstr Command string to send
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*
* If cmdstr is NULL, sends queued commands.
*/
int imap_cmd_start(struct ImapAccountData *adata, const char *cmdstr)
{
return cmd_start(adata, cmdstr, IMAP_CMD_NO_FLAGS);
}
/**
* imap_cmd_step - Reads server responses from an IMAP command
* @param adata Imap Account data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_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 ImapAccountData *adata)
{
if (!adata)
return -1;
size_t len = 0;
int c;
int rc;
int stillrunning = 0;
struct ImapCommand *cmd = NULL;
if (adata->status == IMAP_FATAL)
{
cmd_handle_fatal(adata);
return IMAP_RES_BAD;
}
/* read into buffer, expanding buffer as necessary until we have a full
* line */
do
{
if (len == adata->blen)
{
mutt_mem_realloc(&adata->buf, adata->blen + IMAP_CMD_BUFSIZE);
adata->blen = adata->blen + IMAP_CMD_BUFSIZE;
mutt_debug(LL_DEBUG3, "grew buffer to %lu bytes\n", adata->blen);
}
/* back up over '\0' */
if (len)
len--;
c = mutt_socket_readln_d(adata->buf + len, adata->blen - len, adata->conn, MUTT_SOCK_LOG_FULL);
if (c <= 0)
{
mutt_debug(LL_DEBUG1, "Error reading server response\n");
cmd_handle_fatal(adata);
return IMAP_RES_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 == adata->blen);
/* don't let one large string make cmd->buf hog memory forever */
if ((adata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE))
{
mutt_mem_realloc(&adata->buf, IMAP_CMD_BUFSIZE);
adata->blen = IMAP_CMD_BUFSIZE;
mutt_debug(LL_DEBUG3, "shrank buffer to %lu bytes\n", adata->blen);
}
adata->lastread = mutt_date_epoch();
/* handle untagged messages. The caller still gets its shot afterwards. */
if ((mutt_str_startswith(adata->buf, "* ", CASE_MATCH) ||
mutt_str_startswith(imap_next_word(adata->buf), "OK [", CASE_MATCH)) &&
cmd_handle_untagged(adata))
{
return IMAP_RES_BAD;
}
/* server demands a continuation response from us */
if (adata->buf[0] == '+')
return IMAP_RES_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 adata->cmds entry.
*
* For both these cases, we default to returning OK */
rc = IMAP_RES_OK;
c = adata->lastcmd;
do
{
cmd = &adata->cmds[c];
if (cmd->state == IMAP_RES_NEW)
{
if (mutt_str_startswith(adata->buf, cmd->seq, CASE_MATCH))
{
if (!stillrunning)
{
/* first command in queue has finished - move queue pointer up */
adata->lastcmd = (adata->lastcmd + 1) % adata->cmdslots;
}
cmd->state = cmd_status(adata->buf);
rc = cmd->state;
if (cmd->state == IMAP_RES_NO || cmd->state == IMAP_RES_BAD)
{
mutt_message(_("IMAP command failed: %s"), adata->buf);
}
}
else
stillrunning++;
}
c = (c + 1) % adata->cmdslots;
} while (c != adata->nextcmd);
if (stillrunning)
rc = IMAP_RES_CONTINUE;
else
{
mutt_debug(LL_DEBUG3, "IMAP queue drained\n");
imap_cmd_finish(adata);
}
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_RES_OK;
}
/**
* imap_cmd_trailer - Extra information after tagged command response if any
* @param adata Imap Account data
* @retval ptr Extra command information (pointer into adata->buf)
* @retval "" Error (static string)
*/
const char *imap_cmd_trailer(struct ImapAccountData *adata)
{
static const char *notrailer = "";
const char *s = adata->buf;
if (!s)
{
mutt_debug(LL_DEBUG2, "not a tagged response\n");
return notrailer;
}
s = imap_next_word((char *) s);
if (!s || (!mutt_str_startswith(s, "OK", CASE_IGNORE) &&
!mutt_str_startswith(s, "NO", CASE_IGNORE) &&
!mutt_str_startswith(s, "BAD", CASE_IGNORE)))
{
mutt_debug(LL_DEBUG2, "not a command completion: %s\n", adata->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 adata Imap Account data
* @param cmdstr Command to execute
* @param flags Flags, see #ImapCmdFlags
* @retval #IMAP_EXEC_SUCCESS Command successful or queued
* @retval #IMAP_EXEC_ERROR Command returned an error
* @retval #IMAP_EXEC_FATAL Imap connection failure
*
* Also, handle untagged responses.
*/
int imap_exec(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags)
{
int rc;
rc = cmd_start(adata, cmdstr, flags);
if (rc < 0)
{
cmd_handle_fatal(adata);
return IMAP_EXEC_FATAL;
}
if (flags & IMAP_CMD_QUEUE)
return IMAP_EXEC_SUCCESS;
if ((flags & IMAP_CMD_POLL) && (C_ImapPollTimeout > 0) &&
((mutt_socket_poll(adata->conn, C_ImapPollTimeout)) == 0))
{
mutt_error(_("Connection to %s timed out"), adata->conn->account.host);
cmd_handle_fatal(adata);
return IMAP_EXEC_FATAL;
}
/* Allow interruptions, particularly useful if there are network problems. */
mutt_sig_allow_interrupt(true);
do
{
rc = imap_cmd_step(adata);
} while (rc == IMAP_RES_CONTINUE);
mutt_sig_allow_interrupt(false);
if (rc == IMAP_RES_NO)
return IMAP_EXEC_ERROR;
if (rc != IMAP_RES_OK)
{
if (adata->status != IMAP_FATAL)
return IMAP_EXEC_ERROR;
mutt_debug(LL_DEBUG1, "command failed: %s\n", adata->buf);
return IMAP_EXEC_FATAL;
}
return IMAP_EXEC_SUCCESS;
}
/**
* imap_cmd_finish - Attempt to perform cleanup
* @param adata Imap Account data
*
* If a reopen is allowed, it 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.
*
* mdata->check_status is set and will be used later by imap_check_mailbox().
*/
void imap_cmd_finish(struct ImapAccountData *adata)
{
if (!adata)
return;
if (adata->status == IMAP_FATAL)
{
adata->closing = false;
cmd_handle_fatal(adata);
return;
}
if (!(adata->state >= IMAP_SELECTED) || (adata->mailbox && adata->closing))
{
adata->closing = false;
return;
}
adata->closing = false;
struct ImapMboxData *mdata = imap_mdata_get(adata->mailbox);
if (mdata && mdata->reopen & IMAP_REOPEN_ALLOW)
{
// First remove expunged emails from the msn_index
if (mdata->reopen & IMAP_EXPUNGE_PENDING)
{
mutt_debug(LL_DEBUG2, "Expunging mailbox\n");
imap_expunge_mailbox(adata->mailbox);
/* Detect whether we've gotten unexpected EXPUNGE messages */
if (!(mdata->reopen & IMAP_EXPUNGE_EXPECTED))
mdata->check_status |= IMAP_EXPUNGE_PENDING;
mdata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_EXPUNGE_EXPECTED);
}
// Then add new emails to it
if (mdata->reopen & IMAP_NEWMAIL_PENDING && (mdata->new_mail_count > mdata->max_msn))
{
if (!(mdata->reopen & IMAP_EXPUNGE_PENDING))
mdata->check_status |= IMAP_NEWMAIL_PENDING;
mutt_debug(LL_DEBUG2, "Fetching new mails from %d to %d\n",
mdata->max_msn + 1, mdata->new_mail_count);
imap_read_headers(adata->mailbox, mdata->max_msn + 1, mdata->new_mail_count, false);
}
// And to finish inform about MUTT_REOPEN if needed
if (mdata->reopen & IMAP_EXPUNGE_PENDING && !(mdata->reopen & IMAP_EXPUNGE_EXPECTED))
mdata->check_status |= IMAP_EXPUNGE_PENDING;
if (mdata->reopen & IMAP_EXPUNGE_PENDING)
mdata->reopen &= ~(IMAP_EXPUNGE_PENDING | IMAP_EXPUNGE_EXPECTED);
}
adata->status = 0;
}
/**
* imap_cmd_idle - Enter the IDLE state
* @param adata Imap Account data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_RES_BAD
*/
int imap_cmd_idle(struct ImapAccountData *adata)
{
int rc;
if (cmd_start(adata, "IDLE", IMAP_CMD_POLL) < 0)
{
cmd_handle_fatal(adata);
return -1;
}
if ((C_ImapPollTimeout > 0) && ((mutt_socket_poll(adata->conn, C_ImapPollTimeout)) == 0))
{
mutt_error(_("Connection to %s timed out"), adata->conn->account.host);
cmd_handle_fatal(adata);
return -1;
}
do
{
rc = imap_cmd_step(adata);
} while (rc == IMAP_RES_CONTINUE);
if (rc == IMAP_RES_RESPOND)
{
/* successfully entered IDLE state */
adata->state = IMAP_IDLE;
/* queue automatic exit when next command is issued */
mutt_buffer_addstr(&adata->cmdbuf, "DONE\r\n");
rc = IMAP_RES_OK;
}
if (rc != IMAP_RES_OK)
{
mutt_debug(LL_DEBUG1, "error starting IDLE\n");
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_4069_2 |
crossvul-cpp_data_bad_4069_5 | /**
* @file
* Usenet network mailbox type; talk to an NNTP server
*
* @authors
* Copyright (C) 1998 Brandon Long <blong@fiction.net>
* Copyright (C) 1999 Andrej Gritsenko <andrej@lucky.net>
* Copyright (C) 2000-2017 Vsevolod Volkov <vvv@mutt.org.ua>
* Copyright (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 nntp_nntp Usenet network mailbox type; talk to an NNTP server
*
* Usenet network mailbox type; talk to an NNTP server
*/
#include "config.h"
#include <ctype.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include "private.h"
#include "mutt/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "gui/lib.h"
#include "lib.h"
#include "globals.h"
#include "hook.h"
#include "init.h"
#include "mutt_logging.h"
#include "mutt_parse.h"
#include "mutt_socket.h"
#include "muttlib.h"
#include "mx.h"
#include "progress.h"
#include "sort.h"
#include "bcache/lib.h"
#include "hcache/lib.h"
#include "ncrypt/lib.h"
#ifdef USE_HCACHE
#include "protos.h"
#endif
#ifdef USE_SASL
#include <sasl/sasl.h>
#include <sasl/saslutil.h>
#endif
#if defined(USE_SSL) || defined(USE_HCACHE)
#include "mutt.h"
#endif
struct stat;
/* These Config Variables are only used in nntp/nntp.c */
char *C_NntpAuthenticators; ///< Config: (nntp) Allowed authentication methods
short C_NntpContext; ///< Config: (nntp) Maximum number of articles to list (0 for all articles)
bool C_NntpListgroup; ///< Config: (nntp) Check all articles when opening a newsgroup
bool C_NntpLoadDescription; ///< Config: (nntp) Load descriptions for newsgroups when adding to the list
short C_NntpPoll; ///< Config: (nntp) Interval between checks for new posts
bool C_ShowNewNews; ///< Config: (nntp) Check for new newsgroups when entering the browser
struct NntpAccountData *CurrentNewsSrv;
const char *OverviewFmt = "Subject:\0"
"From:\0"
"Date:\0"
"Message-ID:\0"
"References:\0"
"Content-Length:\0"
"Lines:\0"
"\0";
/**
* struct FetchCtx - Keep track when getting data from a server
*/
struct FetchCtx
{
struct Mailbox *mailbox;
anum_t first;
anum_t last;
bool restore;
unsigned char *messages;
struct Progress progress;
header_cache_t *hc;
};
/**
* struct ChildCtx - Keep track of the children of an article
*/
struct ChildCtx
{
struct Mailbox *mailbox;
unsigned int num;
unsigned int max;
anum_t *child;
};
/**
* nntp_adata_free - Free data attached to the Mailbox
* @param[out] ptr NNTP data
*
* The NntpAccountData struct stores global NNTP data, such as the connection to
* the database. This function will close the database, free the resources and
* the struct itself.
*/
static void nntp_adata_free(void **ptr)
{
if (!ptr || !*ptr)
return;
struct NntpAccountData *adata = *ptr;
mutt_file_fclose(&adata->fp_newsrc);
FREE(&adata->newsrc_file);
FREE(&adata->authenticators);
FREE(&adata->overview_fmt);
FREE(&adata->conn);
FREE(&adata->groups_list);
mutt_hash_free(&adata->groups_hash);
FREE(ptr);
}
/**
* nntp_hashelem_free - Free our hash table data - Implements ::hash_hdata_free_t
*/
static void nntp_hashelem_free(int type, void *obj, intptr_t data)
{
nntp_mdata_free(&obj);
}
/**
* nntp_adata_new - Allocate and initialise a new NntpAccountData structure
* @param conn Network connection
* @retval ptr New NntpAccountData
*/
struct NntpAccountData *nntp_adata_new(struct Connection *conn)
{
struct NntpAccountData *adata = mutt_mem_calloc(1, sizeof(struct NntpAccountData));
adata->conn = conn;
adata->groups_hash = mutt_hash_new(1009, MUTT_HASH_NO_FLAGS);
mutt_hash_set_destructor(adata->groups_hash, nntp_hashelem_free, 0);
adata->groups_max = 16;
adata->groups_list =
mutt_mem_malloc(adata->groups_max * sizeof(struct NntpMboxData *));
return adata;
}
#if 0
/**
* nntp_adata_get - Get the Account data for this mailbox
* @retval ptr Private Account data
*/
struct NntpAccountData *nntp_adata_get(struct Mailbox *m)
{
if (!m || (m->type != MUTT_NNTP))
return NULL;
struct Account *a = m->account;
if (!a)
return NULL;
return a->adata;
}
#endif
/**
* nntp_mdata_free - Free NntpMboxData, used to destroy hash elements
* @param[out] ptr NNTP data
*/
void nntp_mdata_free(void **ptr)
{
if (!ptr || !*ptr)
return;
struct NntpMboxData *mdata = *ptr;
nntp_acache_free(mdata);
mutt_bcache_close(&mdata->bcache);
FREE(&mdata->newsrc_ent);
FREE(&mdata->desc);
FREE(ptr);
}
/**
* nntp_edata_free - Free data attached to an Email
* @param[out] ptr Email data
*/
static void nntp_edata_free(void **ptr)
{
// struct NntpEmailData *edata = *ptr;
FREE(ptr);
}
/**
* nntp_edata_new - Create a new NntpEmailData for an Email
* @retval ptr New NntpEmailData struct
*/
static struct NntpEmailData *nntp_edata_new(void)
{
return mutt_mem_calloc(1, sizeof(struct NntpEmailData));
}
/**
* nntp_edata_get - Get the private data for this Email
* @param e Email
* @retval ptr Private Email data
*/
struct NntpEmailData *nntp_edata_get(struct Email *e)
{
if (!e)
return NULL;
return e->edata;
}
/**
* nntp_connect_error - Signal a failed connection
* @param adata NNTP server
* @retval -1 Always
*/
static int nntp_connect_error(struct NntpAccountData *adata)
{
adata->status = NNTP_NONE;
mutt_error(_("Server closed connection"));
return -1;
}
/**
* nntp_capabilities - Get capabilities
* @param adata NNTP server
* @retval -1 Error, connection is closed
* @retval 0 Mode is reader, capabilities set up
* @retval 1 Need to switch to reader mode
*/
static int nntp_capabilities(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
bool mode_reader = false;
char buf[1024];
char authinfo[1024] = { 0 };
adata->hasCAPABILITIES = false;
adata->hasSTARTTLS = false;
adata->hasDATE = false;
adata->hasLIST_NEWSGROUPS = false;
adata->hasLISTGROUP = false;
adata->hasLISTGROUPrange = false;
adata->hasOVER = false;
FREE(&adata->authenticators);
if ((mutt_socket_send(conn, "CAPABILITIES\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
/* no capabilities */
if (!mutt_str_startswith(buf, "101", CASE_MATCH))
return 1;
adata->hasCAPABILITIES = true;
/* parse capabilities */
do
{
size_t plen = 0;
if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
return nntp_connect_error(adata);
if (mutt_str_strcmp("STARTTLS", buf) == 0)
adata->hasSTARTTLS = true;
else if (mutt_str_strcmp("MODE-READER", buf) == 0)
mode_reader = true;
else if (mutt_str_strcmp("READER", buf) == 0)
{
adata->hasDATE = true;
adata->hasLISTGROUP = true;
adata->hasLISTGROUPrange = true;
}
else if ((plen = mutt_str_startswith(buf, "AUTHINFO ", CASE_MATCH)))
{
mutt_str_strcat(buf, sizeof(buf), " ");
mutt_str_strfcpy(authinfo, buf + plen - 1, sizeof(authinfo));
}
#ifdef USE_SASL
else if ((plen = mutt_str_startswith(buf, "SASL ", CASE_MATCH)))
{
char *p = buf + plen;
while (*p == ' ')
p++;
adata->authenticators = mutt_str_strdup(p);
}
#endif
else if (mutt_str_strcmp("OVER", buf) == 0)
adata->hasOVER = true;
else if (mutt_str_startswith(buf, "LIST ", CASE_MATCH))
{
char *p = strstr(buf, " NEWSGROUPS");
if (p)
{
p += 11;
if ((*p == '\0') || (*p == ' '))
adata->hasLIST_NEWSGROUPS = true;
}
}
} while (mutt_str_strcmp(".", buf) != 0);
*buf = '\0';
#ifdef USE_SASL
if (adata->authenticators && strcasestr(authinfo, " SASL "))
mutt_str_strfcpy(buf, adata->authenticators, sizeof(buf));
#endif
if (strcasestr(authinfo, " USER "))
{
if (*buf != '\0')
mutt_str_strcat(buf, sizeof(buf), " ");
mutt_str_strcat(buf, sizeof(buf), "USER");
}
mutt_str_replace(&adata->authenticators, buf);
/* current mode is reader */
if (adata->hasDATE)
return 0;
/* server is mode-switching, need to switch to reader mode */
if (mode_reader)
return 1;
mutt_socket_close(conn);
adata->status = NNTP_BYE;
mutt_error(_("Server doesn't support reader mode"));
return -1;
}
/**
* nntp_attempt_features - Detect supported commands
* @param adata NNTP server
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_attempt_features(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
char buf[1024];
/* no CAPABILITIES, trying DATE, LISTGROUP, LIST NEWSGROUPS */
if (!adata->hasCAPABILITIES)
{
if ((mutt_socket_send(conn, "DATE\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasDATE = true;
if ((mutt_socket_send(conn, "LISTGROUP\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasLISTGROUP = true;
if ((mutt_socket_send(conn, "LIST NEWSGROUPS +\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasLIST_NEWSGROUPS = true;
if (mutt_str_startswith(buf, "215", CASE_MATCH))
{
do
{
if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
return nntp_connect_error(adata);
} while (mutt_str_strcmp(".", buf) != 0);
}
}
/* no LIST NEWSGROUPS, trying XGTITLE */
if (!adata->hasLIST_NEWSGROUPS)
{
if ((mutt_socket_send(conn, "XGTITLE\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasXGTITLE = true;
}
/* no OVER, trying XOVER */
if (!adata->hasOVER)
{
if ((mutt_socket_send(conn, "XOVER\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasXOVER = true;
}
/* trying LIST OVERVIEW.FMT */
if (adata->hasOVER || adata->hasXOVER)
{
if ((mutt_socket_send(conn, "LIST OVERVIEW.FMT\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "215", CASE_MATCH))
adata->overview_fmt = mutt_str_strdup(OverviewFmt);
else
{
bool cont = false;
size_t buflen = 2048, off = 0, b = 0;
FREE(&adata->overview_fmt);
adata->overview_fmt = mutt_mem_malloc(buflen);
while (true)
{
if ((buflen - off) < 1024)
{
buflen *= 2;
mutt_mem_realloc(&adata->overview_fmt, buflen);
}
const int chunk = mutt_socket_readln_d(adata->overview_fmt + off,
buflen - off, conn, MUTT_SOCK_LOG_HDR);
if (chunk < 0)
{
FREE(&adata->overview_fmt);
return nntp_connect_error(adata);
}
if (!cont && (mutt_str_strcmp(".", adata->overview_fmt + off) == 0))
break;
cont = (chunk >= (buflen - off));
off += strlen(adata->overview_fmt + off);
if (!cont)
{
if (adata->overview_fmt[b] == ':')
{
memmove(adata->overview_fmt + b, adata->overview_fmt + b + 1, off - b - 1);
adata->overview_fmt[off - 1] = ':';
}
char *colon = strchr(adata->overview_fmt + b, ':');
if (!colon)
adata->overview_fmt[off++] = ':';
else if (strcmp(colon + 1, "full") != 0)
off = colon + 1 - adata->overview_fmt;
if (strcasecmp(adata->overview_fmt + b, "Bytes:") == 0)
{
size_t len = strlen(adata->overview_fmt + b);
mutt_str_strfcpy(adata->overview_fmt + b, "Content-Length:", len + 1);
off = b + len;
}
adata->overview_fmt[off++] = '\0';
b = off;
}
}
adata->overview_fmt[off++] = '\0';
mutt_mem_realloc(&adata->overview_fmt, off);
}
}
return 0;
}
#ifdef USE_SASL
/**
* nntp_memchr - look for a char in a binary buf, conveniently
* @param haystack [in/out] input: start here, output: store address of hit
* @param sentinel points just beyond (1 byte after) search area
* @param needle the character to search for
* @retval true found and updated haystack
* @retval false not found
*/
static bool nntp_memchr(char **haystack, char *sentinel, int needle)
{
char *start = *haystack;
size_t max_offset = sentinel - start;
void *vp = memchr(start, max_offset, needle);
if (!vp)
return false;
*haystack = vp;
return true;
}
/**
* nntp_log_binbuf - log a buffer possibly containing NUL bytes
* @param buf source buffer
* @param len how many bytes from buf
* @param pfx logging prefix (protocol etc.)
* @param dbg which loglevel does message belong
*/
static void nntp_log_binbuf(const char *buf, size_t len, const char *pfx, int dbg)
{
char tmp[1024];
char *p = tmp;
char *sentinel = tmp + len;
if (C_DebugLevel < dbg)
return;
memcpy(tmp, buf, len);
tmp[len] = '\0';
while (nntp_memchr(&p, sentinel, '\0'))
*p = '.';
mutt_debug(dbg, "%s> %s\n", pfx, tmp);
}
#endif
/**
* nntp_auth - Get login, password and authenticate
* @param adata NNTP server
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_auth(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
char buf[1024];
char authenticators[1024] = "USER";
char *method = NULL, *a = NULL, *p = NULL;
unsigned char flags = conn->account.flags;
while (true)
{
/* get login and password */
if ((mutt_account_getuser(&conn->account) < 0) || (conn->account.user[0] == '\0') ||
(mutt_account_getpass(&conn->account) < 0) || (conn->account.pass[0] == '\0'))
{
break;
}
/* get list of authenticators */
if (C_NntpAuthenticators)
mutt_str_strfcpy(authenticators, C_NntpAuthenticators, sizeof(authenticators));
else if (adata->hasCAPABILITIES)
{
mutt_str_strfcpy(authenticators, adata->authenticators, sizeof(authenticators));
p = authenticators;
while (*p)
{
if (*p == ' ')
*p = ':';
p++;
}
}
p = authenticators;
while (*p)
{
*p = toupper(*p);
p++;
}
mutt_debug(LL_DEBUG1, "available methods: %s\n", adata->authenticators);
a = authenticators;
while (true)
{
if (!a)
{
mutt_error(_("No authenticators available"));
break;
}
method = a;
a = strchr(a, ':');
if (a)
*a++ = '\0';
/* check authenticator */
if (adata->hasCAPABILITIES)
{
char *m = NULL;
if (!adata->authenticators)
continue;
m = strcasestr(adata->authenticators, method);
if (!m)
continue;
if ((m > adata->authenticators) && (*(m - 1) != ' '))
continue;
m += strlen(method);
if ((*m != '\0') && (*m != ' '))
continue;
}
mutt_debug(LL_DEBUG1, "trying method %s\n", method);
/* AUTHINFO USER authentication */
if (strcmp(method, "USER") == 0)
{
mutt_message(_("Authenticating (%s)..."), method);
snprintf(buf, sizeof(buf), "AUTHINFO USER %s\r\n", conn->account.user);
if ((mutt_socket_send(conn, buf) < 0) ||
(mutt_socket_readln_d(buf, sizeof(buf), conn, MUTT_SOCK_LOG_FULL) < 0))
{
break;
}
/* authenticated, password is not required */
if (mutt_str_startswith(buf, "281", CASE_MATCH))
return 0;
/* username accepted, sending password */
if (mutt_str_startswith(buf, "381", CASE_MATCH))
{
mutt_debug(MUTT_SOCK_LOG_FULL, "%d> AUTHINFO PASS *\n", conn->fd);
snprintf(buf, sizeof(buf), "AUTHINFO PASS %s\r\n", conn->account.pass);
if ((mutt_socket_send_d(conn, buf, MUTT_SOCK_LOG_FULL) < 0) ||
(mutt_socket_readln_d(buf, sizeof(buf), conn, MUTT_SOCK_LOG_FULL) < 0))
{
break;
}
/* authenticated */
if (mutt_str_startswith(buf, "281", CASE_MATCH))
return 0;
}
/* server doesn't support AUTHINFO USER, trying next method */
if (*buf == '5')
continue;
}
else
{
#ifdef USE_SASL
sasl_conn_t *saslconn = NULL;
sasl_interact_t *interaction = NULL;
int rc;
char inbuf[1024] = { 0 };
const char *mech = NULL;
const char *client_out = NULL;
unsigned int client_len, len;
if (mutt_sasl_client_new(conn, &saslconn) < 0)
{
mutt_debug(LL_DEBUG1, "error allocating SASL connection\n");
continue;
}
while (true)
{
rc = sasl_client_start(saslconn, method, &interaction, &client_out,
&client_len, &mech);
if (rc != SASL_INTERACT)
break;
mutt_sasl_interact(interaction);
}
if ((rc != SASL_OK) && (rc != SASL_CONTINUE))
{
sasl_dispose(&saslconn);
mutt_debug(LL_DEBUG1,
"error starting SASL authentication exchange\n");
continue;
}
mutt_message(_("Authenticating (%s)..."), method);
snprintf(buf, sizeof(buf), "AUTHINFO SASL %s", method);
/* looping protocol */
while ((rc == SASL_CONTINUE) || ((rc == SASL_OK) && client_len))
{
/* send out client response */
if (client_len)
{
nntp_log_binbuf(client_out, client_len, "SASL", MUTT_SOCK_LOG_FULL);
if (*buf != '\0')
mutt_str_strcat(buf, sizeof(buf), " ");
len = strlen(buf);
if (sasl_encode64(client_out, client_len, buf + len,
sizeof(buf) - len, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "error base64-encoding client response\n");
break;
}
}
mutt_str_strcat(buf, sizeof(buf), "\r\n");
if (strchr(buf, ' '))
{
mutt_debug(MUTT_SOCK_LOG_CMD, "%d> AUTHINFO SASL %s%s\n", conn->fd,
method, client_len ? " sasl_data" : "");
}
else
mutt_debug(MUTT_SOCK_LOG_CMD, "%d> sasl_data\n", conn->fd);
client_len = 0;
if ((mutt_socket_send_d(conn, buf, MUTT_SOCK_LOG_FULL) < 0) ||
(mutt_socket_readln_d(inbuf, sizeof(inbuf), conn, MUTT_SOCK_LOG_FULL) < 0))
{
break;
}
if (!mutt_str_startswith(inbuf, "283 ", CASE_MATCH) &&
!mutt_str_startswith(inbuf, "383 ", CASE_MATCH))
{
mutt_debug(MUTT_SOCK_LOG_FULL, "%d< %s\n", conn->fd, inbuf);
break;
}
inbuf[3] = '\0';
mutt_debug(MUTT_SOCK_LOG_FULL, "%d< %s sasl_data\n", conn->fd, inbuf);
if (strcmp("=", inbuf + 4) == 0)
len = 0;
else if (sasl_decode64(inbuf + 4, strlen(inbuf + 4), buf,
sizeof(buf) - 1, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "error base64-decoding server response\n");
break;
}
else
nntp_log_binbuf(buf, len, "SASL", MUTT_SOCK_LOG_FULL);
while (true)
{
rc = sasl_client_step(saslconn, buf, len, &interaction, &client_out, &client_len);
if (rc != SASL_INTERACT)
break;
mutt_sasl_interact(interaction);
}
if (*inbuf != '3')
break;
*buf = '\0';
} /* looping protocol */
if ((rc == SASL_OK) && (client_len == 0) && (*inbuf == '2'))
{
mutt_sasl_setup_conn(conn, saslconn);
return 0;
}
/* terminate SASL session */
sasl_dispose(&saslconn);
if (conn->fd < 0)
break;
if (mutt_str_startswith(inbuf, "383 ", CASE_MATCH))
{
if ((mutt_socket_send(conn, "*\r\n") < 0) ||
(mutt_socket_readln(inbuf, sizeof(inbuf), conn) < 0))
{
break;
}
}
/* server doesn't support AUTHINFO SASL, trying next method */
if (*inbuf == '5')
continue;
#else
continue;
#endif /* USE_SASL */
}
mutt_error(_("%s authentication failed"), method);
break;
}
break;
}
/* error */
adata->status = NNTP_BYE;
conn->account.flags = flags;
if (conn->fd < 0)
{
mutt_error(_("Server closed connection"));
}
else
mutt_socket_close(conn);
return -1;
}
/**
* nntp_query - Send data from buffer and receive answer to same buffer
* @param mdata NNTP Mailbox data
* @param line Buffer containing data
* @param linelen Length of buffer
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_query(struct NntpMboxData *mdata, char *line, size_t linelen)
{
struct NntpAccountData *adata = mdata->adata;
char buf[1024] = { 0 };
if (adata->status == NNTP_BYE)
return -1;
while (true)
{
if (adata->status == NNTP_OK)
{
int rc = 0;
if (*line)
rc = mutt_socket_send(adata->conn, line);
else if (mdata->group)
{
snprintf(buf, sizeof(buf), "GROUP %s\r\n", mdata->group);
rc = mutt_socket_send(adata->conn, buf);
}
if (rc >= 0)
rc = mutt_socket_readln(buf, sizeof(buf), adata->conn);
if (rc >= 0)
break;
}
/* reconnect */
while (true)
{
adata->status = NNTP_NONE;
if (nntp_open_connection(adata) == 0)
break;
snprintf(buf, sizeof(buf), _("Connection to %s lost. Reconnect?"),
adata->conn->account.host);
if (mutt_yesorno(buf, MUTT_YES) != MUTT_YES)
{
adata->status = NNTP_BYE;
return -1;
}
}
/* select newsgroup after reconnection */
if (mdata->group)
{
snprintf(buf, sizeof(buf), "GROUP %s\r\n", mdata->group);
if ((mutt_socket_send(adata->conn, buf) < 0) ||
(mutt_socket_readln(buf, sizeof(buf), adata->conn) < 0))
{
return nntp_connect_error(adata);
}
}
if (*line == '\0')
break;
}
mutt_str_strfcpy(line, buf, linelen);
return 0;
}
/**
* nntp_fetch_lines - Read lines, calling a callback function for each
* @param mdata NNTP Mailbox data
* @param query Query to match
* @param qlen Length of query
* @param msg Progress message (OPTIONAL)
* @param func Callback function
* @param data Data for callback function
* @retval 0 Success
* @retval 1 Bad response (answer in query buffer)
* @retval -1 Connection lost
* @retval -2 Error in func(*line, *data)
*
* This function calls func(*line, *data) for each received line,
* func(NULL, *data) if rewind(*data) needs, exits when fail or done:
*/
static int nntp_fetch_lines(struct NntpMboxData *mdata, char *query, size_t qlen,
const char *msg, int (*func)(char *, void *), void *data)
{
bool done = false;
int rc;
while (!done)
{
char buf[1024];
char *line = NULL;
unsigned int lines = 0;
size_t off = 0;
struct Progress progress;
if (msg)
mutt_progress_init(&progress, msg, MUTT_PROGRESS_READ, 0);
mutt_str_strfcpy(buf, query, sizeof(buf));
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
return -1;
if (buf[0] != '2')
{
mutt_str_strfcpy(query, buf, qlen);
return 1;
}
line = mutt_mem_malloc(sizeof(buf));
rc = 0;
while (true)
{
char *p = NULL;
int chunk = mutt_socket_readln_d(buf, sizeof(buf), mdata->adata->conn, MUTT_SOCK_LOG_FULL);
if (chunk < 0)
{
mdata->adata->status = NNTP_NONE;
break;
}
p = buf;
if (!off && (buf[0] == '.'))
{
if (buf[1] == '\0')
{
done = true;
break;
}
if (buf[1] == '.')
p++;
}
mutt_str_strfcpy(line + off, p, sizeof(buf));
if (chunk >= sizeof(buf))
off += strlen(p);
else
{
if (msg)
mutt_progress_update(&progress, ++lines, -1);
if ((rc == 0) && (func(line, data) < 0))
rc = -2;
off = 0;
}
mutt_mem_realloc(&line, off + sizeof(buf));
}
FREE(&line);
func(NULL, data);
}
return rc;
}
/**
* fetch_description - Parse newsgroup description
* @param line String to parse
* @param data NNTP Server
* @retval 0 Always
*/
static int fetch_description(char *line, void *data)
{
if (!line)
return 0;
struct NntpAccountData *adata = data;
char *desc = strpbrk(line, " \t");
if (desc)
{
*desc++ = '\0';
desc += strspn(desc, " \t");
}
else
desc = strchr(line, '\0');
struct NntpMboxData *mdata = mutt_hash_find(adata->groups_hash, line);
if (mdata && (mutt_str_strcmp(desc, mdata->desc) != 0))
{
mutt_str_replace(&mdata->desc, desc);
mutt_debug(LL_DEBUG2, "group: %s, desc: %s\n", line, desc);
}
return 0;
}
/**
* get_description - Fetch newsgroups descriptions
* @param mdata NNTP Mailbox data
* @param wildmat String to match
* @param msg Progress message
* @retval 0 Success
* @retval 1 Bad response (answer in query buffer)
* @retval -1 Connection lost
* @retval -2 Error
*/
static int get_description(struct NntpMboxData *mdata, const char *wildmat, const char *msg)
{
char buf[256];
const char *cmd = NULL;
/* get newsgroup description, if possible */
struct NntpAccountData *adata = mdata->adata;
if (!wildmat)
wildmat = mdata->group;
if (adata->hasLIST_NEWSGROUPS)
cmd = "LIST NEWSGROUPS";
else if (adata->hasXGTITLE)
cmd = "XGTITLE";
else
return 0;
snprintf(buf, sizeof(buf), "%s %s\r\n", cmd, wildmat);
int rc = nntp_fetch_lines(mdata, buf, sizeof(buf), msg, fetch_description, adata);
if (rc > 0)
{
mutt_error("%s: %s", cmd, buf);
}
return rc;
}
/**
* nntp_parse_xref - Parse cross-reference
* @param m Mailbox
* @param e Email
*
* Update read flag and set article number if empty
*/
static void nntp_parse_xref(struct Mailbox *m, struct Email *e)
{
struct NntpMboxData *mdata = m->mdata;
char *buf = mutt_str_strdup(e->env->xref);
char *p = buf;
while (p)
{
anum_t anum;
/* skip to next word */
p += strspn(p, " \t");
char *grp = p;
/* skip to end of word */
p = strpbrk(p, " \t");
if (p)
*p++ = '\0';
/* find colon */
char *colon = strchr(grp, ':');
if (!colon)
continue;
*colon++ = '\0';
if (sscanf(colon, ANUM, &anum) != 1)
continue;
nntp_article_status(m, e, grp, anum);
if (!nntp_edata_get(e)->article_num && (mutt_str_strcmp(mdata->group, grp) == 0))
nntp_edata_get(e)->article_num = anum;
}
FREE(&buf);
}
/**
* fetch_tempfile - Write line to temporary file
* @param line Text to write
* @param data FILE pointer
* @retval 0 Success
* @retval -1 Failure
*/
static int fetch_tempfile(char *line, void *data)
{
FILE *fp = data;
if (!line)
rewind(fp);
else if ((fputs(line, fp) == EOF) || (fputc('\n', fp) == EOF))
return -1;
return 0;
}
/**
* fetch_numbers - Parse article number
* @param line Article number
* @param data FetchCtx
* @retval 0 Always
*/
static int fetch_numbers(char *line, void *data)
{
struct FetchCtx *fc = data;
anum_t anum;
if (!line)
return 0;
if (sscanf(line, ANUM, &anum) != 1)
return 0;
if ((anum < fc->first) || (anum > fc->last))
return 0;
fc->messages[anum - fc->first] = 1;
return 0;
}
/**
* parse_overview_line - Parse overview line
* @param line String to parse
* @param data FetchCtx
* @retval 0 Success
* @retval -1 Failure
*/
static int parse_overview_line(char *line, void *data)
{
if (!line || !data)
return 0;
struct FetchCtx *fc = data;
struct Mailbox *m = fc->mailbox;
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct Email *e = NULL;
char *header = NULL, *field = NULL;
bool save = true;
anum_t anum;
/* parse article number */
field = strchr(line, '\t');
if (field)
*field++ = '\0';
if (sscanf(line, ANUM, &anum) != 1)
return 0;
mutt_debug(LL_DEBUG2, "" ANUM "\n", anum);
/* out of bounds */
if ((anum < fc->first) || (anum > fc->last))
return 0;
/* not in LISTGROUP */
if (!fc->messages[anum - fc->first])
{
/* progress */
if (m->verbose)
mutt_progress_update(&fc->progress, anum - fc->first + 1, -1);
return 0;
}
/* convert overview line to header */
FILE *fp = mutt_file_mkstemp();
if (!fp)
return -1;
header = mdata->adata->overview_fmt;
while (field)
{
char *b = field;
if (*header)
{
if (!strstr(header, ":full") && (fputs(header, fp) == EOF))
{
mutt_file_fclose(&fp);
return -1;
}
header = strchr(header, '\0') + 1;
}
field = strchr(field, '\t');
if (field)
*field++ = '\0';
if ((fputs(b, fp) == EOF) || (fputc('\n', fp) == EOF))
{
mutt_file_fclose(&fp);
return -1;
}
}
rewind(fp);
/* allocate memory for headers */
if (m->msg_count >= m->email_max)
mx_alloc_memory(m);
/* parse header */
m->emails[m->msg_count] = email_new();
e = m->emails[m->msg_count];
e->env = mutt_rfc822_read_header(fp, e, false, false);
e->env->newsgroups = mutt_str_strdup(mdata->group);
e->received = e->date_sent;
mutt_file_fclose(&fp);
#ifdef USE_HCACHE
if (fc->hc)
{
char buf[16];
/* try to replace with header from cache */
snprintf(buf, sizeof(buf), "%u", anum);
struct HCacheEntry hce = mutt_hcache_fetch(fc->hc, buf, strlen(buf), 0);
if (hce.email)
{
mutt_debug(LL_DEBUG2, "mutt_hcache_fetch %s\n", buf);
email_free(&e);
e = hce.email;
m->emails[m->msg_count] = e;
e->edata = NULL;
e->read = false;
e->old = false;
/* skip header marked as deleted in cache */
if (e->deleted && !fc->restore)
{
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
save = false;
}
}
/* not cached yet, store header */
else
{
mutt_debug(LL_DEBUG2, "mutt_hcache_store %s\n", buf);
mutt_hcache_store(fc->hc, buf, strlen(buf), e, 0);
}
}
#endif
if (save)
{
e->index = m->msg_count++;
e->read = false;
e->old = false;
e->deleted = false;
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
nntp_edata_get(e)->article_num = anum;
if (fc->restore)
e->changed = true;
else
{
nntp_article_status(m, e, NULL, anum);
if (!e->read)
nntp_parse_xref(m, e);
}
if (anum > mdata->last_loaded)
mdata->last_loaded = anum;
}
else
email_free(&e);
/* progress */
if (m->verbose)
mutt_progress_update(&fc->progress, anum - fc->first + 1, -1);
return 0;
}
/**
* nntp_fetch_headers - Fetch headers
* @param m Mailbox
* @param hc Header cache
* @param first Number of first header to fetch
* @param last Number of last header to fetch
* @param restore Restore message listed as deleted
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_fetch_headers(struct Mailbox *m, void *hc, anum_t first, anum_t last, bool restore)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct FetchCtx fc;
struct Email *e = NULL;
char buf[8192];
int rc = 0;
anum_t current;
anum_t first_over = first;
/* if empty group or nothing to do */
if (!last || (first > last))
return 0;
/* init fetch context */
fc.mailbox = m;
fc.first = first;
fc.last = last;
fc.restore = restore;
fc.messages = mutt_mem_calloc(last - first + 1, sizeof(unsigned char));
if (!fc.messages)
return -1;
fc.hc = hc;
/* fetch list of articles */
if (C_NntpListgroup && mdata->adata->hasLISTGROUP && !mdata->deleted)
{
if (m->verbose)
mutt_message(_("Fetching list of articles..."));
if (mdata->adata->hasLISTGROUPrange)
snprintf(buf, sizeof(buf), "LISTGROUP %s %u-%u\r\n", mdata->group, first, last);
else
snprintf(buf, sizeof(buf), "LISTGROUP %s\r\n", mdata->group);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_numbers, &fc);
if (rc > 0)
{
mutt_error("LISTGROUP: %s", buf);
}
if (rc == 0)
{
for (current = first; current <= last && rc == 0; current++)
{
if (fc.messages[current - first])
continue;
snprintf(buf, sizeof(buf), "%u", current);
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "#1 mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
#ifdef USE_HCACHE
if (fc.hc)
{
mutt_debug(LL_DEBUG2, "mutt_hcache_delete_header %s\n", buf);
mutt_hcache_delete_header(fc.hc, buf, strlen(buf));
}
#endif
}
}
}
else
{
for (current = first; current <= last; current++)
fc.messages[current - first] = 1;
}
/* fetching header from cache or server, or fallback to fetch overview */
if (m->verbose)
{
mutt_progress_init(&fc.progress, _("Fetching message headers..."),
MUTT_PROGRESS_READ, last - first + 1);
}
for (current = first; current <= last && rc == 0; current++)
{
if (m->verbose)
mutt_progress_update(&fc.progress, current - first + 1, -1);
#ifdef USE_HCACHE
snprintf(buf, sizeof(buf), "%u", current);
#endif
/* delete header from cache that does not exist on server */
if (!fc.messages[current - first])
continue;
/* allocate memory for headers */
if (m->msg_count >= m->email_max)
mx_alloc_memory(m);
#ifdef USE_HCACHE
/* try to fetch header from cache */
struct HCacheEntry hce = mutt_hcache_fetch(fc.hc, buf, strlen(buf), 0);
if (hce.email)
{
mutt_debug(LL_DEBUG2, "mutt_hcache_fetch %s\n", buf);
e = hce.email;
m->emails[m->msg_count] = e;
e->edata = NULL;
/* skip header marked as deleted in cache */
if (e->deleted && !restore)
{
email_free(&e);
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "#2 mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
continue;
}
e->read = false;
e->old = false;
}
else
#endif
if (mdata->deleted)
{
/* don't try to fetch header from removed newsgroup */
continue;
}
/* fallback to fetch overview */
else if (mdata->adata->hasOVER || mdata->adata->hasXOVER)
{
if (C_NntpListgroup && mdata->adata->hasLISTGROUP)
break;
else
continue;
}
/* fetch header from server */
else
{
FILE *fp = mutt_file_mkstemp();
if (!fp)
{
mutt_perror(_("Can't create temporary file"));
rc = -1;
break;
}
snprintf(buf, sizeof(buf), "HEAD %u\r\n", current);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_tempfile, fp);
if (rc)
{
mutt_file_fclose(&fp);
if (rc < 0)
break;
/* invalid response */
if (!mutt_str_startswith(buf, "423", CASE_MATCH))
{
mutt_error("HEAD: %s", buf);
break;
}
/* no such article */
if (mdata->bcache)
{
snprintf(buf, sizeof(buf), "%u", current);
mutt_debug(LL_DEBUG2, "#3 mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
rc = 0;
continue;
}
/* parse header */
m->emails[m->msg_count] = email_new();
e = m->emails[m->msg_count];
e->env = mutt_rfc822_read_header(fp, e, false, false);
e->received = e->date_sent;
mutt_file_fclose(&fp);
}
/* save header in context */
e->index = m->msg_count++;
e->read = false;
e->old = false;
e->deleted = false;
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
nntp_edata_get(e)->article_num = current;
if (restore)
e->changed = true;
else
{
nntp_article_status(m, e, NULL, nntp_edata_get(e)->article_num);
if (!e->read)
nntp_parse_xref(m, e);
}
if (current > mdata->last_loaded)
mdata->last_loaded = current;
first_over = current + 1;
}
if (!C_NntpListgroup || !mdata->adata->hasLISTGROUP)
current = first_over;
/* fetch overview information */
if ((current <= last) && (rc == 0) && !mdata->deleted)
{
char *cmd = mdata->adata->hasOVER ? "OVER" : "XOVER";
snprintf(buf, sizeof(buf), "%s %u-%u\r\n", cmd, current, last);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, parse_overview_line, &fc);
if (rc > 0)
{
mutt_error("%s: %s", cmd, buf);
}
}
FREE(&fc.messages);
if (rc != 0)
return -1;
mutt_clear_error();
return 0;
}
/**
* nntp_group_poll - Check newsgroup for new articles
* @param mdata NNTP Mailbox data
* @param update_stat Update the stats?
* @retval 1 New articles found
* @retval 0 No change
* @retval -1 Lost connection
*/
static int nntp_group_poll(struct NntpMboxData *mdata, bool update_stat)
{
char buf[1024] = { 0 };
anum_t count, first, last;
/* use GROUP command to poll newsgroup */
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
return -1;
if (sscanf(buf, "211 " ANUM " " ANUM " " ANUM, &count, &first, &last) != 3)
return 0;
if ((first == mdata->first_message) && (last == mdata->last_message))
return 0;
/* articles have been renumbered */
if (last < mdata->last_message)
{
mdata->last_cached = 0;
if (mdata->newsrc_len)
{
mutt_mem_realloc(&mdata->newsrc_ent, sizeof(struct NewsrcEntry));
mdata->newsrc_len = 1;
mdata->newsrc_ent[0].first = 1;
mdata->newsrc_ent[0].last = 0;
}
}
mdata->first_message = first;
mdata->last_message = last;
if (!update_stat)
return 1;
/* update counters */
else if (!last || (!mdata->newsrc_ent && !mdata->last_cached))
mdata->unread = count;
else
nntp_group_unread_stat(mdata);
return 1;
}
/**
* check_mailbox - Check current newsgroup for new articles
* @param m Mailbox
* @retval #MUTT_REOPENED Articles have been renumbered or removed from server
* @retval #MUTT_NEW_MAIL New articles found
* @retval 0 No change
* @retval -1 Lost connection
*
* Leave newsrc locked
*/
static int check_mailbox(struct Mailbox *m)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct NntpAccountData *adata = mdata->adata;
time_t now = mutt_date_epoch();
int rc = 0;
void *hc = NULL;
if (adata->check_time + C_NntpPoll > now)
return 0;
mutt_message(_("Checking for new messages..."));
if (nntp_newsrc_parse(adata) < 0)
return -1;
adata->check_time = now;
int rc2 = nntp_group_poll(mdata, false);
if (rc2 < 0)
{
nntp_newsrc_close(adata);
return -1;
}
if (rc2 != 0)
nntp_active_save_cache(adata);
/* articles have been renumbered, remove all headers */
if (mdata->last_message < mdata->last_loaded)
{
for (int i = 0; i < m->msg_count; i++)
email_free(&m->emails[i]);
m->msg_count = 0;
m->msg_tagged = 0;
if (mdata->last_message < mdata->last_loaded)
{
mdata->last_loaded = mdata->first_message - 1;
if (C_NntpContext && (mdata->last_message - mdata->last_loaded > C_NntpContext))
mdata->last_loaded = mdata->last_message - C_NntpContext;
}
rc = MUTT_REOPENED;
}
/* .newsrc has been externally modified */
if (adata->newsrc_modified)
{
#ifdef USE_HCACHE
unsigned char *messages = NULL;
char buf[16];
struct Email *e = NULL;
anum_t first = mdata->first_message;
if (C_NntpContext && (mdata->last_message - first + 1 > C_NntpContext))
first = mdata->last_message - C_NntpContext + 1;
messages = mutt_mem_calloc(mdata->last_loaded - first + 1, sizeof(unsigned char));
hc = nntp_hcache_open(mdata);
nntp_hcache_update(mdata, hc);
#endif
/* update flags according to .newsrc */
int j = 0;
for (int i = 0; i < m->msg_count; i++)
{
if (!m->emails[i])
continue;
bool flagged = false;
anum_t anum = nntp_edata_get(m->emails[i])->article_num;
#ifdef USE_HCACHE
/* check hcache for flagged and deleted flags */
if (hc)
{
if ((anum >= first) && (anum <= mdata->last_loaded))
messages[anum - first] = 1;
snprintf(buf, sizeof(buf), "%u", anum);
struct HCacheEntry hce = mutt_hcache_fetch(hc, buf, strlen(buf), 0);
if (hce.email)
{
bool deleted;
mutt_debug(LL_DEBUG2, "#1 mutt_hcache_fetch %s\n", buf);
e = hce.email;
e->edata = NULL;
deleted = e->deleted;
flagged = e->flagged;
email_free(&e);
/* header marked as deleted, removing from context */
if (deleted)
{
mutt_set_flag(m, m->emails[i], MUTT_TAG, false);
email_free(&m->emails[i]);
continue;
}
}
}
#endif
if (!m->emails[i]->changed)
{
m->emails[i]->flagged = flagged;
m->emails[i]->read = false;
m->emails[i]->old = false;
nntp_article_status(m, m->emails[i], NULL, anum);
if (!m->emails[i]->read)
nntp_parse_xref(m, m->emails[i]);
}
m->emails[j++] = m->emails[i];
}
#ifdef USE_HCACHE
m->msg_count = j;
/* restore headers without "deleted" flag */
for (anum_t anum = first; anum <= mdata->last_loaded; anum++)
{
if (messages[anum - first])
continue;
snprintf(buf, sizeof(buf), "%u", anum);
struct HCacheEntry hce = mutt_hcache_fetch(hc, buf, strlen(buf), 0);
if (hce.email)
{
mutt_debug(LL_DEBUG2, "#2 mutt_hcache_fetch %s\n", buf);
if (m->msg_count >= m->email_max)
mx_alloc_memory(m);
e = hce.email;
m->emails[m->msg_count] = e;
e->edata = NULL;
if (e->deleted)
{
email_free(&e);
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
continue;
}
m->msg_count++;
e->read = false;
e->old = false;
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
nntp_edata_get(e)->article_num = anum;
nntp_article_status(m, e, NULL, anum);
if (!e->read)
nntp_parse_xref(m, e);
}
}
FREE(&messages);
#endif
adata->newsrc_modified = false;
rc = MUTT_REOPENED;
}
/* some headers were removed, context must be updated */
if (rc == MUTT_REOPENED)
mailbox_changed(m, NT_MAILBOX_INVALID);
/* fetch headers of new articles */
if (mdata->last_message > mdata->last_loaded)
{
int oldmsgcount = m->msg_count;
bool verbose = m->verbose;
m->verbose = false;
#ifdef USE_HCACHE
if (!hc)
{
hc = nntp_hcache_open(mdata);
nntp_hcache_update(mdata, hc);
}
#endif
int old_msg_count = m->msg_count;
rc2 = nntp_fetch_headers(m, hc, mdata->last_loaded + 1, mdata->last_message, false);
m->verbose = verbose;
if (rc2 == 0)
{
if (m->msg_count > old_msg_count)
mailbox_changed(m, NT_MAILBOX_INVALID);
mdata->last_loaded = mdata->last_message;
}
if ((rc == 0) && (m->msg_count > oldmsgcount))
rc = MUTT_NEW_MAIL;
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (rc)
nntp_newsrc_close(adata);
mutt_clear_error();
return rc;
}
/**
* nntp_date - Get date and time from server
* @param adata NNTP server
* @param now Server time
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_date(struct NntpAccountData *adata, time_t *now)
{
if (adata->hasDATE)
{
struct NntpMboxData mdata = { 0 };
char buf[1024];
struct tm tm = { 0 };
mdata.adata = adata;
mdata.group = NULL;
mutt_str_strfcpy(buf, "DATE\r\n", sizeof(buf));
if (nntp_query(&mdata, buf, sizeof(buf)) < 0)
return -1;
if (sscanf(buf, "111 %4d%2d%2d%2d%2d%2d%*s", &tm.tm_year, &tm.tm_mon,
&tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6)
{
tm.tm_year -= 1900;
tm.tm_mon--;
*now = timegm(&tm);
if (*now >= 0)
{
mutt_debug(LL_DEBUG1, "server time is %lu\n", *now);
return 0;
}
}
}
*now = mutt_date_epoch();
return 0;
}
/**
* fetch_children - Parse XPAT line
* @param line String to parse
* @param data ChildCtx
* @retval 0 Always
*/
static int fetch_children(char *line, void *data)
{
struct ChildCtx *cc = data;
anum_t anum;
if (!line || (sscanf(line, ANUM, &anum) != 1))
return 0;
for (unsigned int i = 0; i < cc->mailbox->msg_count; i++)
{
struct Email *e = cc->mailbox->emails[i];
if (!e)
break;
if (nntp_edata_get(e)->article_num == anum)
return 0;
}
if (cc->num >= cc->max)
{
cc->max *= 2;
mutt_mem_realloc(&cc->child, sizeof(anum_t) * cc->max);
}
cc->child[cc->num++] = anum;
return 0;
}
/**
* nntp_open_connection - Connect to server, authenticate and get capabilities
* @param adata NNTP server
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_open_connection(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
char buf[256];
int cap;
bool posting = false, auth = true;
if (adata->status == NNTP_OK)
return 0;
if (adata->status == NNTP_BYE)
return -1;
adata->status = NNTP_NONE;
if (mutt_socket_open(conn) < 0)
return -1;
if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
return nntp_connect_error(adata);
if (mutt_str_startswith(buf, "200", CASE_MATCH))
posting = true;
else if (!mutt_str_startswith(buf, "201", CASE_MATCH))
{
mutt_socket_close(conn);
mutt_str_remove_trailing_ws(buf);
mutt_error("%s", buf);
return -1;
}
/* get initial capabilities */
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
/* tell news server to switch to mode reader if it isn't so */
if (cap > 0)
{
if ((mutt_socket_send(conn, "MODE READER\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (mutt_str_startswith(buf, "200", CASE_MATCH))
posting = true;
else if (mutt_str_startswith(buf, "201", CASE_MATCH))
posting = false;
/* error if has capabilities, ignore result if no capabilities */
else if (adata->hasCAPABILITIES)
{
mutt_socket_close(conn);
mutt_error(_("Could not switch to reader mode"));
return -1;
}
/* recheck capabilities after MODE READER */
if (adata->hasCAPABILITIES)
{
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
}
}
mutt_message(_("Connected to %s. %s"), conn->account.host,
posting ? _("Posting is ok") : _("Posting is NOT ok"));
mutt_sleep(1);
#ifdef USE_SSL
/* Attempt STARTTLS if available and desired. */
if ((adata->use_tls != 1) && (adata->hasSTARTTLS || C_SslForceTls))
{
if (adata->use_tls == 0)
{
adata->use_tls =
C_SslForceTls || query_quadoption(C_SslStarttls,
_("Secure connection with TLS?")) == MUTT_YES ?
2 :
1;
}
if (adata->use_tls == 2)
{
if ((mutt_socket_send(conn, "STARTTLS\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "382", CASE_MATCH))
{
adata->use_tls = 0;
mutt_error("STARTTLS: %s", buf);
}
else if (mutt_ssl_starttls(conn))
{
adata->use_tls = 0;
adata->status = NNTP_NONE;
mutt_socket_close(adata->conn);
mutt_error(_("Could not negotiate TLS connection"));
return -1;
}
else
{
/* recheck capabilities after STARTTLS */
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
}
}
}
#endif
/* authentication required? */
if (conn->account.flags & MUTT_ACCT_USER)
{
if (!conn->account.user[0])
auth = false;
}
else
{
if ((mutt_socket_send(conn, "STAT\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "480", CASE_MATCH))
auth = false;
}
/* authenticate */
if (auth && (nntp_auth(adata) < 0))
return -1;
/* get final capabilities after authentication */
if (adata->hasCAPABILITIES && (auth || (cap > 0)))
{
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
if (cap > 0)
{
mutt_socket_close(conn);
mutt_error(_("Could not switch to reader mode"));
return -1;
}
}
/* attempt features */
if (nntp_attempt_features(adata) < 0)
return -1;
adata->status = NNTP_OK;
return 0;
}
/**
* nntp_post - Post article
* @param m Mailbox
* @param msg Message to post
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_post(struct Mailbox *m, const char *msg)
{
struct NntpMboxData *mdata = NULL;
struct NntpMboxData tmp_mdata = { 0 };
char buf[1024];
if (m && (m->type == MUTT_NNTP))
mdata = m->mdata;
else
{
CurrentNewsSrv = nntp_select_server(m, C_NewsServer, false);
if (!CurrentNewsSrv)
return -1;
mdata = &tmp_mdata;
mdata->adata = CurrentNewsSrv;
mdata->group = NULL;
}
FILE *fp = mutt_file_fopen(msg, "r");
if (!fp)
{
mutt_perror(msg);
return -1;
}
mutt_str_strfcpy(buf, "POST\r\n", sizeof(buf));
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
{
mutt_file_fclose(&fp);
return -1;
}
if (buf[0] != '3')
{
mutt_error(_("Can't post article: %s"), buf);
mutt_file_fclose(&fp);
return -1;
}
buf[0] = '.';
buf[1] = '\0';
while (fgets(buf + 1, sizeof(buf) - 2, fp))
{
size_t len = strlen(buf);
if (buf[len - 1] == '\n')
{
buf[len - 1] = '\r';
buf[len] = '\n';
len++;
buf[len] = '\0';
}
if (mutt_socket_send_d(mdata->adata->conn, (buf[1] == '.') ? buf : buf + 1,
MUTT_SOCK_LOG_FULL) < 0)
{
mutt_file_fclose(&fp);
return nntp_connect_error(mdata->adata);
}
}
mutt_file_fclose(&fp);
if (((buf[strlen(buf) - 1] != '\n') &&
(mutt_socket_send_d(mdata->adata->conn, "\r\n", MUTT_SOCK_LOG_FULL) < 0)) ||
(mutt_socket_send_d(mdata->adata->conn, ".\r\n", MUTT_SOCK_LOG_FULL) < 0) ||
(mutt_socket_readln(buf, sizeof(buf), mdata->adata->conn) < 0))
{
return nntp_connect_error(mdata->adata);
}
if (buf[0] != '2')
{
mutt_error(_("Can't post article: %s"), buf);
return -1;
}
return 0;
}
/**
* nntp_active_fetch - Fetch list of all newsgroups from server
* @param adata NNTP server
* @param mark_new Mark the groups as new
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_active_fetch(struct NntpAccountData *adata, bool mark_new)
{
struct NntpMboxData tmp_mdata = { 0 };
char msg[256];
char buf[1024];
unsigned int i;
int rc;
snprintf(msg, sizeof(msg), _("Loading list of groups from server %s..."),
adata->conn->account.host);
mutt_message(msg);
if (nntp_date(adata, &adata->newgroups_time) < 0)
return -1;
tmp_mdata.adata = adata;
tmp_mdata.group = NULL;
i = adata->groups_num;
mutt_str_strfcpy(buf, "LIST\r\n", sizeof(buf));
rc = nntp_fetch_lines(&tmp_mdata, buf, sizeof(buf), msg, nntp_add_group, adata);
if (rc)
{
if (rc > 0)
{
mutt_error("LIST: %s", buf);
}
return -1;
}
if (mark_new)
{
for (; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
mdata->has_new_mail = true;
}
}
for (i = 0; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
if (mdata && mdata->deleted && !mdata->newsrc_ent)
{
nntp_delete_group_cache(mdata);
mutt_hash_delete(adata->groups_hash, mdata->group, NULL);
adata->groups_list[i] = NULL;
}
}
if (C_NntpLoadDescription)
rc = get_description(&tmp_mdata, "*", _("Loading descriptions..."));
nntp_active_save_cache(adata);
if (rc < 0)
return -1;
mutt_clear_error();
return 0;
}
/**
* nntp_check_new_groups - Check for new groups/articles in subscribed groups
* @param m Mailbox
* @param adata NNTP server
* @retval 1 New groups found
* @retval 0 No new groups
* @retval -1 Error
*/
int nntp_check_new_groups(struct Mailbox *m, struct NntpAccountData *adata)
{
struct NntpMboxData tmp_mdata = { 0 };
time_t now;
char buf[1024];
char *msg = _("Checking for new newsgroups...");
unsigned int i;
int rc, update_active = false;
if (!adata || !adata->newgroups_time)
return -1;
/* check subscribed newsgroups for new articles */
if (C_ShowNewNews)
{
mutt_message(_("Checking for new messages..."));
for (i = 0; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
if (mdata && mdata->subscribed)
{
rc = nntp_group_poll(mdata, true);
if (rc < 0)
return -1;
if (rc > 0)
update_active = true;
}
}
}
else if (adata->newgroups_time)
return 0;
/* get list of new groups */
mutt_message(msg);
if (nntp_date(adata, &now) < 0)
return -1;
tmp_mdata.adata = adata;
if (m && m->mdata)
tmp_mdata.group = ((struct NntpMboxData *) m->mdata)->group;
else
tmp_mdata.group = NULL;
i = adata->groups_num;
struct tm tm = mutt_date_gmtime(adata->newgroups_time);
snprintf(buf, sizeof(buf), "NEWGROUPS %02d%02d%02d %02d%02d%02d GMT\r\n",
tm.tm_year % 100, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
rc = nntp_fetch_lines(&tmp_mdata, buf, sizeof(buf), msg, nntp_add_group, adata);
if (rc)
{
if (rc > 0)
{
mutt_error("NEWGROUPS: %s", buf);
}
return -1;
}
/* new groups found */
rc = 0;
if (adata->groups_num != i)
{
int groups_num = i;
adata->newgroups_time = now;
for (; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
mdata->has_new_mail = true;
}
/* loading descriptions */
if (C_NntpLoadDescription)
{
unsigned int count = 0;
struct Progress progress;
mutt_progress_init(&progress, _("Loading descriptions..."),
MUTT_PROGRESS_READ, adata->groups_num - i);
for (i = groups_num; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
if (get_description(mdata, NULL, NULL) < 0)
return -1;
mutt_progress_update(&progress, ++count, -1);
}
}
update_active = true;
rc = 1;
}
if (update_active)
nntp_active_save_cache(adata);
mutt_clear_error();
return rc;
}
/**
* nntp_check_msgid - Fetch article by Message-ID
* @param m Mailbox
* @param msgid Message ID
* @retval 0 Success
* @retval 1 No such article
* @retval -1 Error
*/
int nntp_check_msgid(struct Mailbox *m, const char *msgid)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
char buf[1024];
FILE *fp = mutt_file_mkstemp();
if (!fp)
{
mutt_perror(_("Can't create temporary file"));
return -1;
}
snprintf(buf, sizeof(buf), "HEAD %s\r\n", msgid);
int rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_tempfile, fp);
if (rc)
{
mutt_file_fclose(&fp);
if (rc < 0)
return -1;
if (mutt_str_startswith(buf, "430", CASE_MATCH))
return 1;
mutt_error("HEAD: %s", buf);
return -1;
}
/* parse header */
if (m->msg_count == m->email_max)
mx_alloc_memory(m);
m->emails[m->msg_count] = email_new();
struct Email *e = m->emails[m->msg_count];
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
e->env = mutt_rfc822_read_header(fp, e, false, false);
mutt_file_fclose(&fp);
/* get article number */
if (e->env->xref)
nntp_parse_xref(m, e);
else
{
snprintf(buf, sizeof(buf), "STAT %s\r\n", msgid);
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
{
email_free(&e);
return -1;
}
sscanf(buf + 4, ANUM, &nntp_edata_get(e)->article_num);
}
/* reset flags */
e->read = false;
e->old = false;
e->deleted = false;
e->changed = true;
e->received = e->date_sent;
e->index = m->msg_count++;
mailbox_changed(m, NT_MAILBOX_INVALID);
return 0;
}
/**
* nntp_check_children - Fetch children of article with the Message-ID
* @param m Mailbox
* @param msgid Message ID to find
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_check_children(struct Mailbox *m, const char *msgid)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct ChildCtx cc;
char buf[256];
int rc;
void *hc = NULL;
if (!mdata || !mdata->adata)
return -1;
if (mdata->first_message > mdata->last_loaded)
return 0;
/* init context */
cc.mailbox = m;
cc.num = 0;
cc.max = 10;
cc.child = mutt_mem_malloc(sizeof(anum_t) * cc.max);
/* fetch numbers of child messages */
snprintf(buf, sizeof(buf), "XPAT References %u-%u *%s*\r\n",
mdata->first_message, mdata->last_loaded, msgid);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_children, &cc);
if (rc)
{
FREE(&cc.child);
if (rc > 0)
{
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
mutt_error("XPAT: %s", buf);
else
{
mutt_error(_("Unable to find child articles because server does not "
"support XPAT command"));
}
}
return -1;
}
/* fetch all found messages */
bool verbose = m->verbose;
m->verbose = false;
#ifdef USE_HCACHE
hc = nntp_hcache_open(mdata);
#endif
int old_msg_count = m->msg_count;
for (int i = 0; i < cc.num; i++)
{
rc = nntp_fetch_headers(m, hc, cc.child[i], cc.child[i], true);
if (rc < 0)
break;
}
if (m->msg_count > old_msg_count)
mailbox_changed(m, NT_MAILBOX_INVALID);
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
m->verbose = verbose;
FREE(&cc.child);
return (rc < 0) ? -1 : 0;
}
/**
* nntp_compare_order - Sort to mailbox order - Implements ::sort_t
*/
int nntp_compare_order(const void *a, const void *b)
{
const struct Email *ea = *(struct Email const *const *) a;
const struct Email *eb = *(struct Email const *const *) b;
anum_t na = nntp_edata_get((struct Email *) ea)->article_num;
anum_t nb = nntp_edata_get((struct Email *) eb)->article_num;
int result = (na == nb) ? 0 : (na > nb) ? 1 : -1;
result = perform_auxsort(result, a, b);
return SORT_CODE(result);
}
/**
* nntp_ac_find - Find an Account that matches a Mailbox path - Implements MxOps::ac_find()
*/
static struct Account *nntp_ac_find(struct Account *a, const char *path)
{
#if 0
if (!a || (a->type != MUTT_NNTP) || !path)
return NULL;
struct Url url = { 0 };
char tmp[PATH_MAX];
mutt_str_strfcpy(tmp, path, sizeof(tmp));
url_parse(&url, tmp);
struct ImapAccountData *adata = a->data;
struct ConnAccount *cac = &adata->conn_account;
if (mutt_str_strcasecmp(url.host, cac->host) != 0)
return NULL;
if (mutt_str_strcasecmp(url.user, cac->user) != 0)
return NULL;
// if (mutt_str_strcmp(path, a->mailbox->realpath) == 0)
// return a;
#endif
return a;
}
/**
* nntp_ac_add - Add a Mailbox to an Account - Implements MxOps::ac_add()
*/
static int nntp_ac_add(struct Account *a, struct Mailbox *m)
{
if (!a || !m || (m->type != MUTT_NNTP))
return -1;
return 0;
}
/**
* nntp_mbox_open - Open a Mailbox - Implements MxOps::mbox_open()
*/
static int nntp_mbox_open(struct Mailbox *m)
{
if (!m || !m->account)
return -1;
char buf[8192];
char server[1024];
char *group = NULL;
int rc;
void *hc = NULL;
anum_t first, last, count = 0;
struct Url *url = url_parse(mailbox_path(m));
if (!url || !url->host || !url->path ||
!((url->scheme == U_NNTP) || (url->scheme == U_NNTPS)))
{
url_free(&url);
mutt_error(_("%s is an invalid newsgroup specification"), mailbox_path(m));
return -1;
}
group = url->path;
if (group[0] == '/') /* Skip a leading '/' */
group++;
url->path = strchr(url->path, '\0');
url_tostring(url, server, sizeof(server), 0);
mutt_account_hook(m->realpath);
struct NntpAccountData *adata = m->account->adata;
if (!adata)
{
adata = nntp_select_server(m, server, true);
m->account->adata = adata;
m->account->adata_free = nntp_adata_free;
}
if (!adata)
{
url_free(&url);
return -1;
}
CurrentNewsSrv = adata;
m->msg_count = 0;
m->msg_unread = 0;
m->vcount = 0;
if (group[0] == '/')
group++;
/* find news group data structure */
struct NntpMboxData *mdata = mutt_hash_find(adata->groups_hash, group);
if (!mdata)
{
nntp_newsrc_close(adata);
mutt_error(_("Newsgroup %s not found on the server"), group);
url_free(&url);
return -1;
}
m->rights &= ~MUTT_ACL_INSERT; // Clear the flag
if (!mdata->newsrc_ent && !mdata->subscribed && !C_SaveUnsubscribed)
m->readonly = true;
/* select newsgroup */
mutt_message(_("Selecting %s..."), group);
url_free(&url);
buf[0] = '\0';
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
{
nntp_newsrc_close(adata);
return -1;
}
/* newsgroup not found, remove it */
if (mutt_str_startswith(buf, "411", CASE_MATCH))
{
mutt_error(_("Newsgroup %s has been removed from the server"), mdata->group);
if (!mdata->deleted)
{
mdata->deleted = true;
nntp_active_save_cache(adata);
}
if (mdata->newsrc_ent && !mdata->subscribed && !C_SaveUnsubscribed)
{
FREE(&mdata->newsrc_ent);
mdata->newsrc_len = 0;
nntp_delete_group_cache(mdata);
nntp_newsrc_update(adata);
}
}
/* parse newsgroup info */
else
{
if (sscanf(buf, "211 " ANUM " " ANUM " " ANUM, &count, &first, &last) != 3)
{
nntp_newsrc_close(adata);
mutt_error("GROUP: %s", buf);
return -1;
}
mdata->first_message = first;
mdata->last_message = last;
mdata->deleted = false;
/* get description if empty */
if (C_NntpLoadDescription && !mdata->desc)
{
if (get_description(mdata, NULL, NULL) < 0)
{
nntp_newsrc_close(adata);
return -1;
}
if (mdata->desc)
nntp_active_save_cache(adata);
}
}
adata->check_time = mutt_date_epoch();
m->mdata = mdata;
// Every known newsgroup has an mdata which is stored in adata->groups_list.
// Currently we don't let the Mailbox free the mdata.
// m->mdata_free = nntp_mdata_free;
if (!mdata->bcache && (mdata->newsrc_ent || mdata->subscribed || C_SaveUnsubscribed))
mdata->bcache = mutt_bcache_open(&adata->conn->account, mdata->group);
/* strip off extra articles if adding context is greater than $nntp_context */
first = mdata->first_message;
if (C_NntpContext && (mdata->last_message - first + 1 > C_NntpContext))
first = mdata->last_message - C_NntpContext + 1;
mdata->last_loaded = first ? first - 1 : 0;
count = mdata->first_message;
mdata->first_message = first;
nntp_bcache_update(mdata);
mdata->first_message = count;
#ifdef USE_HCACHE
hc = nntp_hcache_open(mdata);
nntp_hcache_update(mdata, hc);
#endif
if (!hc)
m->rights &= ~(MUTT_ACL_WRITE | MUTT_ACL_DELETE); // Clear the flags
nntp_newsrc_close(adata);
rc = nntp_fetch_headers(m, hc, first, mdata->last_message, false);
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (rc < 0)
return -1;
mdata->last_loaded = mdata->last_message;
adata->newsrc_modified = false;
return 0;
}
/**
* nntp_mbox_check - Check for new mail - Implements MxOps::mbox_check()
* @param m Mailbox
* @param index_hint Current message (UNUSED)
* @retval #MUTT_REOPENED Articles have been renumbered or removed from server
* @retval #MUTT_NEW_MAIL New articles found
* @retval 0 No change
* @retval -1 Lost connection
*/
static int nntp_mbox_check(struct Mailbox *m, int *index_hint)
{
if (!m)
return -1;
int rc = check_mailbox(m);
if (rc == 0)
{
struct NntpMboxData *mdata = m->mdata;
struct NntpAccountData *adata = mdata->adata;
nntp_newsrc_close(adata);
}
return rc;
}
/**
* nntp_mbox_sync - Save changes to the Mailbox - Implements MxOps::mbox_sync()
*
* @note May also return values from check_mailbox()
*/
static int nntp_mbox_sync(struct Mailbox *m, int *index_hint)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
int rc;
/* check for new articles */
mdata->adata->check_time = 0;
rc = check_mailbox(m);
if (rc)
return rc;
#ifdef USE_HCACHE
mdata->last_cached = 0;
header_cache_t *hc = nntp_hcache_open(mdata);
#endif
for (int i = 0; i < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
char buf[16];
snprintf(buf, sizeof(buf), ANUM, nntp_edata_get(e)->article_num);
if (mdata->bcache && e->deleted)
{
mutt_debug(LL_DEBUG2, "mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
#ifdef USE_HCACHE
if (hc && (e->changed || e->deleted))
{
if (e->deleted && !e->read)
mdata->unread--;
mutt_debug(LL_DEBUG2, "mutt_hcache_store %s\n", buf);
mutt_hcache_store(hc, buf, strlen(buf), e, 0);
}
#endif
}
#ifdef USE_HCACHE
if (hc)
{
mutt_hcache_close(hc);
mdata->last_cached = mdata->last_loaded;
}
#endif
/* save .newsrc entries */
nntp_newsrc_gen_entries(m);
nntp_newsrc_update(mdata->adata);
nntp_newsrc_close(mdata->adata);
return 0;
}
/**
* nntp_mbox_close - Close a Mailbox - Implements MxOps::mbox_close()
* @retval 0 Always
*/
static int nntp_mbox_close(struct Mailbox *m)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct NntpMboxData *tmp_mdata = NULL;
if (!mdata)
return 0;
mdata->unread = m->msg_unread;
nntp_acache_free(mdata);
if (!mdata->adata || !mdata->adata->groups_hash || !mdata->group)
return 0;
tmp_mdata = mutt_hash_find(mdata->adata->groups_hash, mdata->group);
if (!tmp_mdata || (tmp_mdata != mdata))
nntp_mdata_free((void **) &mdata);
return 0;
}
/**
* nntp_msg_open - Open an email message in a Mailbox - Implements MxOps::msg_open()
*/
static int nntp_msg_open(struct Mailbox *m, struct Message *msg, int msgno)
{
if (!m || !m->emails || (msgno >= m->msg_count) || !msg)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct Email *e = m->emails[msgno];
if (!e)
return -1;
char article[16];
/* try to get article from cache */
struct NntpAcache *acache = &mdata->acache[e->index % NNTP_ACACHE_LEN];
if (acache->path)
{
if (acache->index == e->index)
{
msg->fp = mutt_file_fopen(acache->path, "r");
if (msg->fp)
return 0;
}
/* clear previous entry */
else
{
unlink(acache->path);
FREE(&acache->path);
}
}
snprintf(article, sizeof(article), ANUM, nntp_edata_get(e)->article_num);
msg->fp = mutt_bcache_get(mdata->bcache, article);
if (msg->fp)
{
if (nntp_edata_get(e)->parsed)
return 0;
}
else
{
char buf[PATH_MAX];
/* don't try to fetch article from removed newsgroup */
if (mdata->deleted)
return -1;
/* create new cache file */
const char *fetch_msg = _("Fetching message...");
mutt_message(fetch_msg);
msg->fp = mutt_bcache_put(mdata->bcache, article);
if (!msg->fp)
{
mutt_mktemp(buf, sizeof(buf));
acache->path = mutt_str_strdup(buf);
acache->index = e->index;
msg->fp = mutt_file_fopen(acache->path, "w+");
if (!msg->fp)
{
mutt_perror(acache->path);
unlink(acache->path);
FREE(&acache->path);
return -1;
}
}
/* fetch message to cache file */
snprintf(buf, sizeof(buf), "ARTICLE %s\r\n",
nntp_edata_get(e)->article_num ? article : e->env->message_id);
const int rc =
nntp_fetch_lines(mdata, buf, sizeof(buf), fetch_msg, fetch_tempfile, msg->fp);
if (rc)
{
mutt_file_fclose(&msg->fp);
if (acache->path)
{
unlink(acache->path);
FREE(&acache->path);
}
if (rc > 0)
{
if (mutt_str_startswith(buf, nntp_edata_get(e)->article_num ? "423" : "430", CASE_MATCH))
{
mutt_error(_("Article %s not found on the server"),
nntp_edata_get(e)->article_num ? article : e->env->message_id);
}
else
mutt_error("ARTICLE: %s", buf);
}
return -1;
}
if (!acache->path)
mutt_bcache_commit(mdata->bcache, article);
}
/* replace envelope with new one
* hash elements must be updated because pointers will be changed */
if (m->id_hash && e->env->message_id)
mutt_hash_delete(m->id_hash, e->env->message_id, e);
if (m->subj_hash && e->env->real_subj)
mutt_hash_delete(m->subj_hash, e->env->real_subj, e);
mutt_env_free(&e->env);
e->env = mutt_rfc822_read_header(msg->fp, e, false, false);
if (m->id_hash && e->env->message_id)
mutt_hash_insert(m->id_hash, e->env->message_id, e);
if (m->subj_hash && e->env->real_subj)
mutt_hash_insert(m->subj_hash, e->env->real_subj, e);
/* fix content length */
fseek(msg->fp, 0, SEEK_END);
e->content->length = ftell(msg->fp) - e->content->offset;
/* this is called in neomutt before the open which fetches the message,
* which is probably wrong, but we just call it again here to handle
* the problem instead of fixing it */
nntp_edata_get(e)->parsed = true;
mutt_parse_mime_message(m, e);
/* these would normally be updated in ctx_update(), but the
* full headers aren't parsed with overview, so the information wasn't
* available then */
if (WithCrypto)
e->security = crypt_query(e->content);
rewind(msg->fp);
mutt_clear_error();
return 0;
}
/**
* nntp_msg_close - Close an email - Implements MxOps::msg_close()
*
* @note May also return EOF Failure, see errno
*/
static int nntp_msg_close(struct Mailbox *m, struct Message *msg)
{
return mutt_file_fclose(&msg->fp);
}
/**
* nntp_path_probe - Is this an NNTP Mailbox? - Implements MxOps::path_probe()
*/
enum MailboxType nntp_path_probe(const char *path, const struct stat *st)
{
if (!path)
return MUTT_UNKNOWN;
if (mutt_str_startswith(path, "news://", CASE_IGNORE))
return MUTT_NNTP;
if (mutt_str_startswith(path, "snews://", CASE_IGNORE))
return MUTT_NNTP;
return MUTT_UNKNOWN;
}
/**
* nntp_path_canon - Canonicalise a Mailbox path - Implements MxOps::path_canon()
*/
static int nntp_path_canon(char *buf, size_t buflen)
{
if (!buf)
return -1;
return 0;
}
/**
* nntp_path_pretty - Abbreviate a Mailbox path - Implements MxOps::path_pretty()
*/
static int nntp_path_pretty(char *buf, size_t buflen, const char *folder)
{
/* Succeed, but don't do anything, for now */
return 0;
}
/**
* nntp_path_parent - Find the parent of a Mailbox path - Implements MxOps::path_parent()
*/
static int nntp_path_parent(char *buf, size_t buflen)
{
/* Succeed, but don't do anything, for now */
return 0;
}
// clang-format off
/**
* MxNntpOps - NNTP Mailbox - Implements ::MxOps
*/
struct MxOps MxNntpOps = {
.type = MUTT_NNTP,
.name = "nntp",
.is_local = false,
.ac_find = nntp_ac_find,
.ac_add = nntp_ac_add,
.mbox_open = nntp_mbox_open,
.mbox_open_append = NULL,
.mbox_check = nntp_mbox_check,
.mbox_check_stats = NULL,
.mbox_sync = nntp_mbox_sync,
.mbox_close = nntp_mbox_close,
.msg_open = nntp_msg_open,
.msg_open_new = NULL,
.msg_commit = NULL,
.msg_close = nntp_msg_close,
.msg_padding_size = NULL,
.msg_save_hcache = NULL,
.tags_edit = NULL,
.tags_commit = NULL,
.path_probe = nntp_path_probe,
.path_canon = nntp_path_canon,
.path_pretty = nntp_path_pretty,
.path_parent = nntp_path_parent,
};
// clang-format on
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_4069_5 |
crossvul-cpp_data_good_1908_0 | /*
* Copyright © 2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
/* NOTE: This code was copied mostly as-is from xdg-desktop-portal */
#include <locale.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
#include <gio/gdesktopappinfo.h>
#include "flatpak-portal-dbus.h"
#include "flatpak-portal.h"
#include "flatpak-dir-private.h"
#include "flatpak-utils-private.h"
#include "flatpak-transaction.h"
#include "flatpak-installation-private.h"
#include "flatpak-instance-private.h"
#include "flatpak-portal-app-info.h"
#include "flatpak-portal-error.h"
#include "flatpak-utils-base-private.h"
#include "portal-impl.h"
#include "flatpak-permission-dbus.h"
/* GLib 2.47.92 was the first release to define these in gdbus-codegen */
#if !GLIB_CHECK_VERSION (2, 47, 92)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakSkeleton, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorSkeleton, g_object_unref)
#endif
#define IDLE_TIMEOUT_SECS 10 * 60
/* Should be roughly 2 seconds */
#define CHILD_STATUS_CHECK_ATTEMPTS 20
static GHashTable *client_pid_data_hash = NULL;
static GDBusConnection *session_bus = NULL;
static GNetworkMonitor *network_monitor = NULL;
static gboolean no_idle_exit = FALSE;
static guint name_owner_id = 0;
static GMainLoop *main_loop;
static PortalFlatpak *portal;
static gboolean opt_verbose;
static int opt_poll_timeout;
static gboolean opt_poll_when_metered;
static FlatpakSpawnSupportFlags supports = 0;
G_LOCK_DEFINE (update_monitors); /* This protects the three variables below */
static GHashTable *update_monitors;
static guint update_monitors_timeout = 0;
static gboolean update_monitors_timeout_running_thread = FALSE;
/* Poll all update monitors twice an hour */
#define DEFAULT_UPDATE_POLL_TIMEOUT_SEC (30 * 60)
#define PERMISSION_TABLE "flatpak"
#define PERMISSION_ID "updates"
/* Instance IDs are 32-bit unsigned integers */
#define INSTANCE_ID_BUFFER_SIZE 16
typedef enum { UNSET, ASK, YES, NO } Permission;
typedef enum {
PROGRESS_STATUS_RUNNING = 0,
PROGRESS_STATUS_EMPTY = 1,
PROGRESS_STATUS_DONE = 2,
PROGRESS_STATUS_ERROR = 3
} UpdateStatus;
static XdpDbusPermissionStore *permission_store;
typedef struct {
GMutex lock; /* This protects the closed, running and installed state */
gboolean closed;
gboolean running; /* While this is set, don't close the monitor */
gboolean installing;
char *sender;
char *obj_path;
GCancellable *cancellable;
/* Static data */
char *name;
char *arch;
char *branch;
char *commit;
char *app_path;
/* Last reported values, starting at the instance commit */
char *reported_local_commit;
char *reported_remote_commit;
} UpdateMonitorData;
static gboolean check_all_for_updates_cb (void *data);
static gboolean has_update_monitors (void);
static UpdateMonitorData *update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor);
static gboolean handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation);
static gboolean handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options);
static void
skeleton_died_cb (gpointer data)
{
g_debug ("skeleton finalized, exiting");
g_main_loop_quit (main_loop);
}
static gboolean
unref_skeleton_in_timeout_cb (gpointer user_data)
{
static gboolean unreffed = FALSE;
g_debug ("unreffing portal main ref");
if (!unreffed)
{
g_object_unref (portal);
unreffed = TRUE;
}
return G_SOURCE_REMOVE;
}
static void
unref_skeleton_in_timeout (void)
{
if (name_owner_id)
g_bus_unown_name (name_owner_id);
name_owner_id = 0;
/* After we've lost the name or idled we drop the main ref on the helper
so that we'll exit when it drops to zero. However, if there are
outstanding calls these will keep the refcount up during the
execution of them. We do the unref on a timeout to make sure
we're completely draining the queue of (stale) requests. */
g_timeout_add (500, unref_skeleton_in_timeout_cb, NULL);
}
static guint idle_timeout_id = 0;
static gboolean
idle_timeout_cb (gpointer user_data)
{
if (name_owner_id &&
g_hash_table_size (client_pid_data_hash) == 0 &&
!has_update_monitors ())
{
g_debug ("Idle - unowning name");
unref_skeleton_in_timeout ();
}
idle_timeout_id = 0;
return G_SOURCE_REMOVE;
}
G_LOCK_DEFINE_STATIC (idle);
static void
schedule_idle_callback (void)
{
G_LOCK (idle);
if (!no_idle_exit)
{
if (idle_timeout_id != 0)
g_source_remove (idle_timeout_id);
idle_timeout_id = g_timeout_add_seconds (IDLE_TIMEOUT_SECS, idle_timeout_cb, NULL);
}
G_UNLOCK (idle);
}
typedef struct
{
GPid pid;
char *client;
guint child_watch;
gboolean watch_bus;
gboolean expose_or_share_pids;
} PidData;
static void
pid_data_free (PidData *data)
{
g_free (data->client);
g_free (data);
}
static void
child_watch_died (GPid pid,
gint status,
gpointer user_data)
{
PidData *pid_data = user_data;
g_autoptr(GVariant) signal_variant = NULL;
g_debug ("Client Pid %d died", pid_data->pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, status));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnExited",
signal_variant,
NULL);
/* This frees the pid_data, so be careful */
g_hash_table_remove (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid));
/* This might have caused us to go to idle (zero children) */
schedule_idle_callback ();
}
typedef struct
{
int from;
int to;
int final;
} FdMapEntry;
typedef struct
{
FdMapEntry *fd_map;
int fd_map_len;
int instance_id_fd;
gboolean set_tty;
int tty;
int env_fd;
} ChildSetupData;
typedef struct
{
guint pid;
gchar buffer[INSTANCE_ID_BUFFER_SIZE];
} InstanceIdReadData;
typedef struct
{
FlatpakInstance *instance;
guint pid;
guint attempt;
} BwrapinfoWatcherData;
static void
bwrapinfo_watcher_data_free (BwrapinfoWatcherData* data)
{
g_object_unref (data->instance);
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (BwrapinfoWatcherData, bwrapinfo_watcher_data_free)
static int
get_child_pid_relative_to_parent_sandbox (int pid,
GError **error)
{
g_autofree char *status_file_path = NULL;
g_autoptr(GFile) status_file = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
int relative_pid = 0;
status_file_path = g_strdup_printf ("/proc/%u/status", pid);
status_file = g_file_new_for_path (status_file_path);
input_stream = g_file_read (status_file, NULL, error);
if (input_stream == NULL)
return 0;
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line_utf8 (data_stream, NULL, NULL, error);
if (line == NULL)
break;
g_strchug (line);
if (g_str_has_prefix (line, "NSpid:"))
{
g_auto(GStrv) fields = NULL;
guint nfields = 0;
char *endptr = NULL;
fields = g_strsplit (line, "\t", -1);
nfields = g_strv_length (fields);
if (nfields < 3)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"NSpid line has too few fields: %s", line);
return 0;
}
/* The second to last PID namespace is the one that spawned this process */
relative_pid = strtol (fields[nfields - 2], &endptr, 10);
if (*endptr)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"Invalid parent-relative PID in NSpid line: %s", line);
return 0;
}
return relative_pid;
}
}
if (*error == NULL)
/* EOF was reached while reading the file */
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "NSpid not found");
return 0;
}
static int
check_child_pid_status (void *user_data)
{
/* Stores a sequence of the time interval to use until the child PID is checked again.
In general from testing, bwrapinfo is never ready before 25ms have passed at minimum,
thus 25ms is the first interval, doubling until a max interval of 100ms is reached.
In addition, if the program is not available after 100ms for an extended period of time,
the timeout is further increased to a full second. */
static gint timeouts[] = {25, 50, 100};
g_autoptr(GVariant) signal_variant = NULL;
g_autoptr(BwrapinfoWatcherData) data = user_data;
PidData *pid_data;
guint pid;
int child_pid;
int relative_child_pid = 0;
pid = data->pid;
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (pid));
/* Process likely already exited if pid_data == NULL, so don't send the
signal to avoid an awkward out-of-order SpawnExited -> SpawnStarted. */
if (pid_data == NULL)
{
g_warning ("%u already exited, skipping SpawnStarted", pid);
return G_SOURCE_REMOVE;
}
child_pid = flatpak_instance_get_child_pid (data->instance);
if (child_pid == 0)
{
gint timeout;
gboolean readd_timer = FALSE;
if (data->attempt >= CHILD_STATUS_CHECK_ATTEMPTS)
/* If too many attempts, use a 1 second timeout */
timeout = 1000;
else
timeout = timeouts[MIN (data->attempt, G_N_ELEMENTS (timeouts) - 1)];
g_debug ("Failed to read child PID, trying again in %d ms", timeout);
/* The timer source only needs to be re-added if the timeout has changed,
which won't happen while staying on the 100 or 1000ms timeouts.
This test must happen *before* the attempt counter is incremented, since the
attempt counter represents the *current* timeout. */
readd_timer = data->attempt <= G_N_ELEMENTS (timeouts) || data->attempt == CHILD_STATUS_CHECK_ATTEMPTS;
data->attempt++;
/* Make sure the data isn't destroyed */
data = NULL;
if (readd_timer)
{
g_timeout_add (timeout, check_child_pid_status, user_data);
return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
/* Only send the child PID if it's exposed */
if (pid_data->expose_or_share_pids)
{
g_autoptr(GError) error = NULL;
relative_child_pid = get_child_pid_relative_to_parent_sandbox (child_pid, &error);
if (relative_child_pid == 0)
g_warning ("Failed to find relative PID for %d: %s", child_pid, error->message);
}
g_debug ("Emitting SpawnStarted(%u, %d)", pid, relative_child_pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, relative_child_pid));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnStarted",
signal_variant,
NULL);
return G_SOURCE_REMOVE;
}
static void
instance_id_read_finish (GObject *source,
GAsyncResult *res,
gpointer user_data)
{
g_autoptr(GInputStream) stream = NULL;
g_autofree InstanceIdReadData *data = NULL;
g_autoptr(FlatpakInstance) instance = NULL;
g_autoptr(GError) error = NULL;
BwrapinfoWatcherData *watcher_data = NULL;
gssize bytes_read;
stream = G_INPUT_STREAM (source);
data = (InstanceIdReadData *) user_data;
bytes_read = g_input_stream_read_finish (stream, res, &error);
if (bytes_read <= 0)
{
/* 0 means EOF, so the process could never have been started. */
if (bytes_read == -1)
g_warning ("Failed to read instance id: %s", error->message);
return;
}
data->buffer[bytes_read] = 0;
instance = flatpak_instance_new_for_id (data->buffer);
watcher_data = g_new0 (BwrapinfoWatcherData, 1);
watcher_data->instance = g_steal_pointer (&instance);
watcher_data->pid = data->pid;
check_child_pid_status (watcher_data);
}
static void
drop_cloexec (int fd)
{
fcntl (fd, F_SETFD, 0);
}
static void
child_setup_func (gpointer user_data)
{
ChildSetupData *data = (ChildSetupData *) user_data;
FdMapEntry *fd_map = data->fd_map;
sigset_t set;
int i;
flatpak_close_fds_workaround (3);
if (data->instance_id_fd != -1)
drop_cloexec (data->instance_id_fd);
if (data->env_fd != -1)
drop_cloexec (data->env_fd);
/* Unblock all signals */
sigemptyset (&set);
if (pthread_sigmask (SIG_SETMASK, &set, NULL) == -1)
{
g_warning ("Failed to unblock signals when starting child");
return;
}
/* Reset the handlers for all signals to their defaults. */
for (i = 1; i < NSIG; i++)
{
if (i != SIGSTOP && i != SIGKILL)
signal (i, SIG_DFL);
}
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from != fd_map[i].to)
{
dup2 (fd_map[i].from, fd_map[i].to);
close (fd_map[i].from);
}
}
/* Second pass in case we needed an in-between fd value to avoid conflicts */
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].to != fd_map[i].final)
{
dup2 (fd_map[i].to, fd_map[i].final);
close (fd_map[i].to);
}
/* Ensure we inherit the final fd value */
drop_cloexec (fd_map[i].final);
}
/* We become our own session and process group, because it never makes sense
to share the flatpak-session-helper dbus activated process group */
setsid ();
setpgid (0, 0);
if (data->set_tty)
{
/* data->tty is our from fd which is closed at this point.
* so locate the destination fd and use it for the ioctl.
*/
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from == data->tty)
{
if (ioctl (fd_map[i].final, TIOCSCTTY, 0) == -1)
g_debug ("ioctl(%d, TIOCSCTTY, 0) failed: %s",
fd_map[i].final, strerror (errno));
break;
}
}
}
}
static gboolean
is_valid_expose (const char *expose,
GError **error)
{
/* No subdirs or absolute paths */
if (expose[0] == '/')
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: absolute paths not allowed");
return FALSE;
}
else if (strchr (expose, '/'))
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: subdirectories not allowed");
return FALSE;
}
return TRUE;
}
static char *
filesystem_arg (const char *path,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
filesystem_sandbox_arg (const char *path,
const char *sandbox,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
g_string_append (s, "/sandbox/");
for (p = sandbox; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
bubblewrap_remap_path (const char *path)
{
if (g_str_has_prefix (path, "/newroot/"))
path = path + strlen ("/newroot");
return g_strdup (path);
}
static char *
verify_proc_self_fd (const char *proc_path,
GError **error)
{
char path_buffer[PATH_MAX + 1];
ssize_t symlink_size;
symlink_size = readlink (proc_path, path_buffer, PATH_MAX);
if (symlink_size < 0)
return glnx_null_throw_errno_prefix (error, "readlink");
path_buffer[symlink_size] = 0;
/* All normal paths start with /, but some weird things
don't, such as socket:[27345] or anon_inode:[eventfd].
We don't support any of these */
if (path_buffer[0] != '/')
return glnx_null_throw (error, "%s resolves to non-absolute path %s",
proc_path, path_buffer);
/* File descriptors to actually deleted files have " (deleted)"
appended to them. This also happens to some fake fd types
like shmem which are "/<name> (deleted)". All such
files are considered invalid. Unfortunatelly this also
matches files with filenames that actually end in " (deleted)",
but there is not much to do about this. */
if (g_str_has_suffix (path_buffer, " (deleted)"))
return glnx_null_throw (error, "%s resolves to deleted path %s",
proc_path, path_buffer);
/* remap from sandbox to host if needed */
return bubblewrap_remap_path (path_buffer);
}
static char *
get_path_for_fd (int fd,
gboolean *writable_out,
GError **error)
{
g_autofree char *proc_path = NULL;
int fd_flags;
struct stat st_buf;
struct stat real_st_buf;
g_autofree char *path = NULL;
gboolean writable = FALSE;
int read_access_mode;
/* Must be able to get fd flags */
fd_flags = fcntl (fd, F_GETFL);
if (fd_flags == -1)
return glnx_null_throw_errno_prefix (error, "fcntl F_GETFL");
/* Must be O_PATH */
if ((fd_flags & O_PATH) != O_PATH)
return glnx_null_throw (error, "not opened with O_PATH");
/* We don't want to allow exposing symlinks, because if they are
* under the callers control they could be changed between now and
* starting the child allowing it to point anywhere, so enforce NOFOLLOW.
* and verify that stat is not a link.
*/
if ((fd_flags & O_NOFOLLOW) != O_NOFOLLOW)
return glnx_null_throw (error, "not opened with O_NOFOLLOW");
/* Must be able to fstat */
if (fstat (fd, &st_buf) < 0)
return glnx_null_throw_errno_prefix (error, "fstat");
/* As per above, no symlinks */
if (S_ISLNK (st_buf.st_mode))
return glnx_null_throw (error, "is a symbolic link");
proc_path = g_strdup_printf ("/proc/self/fd/%d", fd);
/* Must be able to read valid path from /proc/self/fd */
/* This is an absolute and (at least at open time) symlink-expanded path */
path = verify_proc_self_fd (proc_path, error);
if (path == NULL)
return NULL;
/* Verify that this is the same file as the app opened */
if (stat (path, &real_st_buf) < 0 ||
st_buf.st_dev != real_st_buf.st_dev ||
st_buf.st_ino != real_st_buf.st_ino)
{
/* Different files on the inside and the outside, reject the request */
return glnx_null_throw (error,
"different file inside and outside sandbox");
}
read_access_mode = R_OK;
if (S_ISDIR (st_buf.st_mode))
read_access_mode |= X_OK;
/* Must be able to access the path via the sandbox supplied O_PATH fd,
which applies the sandbox side mount options (like readonly). */
if (access (proc_path, read_access_mode) != 0)
return glnx_null_throw (error, "not %s in sandbox",
read_access_mode & X_OK ? "accessible" : "readable");
if (access (proc_path, W_OK) == 0)
writable = TRUE;
*writable_out = writable;
return g_steal_pointer (&path);
}
static gboolean
handle_spawn (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GUnixFDList *fd_list,
const gchar *arg_cwd_path,
const gchar *const *arg_argv,
GVariant *arg_fds,
GVariant *arg_envs,
guint arg_flags,
GVariant *arg_options)
{
g_autoptr(GError) error = NULL;
ChildSetupData child_setup_data = { NULL };
GPid pid;
PidData *pid_data;
InstanceIdReadData *instance_id_read_data = NULL;
gsize i, j, n_fds, n_envs;
const gint *fds = NULL;
gint fds_len = 0;
g_autofree FdMapEntry *fd_map = NULL;
gchar **env;
gint32 max_fd;
GKeyFile *app_info;
g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);
g_autofree char *app_id = NULL;
g_autofree char *branch = NULL;
g_autofree char *arch = NULL;
g_autofree char *app_commit = NULL;
g_autofree char *runtime_ref = NULL;
g_auto(GStrv) runtime_parts = NULL;
g_autofree char *runtime_commit = NULL;
g_autofree char *instance_path = NULL;
g_auto(GStrv) extra_args = NULL;
g_auto(GStrv) shares = NULL;
g_auto(GStrv) sockets = NULL;
g_auto(GStrv) devices = NULL;
g_auto(GStrv) sandbox_expose = NULL;
g_auto(GStrv) sandbox_expose_ro = NULL;
g_autoptr(GVariant) sandbox_expose_fd = NULL;
g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;
g_autoptr(GOutputStream) instance_id_out_stream = NULL;
guint sandbox_flags = 0;
gboolean sandboxed;
gboolean expose_pids;
gboolean share_pids;
gboolean notify_start;
gboolean devel;
g_autoptr(GString) env_string = g_string_new ("");
child_setup_data.instance_id_fd = -1;
child_setup_data.env_fd = -1;
if (fd_list != NULL)
fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);
app_info = g_object_get_data (G_OBJECT (invocation), "app-info");
g_assert (app_info != NULL);
app_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, NULL);
g_assert (app_id != NULL);
g_debug ("spawn() called from app: '%s'", app_id);
if (*app_id == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (*arg_cwd_path == 0)
arg_cwd_path = NULL;
if (arg_argv == NULL || *arg_argv == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No command given");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_ref = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_RUNTIME, NULL);
if (runtime_ref == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"No runtime found");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_parts = g_strsplit (runtime_ref, "/", -1);
branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BRANCH, NULL);
instance_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);
arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_ARCH, NULL);
extra_args = g_key_file_get_string_list (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);
app_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_COMMIT, NULL);
runtime_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);
shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED, NULL, NULL);
sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);
devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);
devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_DEVEL, NULL);
g_variant_lookup (arg_options, "sandbox-expose", "^as", &sandbox_expose);
g_variant_lookup (arg_options, "sandbox-expose-ro", "^as", &sandbox_expose_ro);
g_variant_lookup (arg_options, "sandbox-flags", "u", &sandbox_flags);
sandbox_expose_fd = g_variant_lookup_value (arg_options, "sandbox-expose-fd", G_VARIANT_TYPE ("ah"));
sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, "sandbox-expose-fd-ro", G_VARIANT_TYPE ("ah"));
if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported sandbox flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_path == NULL &&
((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||
(sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose, caller has no instance path");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
{
const char *expose = sandbox_expose[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
g_debug ("Running spawn command %s", arg_argv[0]);
n_fds = 0;
if (fds != NULL)
n_fds = g_variant_n_children (arg_fds);
fd_map = g_new0 (FdMapEntry, n_fds);
child_setup_data.fd_map = fd_map;
child_setup_data.fd_map_len = n_fds;
max_fd = -1;
for (i = 0; i < n_fds; i++)
{
gint32 handle, dest_fd;
int handle_fd;
g_variant_get_child (arg_fds, i, "{uh}", &dest_fd, &handle);
if (handle >= fds_len || handle < 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
handle_fd = fds[handle];
fd_map[i].to = dest_fd;
fd_map[i].from = handle_fd;
fd_map[i].final = fd_map[i].to;
/* If stdin/out/err is a tty we try to set it as the controlling
tty for the app, this way we can use this to run in a terminal. */
if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&
!child_setup_data.set_tty &&
isatty (handle_fd))
{
child_setup_data.set_tty = TRUE;
child_setup_data.tty = handle_fd;
}
max_fd = MAX (max_fd, fd_map[i].to);
max_fd = MAX (max_fd, fd_map[i].from);
}
/* We make a second pass over the fds to find if any "to" fd index
overlaps an already in use fd (i.e. one in the "from" category
that are allocated randomly). If a fd overlaps "to" fd then its
a caller issue and not our fault, so we ignore that. */
for (i = 0; i < n_fds; i++)
{
int to_fd = fd_map[i].to;
gboolean conflict = FALSE;
/* At this point we're fine with using "from" values for this
value (because we handle to==from in the code), or values
that are before "i" in the fd_map (because those will be
closed at this point when dup:ing). However, we can't
reuse a fd that is in "from" for j > i. */
for (j = i + 1; j < n_fds; j++)
{
int from_fd = fd_map[j].from;
if (from_fd == to_fd)
{
conflict = TRUE;
break;
}
}
if (conflict)
fd_map[i].to = ++max_fd;
}
if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)
{
char *empty[] = { NULL };
env = g_strdupv (empty);
}
else
env = g_get_environ ();
n_envs = g_variant_n_children (arg_envs);
for (i = 0; i < n_envs; i++)
{
const char *var = NULL;
const char *val = NULL;
g_variant_get_child (arg_envs, i, "{&s&s}", &var, &val);
env = g_environ_setenv (env, var, val, TRUE);
}
g_ptr_array_add (flatpak_argv, g_strdup ("flatpak"));
g_ptr_array_add (flatpak_argv, g_strdup ("run"));
sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;
if (sandboxed)
{
g_ptr_array_add (flatpak_argv, g_strdup ("--sandbox"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "wayland"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=wayland"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "fallback-x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=fallback-x11"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=x11"));
if (shares != NULL && g_strv_contains ((const char * const *) shares, "ipc") &&
sockets != NULL && (g_strv_contains ((const char * const *) sockets, "fallback-x11") ||
g_strv_contains ((const char * const *) sockets, "x11")))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=ipc"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "pulseaudio"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=pulseaudio"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)
{
if (devices != NULL &&
(g_strv_contains ((const char * const *) devices, "dri") ||
g_strv_contains ((const char * const *) devices, "all")))
g_ptr_array_add (flatpak_argv, g_strdup ("--device=dri"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)
g_ptr_array_add (flatpak_argv, g_strdup ("--session-bus"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)
g_ptr_array_add (flatpak_argv, g_strdup ("--a11y-bus"));
}
else
{
for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)
{
if (g_str_has_prefix (extra_args[i], "--env="))
{
const char *var_val = extra_args[i] + strlen ("--env=");
if (var_val[0] == '\0' || var_val[0] == '=')
{
g_warning ("Environment variable in extra-args has empty name");
continue;
}
if (strchr (var_val, '=') == NULL)
{
g_warning ("Environment variable in extra-args has no value");
continue;
}
g_string_append (env_string, var_val);
g_string_append_c (env_string, '\0');
}
else
{
g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));
}
}
}
if (env_string->len > 0)
{
g_auto(GLnxTmpfile) env_tmpf = { 0, };
if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&env_tmpf, "environ",
env_string->str,
env_string->len, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
child_setup_data.env_fd = glnx_steal_fd (&env_tmpf.fd);
g_ptr_array_add (flatpak_argv,
g_strdup_printf ("--env-fd=%d",
child_setup_data.env_fd));
}
expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;
share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;
if (expose_pids || share_pids)
{
g_autofree char *instance_id = NULL;
int sender_pid1 = 0;
if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_NOT_SUPPORTED,
"Expose pids not supported with setuid bwrap");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
instance_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);
if (instance_id)
{
g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);
sender_pid1 = flatpak_instance_get_child_pid (instance);
}
if (sender_pid1 == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Could not find requesting pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--parent-pid=%d", sender_pid1));
if (share_pids)
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-share-pids"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-expose-pids"));
}
notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;
if (notify_start)
{
int pipe_fds[2];
if (pipe (pipe_fds) == -1)
{
int errsv = errno;
g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,
g_io_error_from_errno (errsv),
"Failed to create instance ID pipe: %s",
g_strerror (errsv));
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));
/* This is saved to ensure the portal's end gets closed after the exec. */
instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));
instance_id_read_data = g_new0 (InstanceIdReadData, 1);
g_input_stream_read_async (in_stream, instance_id_read_data->buffer,
INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,
instance_id_read_finish, instance_id_read_data);
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--instance-id-fd=%d", pipe_fds[1]));
child_setup_data.instance_id_fd = pipe_fds[1];
}
if (devel)
g_ptr_array_add (flatpak_argv, g_strdup ("--devel"));
/* Inherit launcher network access from launcher, unless
NO_NETWORK set. */
if (shares != NULL && g_strv_contains ((const char * const *) shares, "network") &&
!(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=network"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--unshare=network"));
if (instance_path)
{
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
}
if (sandbox_expose_fd != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
if (sandbox_expose_fd_ro != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd_ro);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd_ro, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime=%s", runtime_parts[1]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-version=%s", runtime_parts[3]));
if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)
{
if (app_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--commit=%s", app_commit));
if (runtime_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-commit=%s", runtime_commit));
}
if (arg_cwd_path != NULL)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--cwd=%s", arg_cwd_path));
if (arg_argv[0][0] != 0)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--command=%s", arg_argv[0]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("%s/%s/%s", app_id, arch ? arch : "", branch ? branch : ""));
for (i = 1; arg_argv[i] != NULL; i++)
g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));
g_ptr_array_add (flatpak_argv, NULL);
if (opt_verbose)
{
g_autoptr(GString) cmd = g_string_new ("");
for (i = 0; flatpak_argv->pdata[i] != NULL; i++)
{
if (i > 0)
g_string_append (cmd, " ");
g_string_append (cmd, flatpak_argv->pdata[i]);
}
g_debug ("Starting: %s\n", cmd->str);
}
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_async_with_pipes (NULL,
(char **) flatpak_argv->pdata,
env,
G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
child_setup_func, &child_setup_data,
&pid,
NULL,
NULL,
NULL,
&error))
{
gint code = G_DBUS_ERROR_FAILED;
if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))
code = G_DBUS_ERROR_ACCESS_DENIED;
else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))
code = G_DBUS_ERROR_FILE_NOT_FOUND;
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,
"Failed to start command: %s",
error->message);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_id_read_data)
instance_id_read_data->pid = pid;
pid_data = g_new0 (PidData, 1);
pid_data->pid = pid;
pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));
pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;
pid_data->expose_or_share_pids = (expose_pids || share_pids);
pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,
pid,
child_watch_died,
pid_data,
NULL);
g_debug ("Client Pid is %d", pid_data->pid);
g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),
pid_data);
portal_flatpak_complete_spawn (object, invocation, NULL, pid);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
handle_spawn_signal (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
guint arg_pid,
guint arg_signal,
gboolean arg_to_process_group)
{
PidData *pid_data = NULL;
g_debug ("spawn_signal(%d %d)", arg_pid, arg_signal);
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (arg_pid));
if (pid_data == NULL ||
strcmp (pid_data->client, g_dbus_method_invocation_get_sender (invocation)) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,
"No such pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_debug ("Sending signal %d to client pid %d", arg_signal, arg_pid);
if (arg_to_process_group)
killpg (pid_data->pid, arg_signal);
else
kill (pid_data->pid, arg_signal);
portal_flatpak_complete_spawn_signal (portal, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
authorize_method_handler (GDBusInterfaceSkeleton *interface,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
g_autoptr(GError) error = NULL;
g_autoptr(GKeyFile) keyfile = NULL;
g_autofree char *app_id = NULL;
const char *required_sender;
/* Ensure we don't idle exit */
schedule_idle_callback ();
required_sender = g_object_get_data (G_OBJECT (interface), "required-sender");
if (required_sender)
{
const char *sender = g_dbus_method_invocation_get_sender (invocation);
if (g_strcmp0 (required_sender, sender) != 0)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
"Client not allowed to access object");
return FALSE;
}
}
keyfile = flatpak_invocation_lookup_app_info (invocation, NULL, &error);
if (keyfile == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
app_id = g_key_file_get_string (keyfile,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, &error);
if (app_id == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
g_object_set_data_full (G_OBJECT (invocation), "app-info", g_steal_pointer (&keyfile), (GDestroyNotify) g_key_file_unref);
return TRUE;
}
static void
register_update_monitor (PortalFlatpakUpdateMonitor *monitor,
const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_insert (update_monitors, g_strdup (obj_path), g_object_ref (monitor));
/* Trigger update timeout if needed */
if (update_monitors_timeout == 0 && !update_monitors_timeout_running_thread)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
static void
unregister_update_monitor (const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_remove (update_monitors, obj_path);
G_UNLOCK (update_monitors);
}
static gboolean
has_update_monitors (void)
{
gboolean res;
G_LOCK (update_monitors);
res = g_hash_table_size (update_monitors) > 0;
G_UNLOCK (update_monitors);
return res;
}
static GList *
update_monitors_get_all (const char *optional_sender)
{
GList *list = NULL;
G_LOCK (update_monitors);
if (update_monitors)
{
GLNX_HASH_TABLE_FOREACH_V (update_monitors, PortalFlatpakUpdateMonitor *, monitor)
{
UpdateMonitorData *data = update_monitor_get_data (monitor);
if (optional_sender == NULL ||
strcmp (data->sender, optional_sender) == 0)
list = g_list_prepend (list, g_object_ref (monitor));
}
}
G_UNLOCK (update_monitors);
return list;
}
static void
update_monitor_data_free (gpointer data)
{
UpdateMonitorData *m = data;
g_mutex_clear (&m->lock);
g_free (m->sender);
g_free (m->obj_path);
g_object_unref (m->cancellable);
g_free (m->name);
g_free (m->arch);
g_free (m->branch);
g_free (m->commit);
g_free (m->app_path);
g_free (m->reported_local_commit);
g_free (m->reported_remote_commit);
g_free (m);
}
static UpdateMonitorData *
update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor)
{
return (UpdateMonitorData *)g_object_get_data (G_OBJECT (monitor), "update-monitor-data");
}
static PortalFlatpakUpdateMonitor *
create_update_monitor (GDBusMethodInvocation *invocation,
const char *obj_path,
GError **error)
{
PortalFlatpakUpdateMonitor *monitor;
UpdateMonitorData *m;
g_autoptr(GKeyFile) app_info = NULL;
g_autofree char *name = NULL;
app_info = flatpak_invocation_lookup_app_info (invocation, NULL, error);
if (app_info == NULL)
return NULL;
name = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
"name", NULL);
if (name == NULL || *name == 0)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
"Updates only supported by flatpak apps");
return NULL;
}
m = g_new0 (UpdateMonitorData, 1);
g_mutex_init (&m->lock);
m->obj_path = g_strdup (obj_path);
m->sender = g_strdup (g_dbus_method_invocation_get_sender (invocation));
m->cancellable = g_cancellable_new ();
m->name = g_steal_pointer (&name);
m->arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"arch", NULL);
m->branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"branch", NULL);
m->commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-commit", NULL);
m->app_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-path", NULL);
m->reported_local_commit = g_strdup (m->commit);
m->reported_remote_commit = g_strdup (m->commit);
monitor = portal_flatpak_update_monitor_skeleton_new ();
g_object_set_data_full (G_OBJECT (monitor), "update-monitor-data", m, update_monitor_data_free);
g_object_set_data_full (G_OBJECT (monitor), "required-sender", g_strdup (m->sender), g_free);
g_debug ("created UpdateMonitor for %s/%s at %s", m->name, m->branch, obj_path);
return monitor;
}
static void
update_monitor_do_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_dbus_interface_skeleton_unexport (G_DBUS_INTERFACE_SKELETON (monitor));
unregister_update_monitor (m->obj_path);
}
/* Always called in worker thread */
static void
update_monitor_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean do_close;
g_mutex_lock (&m->lock);
/* Close at most once, but not if running, if running it will be closed when that is done */
do_close = !m->closed && !m->running;
m->closed = TRUE;
g_mutex_unlock (&m->lock);
/* Always cancel though, so we can exit any running code early */
g_cancellable_cancel (m->cancellable);
if (do_close)
update_monitor_do_close (monitor);
}
static GDBusConnection *
update_monitor_get_connection (PortalFlatpakUpdateMonitor *monitor)
{
return g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (monitor));
}
static GHashTable *installation_cache = NULL;
static void
clear_installation_cache (void)
{
if (installation_cache != NULL)
g_hash_table_remove_all (installation_cache);
}
/* Caching lookup of Installation for a path */
static FlatpakInstallation *
lookup_installation_for_path (GFile *path, GError **error)
{
FlatpakInstallation *installation;
if (installation_cache == NULL)
installation_cache = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal, g_object_unref, g_object_unref);
installation = g_hash_table_lookup (installation_cache, path);
if (installation == NULL)
{
g_autoptr(FlatpakDir) dir = NULL;
dir = flatpak_dir_get_by_path (path);
installation = flatpak_installation_new_for_dir (dir, NULL, error);
if (installation == NULL)
return NULL;
flatpak_installation_set_no_interaction (installation, TRUE);
g_hash_table_insert (installation_cache, g_object_ref (path), installation);
}
return g_object_ref (installation);
}
static GFile *
update_monitor_get_installation_path (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) app_path = NULL;
app_path = g_file_new_for_path (m->app_path);
/* The app path is always 6 level deep inside the installation dir,
* like $dir/app/org.the.app/x86_64/stable/$commit/files, so we find
* the installation by just going up 6 parents. */
return g_file_resolve_relative_path (app_path, "../../../../../..");
}
static void
check_for_updates (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) installation_path = NULL;
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakInstalledRef) installed_ref = NULL;
g_autoptr(FlatpakRemoteRef) remote_ref = NULL;
const char *origin = NULL;
const char *local_commit = NULL;
const char *remote_commit;
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
const char *ref;
installation_path = update_monitor_get_installation_path (monitor);
g_debug ("Checking for updates for %s/%s/%s in %s", m->name, m->arch, m->branch, flatpak_file_get_path_cached (installation_path));
installation = lookup_installation_for_path (installation_path, &error);
if (installation == NULL)
{
g_debug ("Unable to find installation for path %s: %s", flatpak_file_get_path_cached (installation_path), error->message);
return;
}
installed_ref = flatpak_installation_get_installed_ref (installation,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (installed_ref == NULL)
{
g_debug ("getting installed ref failed: %s", error->message);
return; /* Never report updates for uninstalled refs */
}
dir = flatpak_installation_get_dir (installation, NULL);
if (dir == NULL)
return;
ref = flatpak_ref_format_ref_cached (FLATPAK_REF (installed_ref));
if (flatpak_dir_ref_is_masked (dir, ref))
return; /* Never report updates for masked refs */
local_commit = flatpak_ref_get_commit (FLATPAK_REF (installed_ref));
origin = flatpak_installed_ref_get_origin (installed_ref);
remote_ref = flatpak_installation_fetch_remote_ref_sync (installation, origin,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (remote_ref == NULL)
{
/* Probably some network issue.
* Fall back to the local_commit to at least be able to pick up already installed updates.
*/
g_debug ("getting remote ref failed: %s", error->message);
g_clear_error (&error);
remote_commit = local_commit;
}
else
{
remote_commit = flatpak_ref_get_commit (FLATPAK_REF (remote_ref));
if (remote_commit == NULL)
{
/* This can happen if we're offline and there is an update from an usb drive.
* Not much we can do in terms of reporting it, but at least handle the case
*/
g_debug ("Unknown remote commit, setting to local_commit");
remote_commit = local_commit;
}
}
if (g_strcmp0 (m->reported_local_commit, local_commit) != 0 ||
g_strcmp0 (m->reported_remote_commit, remote_commit) != 0)
{
GVariantBuilder builder;
gboolean is_closed;
g_free (m->reported_local_commit);
m->reported_local_commit = g_strdup (local_commit);
g_free (m->reported_remote_commit);
m->reported_remote_commit = g_strdup (remote_commit);
g_debug ("Found update for %s/%s/%s, local: %s, remote: %s", m->name, m->arch, m->branch, local_commit, remote_commit);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&builder, "{sv}", "running-commit", g_variant_new_string (m->commit));
g_variant_builder_add (&builder, "{sv}", "local-commit", g_variant_new_string (local_commit));
g_variant_builder_add (&builder, "{sv}", "remote-commit", g_variant_new_string (remote_commit));
/* Maybe someone closed the monitor while we were checking for updates, then drop the signal.
* There is still a minimal race between this check and the emit where a client could call close()
* and still see the signal though. */
g_mutex_lock (&m->lock);
is_closed = m->closed;
g_mutex_unlock (&m->lock);
if (!is_closed &&
!g_dbus_connection_emit_signal (update_monitor_get_connection (monitor),
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"UpdateAvailable",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit UpdateAvailable: %s", error->message);
g_clear_error (&error);
}
}
}
static void
check_all_for_updates_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *monitors, *l;
monitors = update_monitors_get_all (NULL);
for (l = monitors; l != NULL; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean was_closed = FALSE;
g_mutex_lock (&m->lock);
if (m->closed)
was_closed = TRUE;
else
m->running = TRUE;
g_mutex_unlock (&m->lock);
if (!was_closed)
{
check_for_updates (monitor);
g_mutex_lock (&m->lock);
m->running = FALSE;
if (m->closed) /* Was closed during running, do delayed close */
update_monitor_do_close (monitor);
g_mutex_unlock (&m->lock);
}
}
g_list_free_full (monitors, g_object_unref);
/* We want to cache stuff between multiple monitors
when a poll is scheduled, but there is no need to keep it
long term to the next poll, the in-memory is just
a waste of space then. */
clear_installation_cache ();
G_LOCK (update_monitors);
update_monitors_timeout_running_thread = FALSE;
if (g_hash_table_size (update_monitors) > 0)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
/* Runs on main thread */
static gboolean
check_all_for_updates_cb (void *data)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
if (!opt_poll_when_metered &&
g_network_monitor_get_network_metered (network_monitor))
{
g_debug ("Skipping update check on metered network");
return G_SOURCE_CONTINUE;
}
g_debug ("Checking all update monitors");
G_LOCK (update_monitors);
update_monitors_timeout = 0;
update_monitors_timeout_running_thread = TRUE;
G_UNLOCK (update_monitors);
g_task_run_in_thread (task, check_all_for_updates_in_thread_func);
return G_SOURCE_REMOVE; /* This will be re-added by the thread when done */
}
/* Runs in worker thread */
static gboolean
handle_create_update_monitor (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GVariant *options)
{
GDBusConnection *connection = g_dbus_method_invocation_get_connection (invocation);
g_autoptr(PortalFlatpakUpdateMonitorSkeleton) monitor = NULL;
const char *sender;
g_autofree char *sender_escaped = NULL;
g_autofree char *obj_path = NULL;
g_autofree char *token = NULL;
g_autoptr(GError) error = NULL;
int i;
if (!g_variant_lookup (options, "handle_token", "s", &token))
token = g_strdup_printf ("%d", g_random_int_range (0, 1000));
sender = g_dbus_method_invocation_get_sender (invocation);
g_debug ("handle CreateUpdateMonitor from %s", sender);
sender_escaped = g_strdup (sender + 1);
for (i = 0; sender_escaped[i]; i++)
{
if (sender_escaped[i] == '.')
sender_escaped[i] = '_';
}
obj_path = g_strdup_printf ("/org/freedesktop/portal/Flatpak/update_monitor/%s/%s",
sender_escaped,
token);
monitor = (PortalFlatpakUpdateMonitorSkeleton *) create_update_monitor (invocation, obj_path, &error);
if (monitor == NULL)
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_signal_connect (monitor, "handle-close", G_CALLBACK (handle_close), NULL);
g_signal_connect (monitor, "handle-update", G_CALLBACK (handle_update), NULL);
g_signal_connect (monitor, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (monitor),
connection,
obj_path,
&error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
register_update_monitor ((PortalFlatpakUpdateMonitor*)monitor, obj_path);
portal_flatpak_complete_create_update_monitor (portal, invocation, obj_path);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
/* Runs in worker thread */
static gboolean
handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation)
{
update_monitor_close (monitor);
g_debug ("handle UpdateMonitor.Close");
portal_flatpak_update_monitor_complete_close (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
deep_free_object_list (gpointer data)
{
g_list_free_full ((GList *)data, g_object_unref);
}
static void
close_update_monitors_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *list = task_data;
GList *l;
for (l = list; l; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_debug ("closing monitor %s", m->obj_path);
update_monitor_close (monitor);
}
}
static void
close_update_monitors_for_sender (const char *sender)
{
GList *list = update_monitors_get_all (sender);
if (list)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
g_task_set_task_data (task, list, deep_free_object_list);
g_debug ("%s dropped off the bus, closing monitors", sender);
g_task_run_in_thread (task, close_update_monitors_in_thread_func);
}
}
static guint32
get_update_permission (const char *app_id)
{
g_autoptr(GVariant) out_perms = NULL;
g_autoptr(GVariant) out_data = NULL;
g_autoptr(GError) error = NULL;
guint32 ret = UNSET;
if (permission_store == NULL)
{
g_debug ("No portals installed, assume no permissions");
return NO;
}
if (!xdp_dbus_permission_store_call_lookup_sync (permission_store,
PERMISSION_TABLE,
PERMISSION_ID,
&out_perms,
&out_data,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_debug ("No updates permissions found: %s", error->message);
g_clear_error (&error);
}
if (out_perms != NULL)
{
const char **perms;
if (g_variant_lookup (out_perms, app_id, "^a&s", &perms))
{
if (strcmp (perms[0], "ask") == 0)
ret = ASK;
else if (strcmp (perms[0], "yes") == 0)
ret = YES;
else
ret = NO;
}
}
g_debug ("Updates permissions for %s: %d", app_id, ret);
return ret;
}
static void
set_update_permission (const char *app_id,
Permission permission)
{
g_autoptr(GError) error = NULL;
const char *permissions[2];
if (permission == ASK)
permissions[0] = "ask";
else if (permission == YES)
permissions[0] = "yes";
else if (permission == NO)
permissions[0] = "no";
else
{
g_warning ("Wrong permission format, ignoring");
return;
}
permissions[1] = NULL;
if (!xdp_dbus_permission_store_call_set_permission_sync (permission_store,
PERMISSION_TABLE,
TRUE,
PERMISSION_ID,
app_id,
(const char * const*)permissions,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_info ("Error updating permission store: %s", error->message);
}
}
static char *
get_app_display_name (const char *app_id)
{
g_autofree char *id = NULL;
g_autoptr(GDesktopAppInfo) info = NULL;
const char *name = NULL;
id = g_strconcat (app_id, ".desktop", NULL);
info = g_desktop_app_info_new (id);
if (info)
{
name = g_app_info_get_display_name (G_APP_INFO (info));
if (name)
return g_strdup (name);
}
return g_strdup (app_id);
}
static gboolean
request_update_permissions_sync (PortalFlatpakUpdateMonitor *monitor,
const char *app_id,
const char *window,
GError **error)
{
Permission permission;
permission = get_update_permission (app_id);
if (permission == UNSET || permission == ASK)
{
guint access_response = 2;
PortalImplementation *access_impl;
GVariantBuilder access_opt_builder;
g_autofree char *app_name = NULL;
g_autofree char *title = NULL;
g_autoptr(GVariant) ret = NULL;
access_impl = find_portal_implementation ("org.freedesktop.impl.portal.Access");
if (access_impl == NULL)
{
g_warning ("No Access portal implementation found");
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED, _("No portal support found"));
return FALSE;
}
g_variant_builder_init (&access_opt_builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&access_opt_builder, "{sv}",
"deny_label", g_variant_new_string (_("Deny")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"grant_label", g_variant_new_string (_("Update")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"icon", g_variant_new_string ("package-x-generic-symbolic"));
app_name = get_app_display_name (app_id);
title = g_strdup_printf (_("Update %s?"), app_name);
ret = g_dbus_connection_call_sync (update_monitor_get_connection (monitor),
access_impl->dbus_name,
"/org/freedesktop/portal/desktop",
"org.freedesktop.impl.portal.Access",
"AccessDialog",
g_variant_new ("(osssssa{sv})",
"/request/path",
app_id,
window,
title,
_("The application wants to update itself."),
_("Update access can be changed any time from the privacy settings."),
&access_opt_builder),
G_VARIANT_TYPE ("(ua{sv})"),
G_DBUS_CALL_FLAGS_NONE,
G_MAXINT,
NULL,
error);
if (ret == NULL)
{
g_dbus_error_strip_remote_error (*error);
g_warning ("Failed to show access dialog: %s", (*error)->message);
return FALSE;
}
g_variant_get (ret, "(ua{sv})", &access_response, NULL);
if (permission == UNSET)
set_update_permission (app_id, (access_response == 0) ? YES : NO);
permission = (access_response == 0) ? YES : NO;
}
if (permission == NO)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
_("Application update not allowed"));
return FALSE;
}
return TRUE;
}
static void
emit_progress (PortalFlatpakUpdateMonitor *monitor,
int op,
int n_ops,
int progress,
int status,
const char *error_name,
const char *error_message)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
GDBusConnection *connection;
GVariantBuilder builder;
g_autoptr(GError) error = NULL;
g_debug ("%d/%d ops, progress %d, status: %d", op, n_ops, progress, status);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
if (n_ops > 0)
{
g_variant_builder_add (&builder, "{sv}", "op", g_variant_new_uint32 (op));
g_variant_builder_add (&builder, "{sv}", "n_ops", g_variant_new_uint32 (n_ops));
g_variant_builder_add (&builder, "{sv}", "progress", g_variant_new_uint32 (progress));
}
g_variant_builder_add (&builder, "{sv}", "status", g_variant_new_uint32 (status));
if (error_name)
{
g_variant_builder_add (&builder, "{sv}", "error", g_variant_new_string (error_name));
g_variant_builder_add (&builder, "{sv}", "error_message", g_variant_new_string (error_message));
}
connection = update_monitor_get_connection (monitor);
if (!g_dbus_connection_emit_signal (connection,
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"Progress",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit ::progress: %s", error->message);
}
}
static char *
get_progress_error (const GError *update_error)
{
g_autofree gchar *name = NULL;
name = g_dbus_error_encode_gerror (update_error);
/* Don't return weird dbus wrapped things from the portal */
if (g_str_has_prefix (name, "org.gtk.GDBus.UnmappedGError.Quark"))
return g_strdup ("org.freedesktop.DBus.Error.Failed");
return g_steal_pointer (&name);
}
static void
emit_progress_error (PortalFlatpakUpdateMonitor *monitor,
GError *update_error)
{
g_autofree gchar *error_name = get_progress_error (update_error);
emit_progress (monitor, 0, 0, 0,
PROGRESS_STATUS_ERROR,
error_name, update_error->message);
}
static void
send_variant (GVariant *v, GOutputStream *out)
{
g_autoptr(GError) error = NULL;
const guchar *data;
gsize size;
guint32 size32;
data = g_variant_get_data (v);
size = g_variant_get_size (v);
size32 = size;
if (!g_output_stream_write_all (out, &size32, 4, NULL, NULL, &error) ||
!g_output_stream_write_all (out, data, size, NULL, NULL, &error))
{
g_warning ("sending to parent failed: %s", error->message);
exit (1); // This will exit the child process and cause the parent to report an error
}
}
static void
send_progress (GOutputStream *out,
int op,
int n_ops,
int progress,
int status,
const GError *update_error)
{
g_autoptr(GVariant) v = NULL;
g_autofree gchar *error_name = NULL;
if (update_error)
error_name = get_progress_error (update_error);
v = g_variant_ref_sink (g_variant_new ("(uuuuss)",
op, n_ops, progress, status,
error_name ? error_name : "",
update_error ? update_error->message : ""));
send_variant (v, out);
}
typedef struct {
GOutputStream *out;
int n_ops;
int op;
int progress;
gboolean saw_first_operation;
} TransactionData;
static gboolean
transaction_ready (FlatpakTransaction *transaction,
TransactionData *d)
{
GList *ops = flatpak_transaction_get_operations (transaction);
int status;
GList *l;
d->n_ops = g_list_length (ops);
d->op = 0;
d->progress = 0;
for (l = ops; l != NULL; l = l->next)
{
FlatpakTransactionOperation *op = l->data;
const char *ref = flatpak_transaction_operation_get_ref (op);
FlatpakTransactionOperationType type = flatpak_transaction_operation_get_operation_type (op);
/* Actual app updates need to not increase premission requirements */
if (type == FLATPAK_TRANSACTION_OPERATION_UPDATE && g_str_has_prefix (ref, "app/"))
{
GKeyFile *new_metadata = flatpak_transaction_operation_get_metadata (op);
GKeyFile *old_metadata = flatpak_transaction_operation_get_old_metadata (op);
g_autoptr(FlatpakContext) new_context = flatpak_context_new ();
g_autoptr(FlatpakContext) old_context = flatpak_context_new ();
if (!flatpak_context_load_metadata (new_context, new_metadata, NULL) ||
!flatpak_context_load_metadata (old_context, old_metadata, NULL) ||
flatpak_context_adds_permissions (old_context, new_context))
{
g_autoptr(GError) error = NULL;
g_set_error (&error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
_("Self update not supported, new version requires new permissions"));
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE;
}
}
}
if (flatpak_transaction_is_empty (transaction))
status = PROGRESS_STATUS_EMPTY;
else
status = PROGRESS_STATUS_RUNNING;
send_progress (d->out,
d->op, d->n_ops,
d->progress, status,
NULL);
if (status == PROGRESS_STATUS_EMPTY)
return FALSE; /* This will cause us to return an ABORTED error */
return TRUE;
}
static void
transaction_progress_changed (FlatpakTransactionProgress *progress,
TransactionData *d)
{
/* Only report 100 when really done */
d->progress = MIN (flatpak_transaction_progress_get_progress (progress), 99);
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
transaction_new_operation (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
FlatpakTransactionProgress *progress,
TransactionData *d)
{
d->progress = 0;
if (d->saw_first_operation)
d->op++;
else
d->saw_first_operation = TRUE;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
g_signal_connect (progress, "changed", G_CALLBACK (transaction_progress_changed), d);
}
static gboolean
transaction_operation_error (FlatpakTransaction *transaction,
FlatpakTransactionOperation *operation,
const GError *error,
FlatpakTransactionErrorDetails detail,
TransactionData *d)
{
gboolean non_fatal = (detail & FLATPAK_TRANSACTION_ERROR_DETAILS_NON_FATAL) != 0;
if (non_fatal)
return TRUE; /* Continue */
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE; /* This will cause us to return an ABORTED error */
}
static void
transaction_operation_done (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
const char *commit,
FlatpakTransactionResult result,
TransactionData *d)
{
d->progress = 100;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
update_child_setup_func (gpointer user_data)
{
int *socket = user_data;
dup2 (*socket, 3);
flatpak_close_fds_workaround (4);
}
/* This is the meat of the update process, its run out of process (via
spawn) to avoid running lots of complicated code in the portal
process and possibly long-term leaks in a long-running process. */
static int
do_update_child_process (const char *installation_path, const char *ref, int socket_fd)
{
g_autoptr(GOutputStream) out = g_unix_output_stream_new (socket_fd, TRUE);
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakTransaction) transaction = NULL;
g_autoptr(GFile) f = g_file_new_for_path (installation_path);
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
TransactionData transaction_data = { NULL };
dir = flatpak_dir_get_by_path (f);
if (!flatpak_dir_maybe_ensure_repo (dir, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
installation = flatpak_installation_new_for_dir (dir, NULL, &error);
if (installation)
transaction = flatpak_transaction_new_for_installation (installation, NULL, &error);
if (transaction == NULL)
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
flatpak_transaction_add_default_dependency_sources (transaction);
if (!flatpak_transaction_add_update (transaction, ref, NULL, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
transaction_data.out = out;
g_signal_connect (transaction, "ready", G_CALLBACK (transaction_ready), &transaction_data);
g_signal_connect (transaction, "new-operation", G_CALLBACK (transaction_new_operation), &transaction_data);
g_signal_connect (transaction, "operation-done", G_CALLBACK (transaction_operation_done), &transaction_data);
g_signal_connect (transaction, "operation-error", G_CALLBACK (transaction_operation_error), &transaction_data);
if (!flatpak_transaction_run (transaction, NULL, &error))
{
if (!g_error_matches (error, FLATPAK_ERROR, FLATPAK_ERROR_ABORTED)) /* If aborted we already sent error */
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_ERROR, error);
return 0;
}
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_DONE, error);
return 0;
}
static GVariant *
read_variant (GInputStream *in,
GCancellable *cancellable,
GError **error)
{
guint32 size;
guchar *data;
gsize bytes_read;
if (!g_input_stream_read_all (in, &size, 4, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != 4)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
data = g_try_malloc (size);
if (data == NULL)
{
flatpak_fail (error, "Out of memory");
return NULL;
}
if (!g_input_stream_read_all (in, data, size, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != size)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
return g_variant_ref_sink (g_variant_new_from_data (G_VARIANT_TYPE("(uuuuss)"),
data, size, FALSE, g_free, data));
}
/* We do the actual update out of process (in do_update_child_process,
via spawn) and just proxy the feedback here */
static gboolean
handle_update_responses (PortalFlatpakUpdateMonitor *monitor,
int socket_fd,
GError **error)
{
g_autoptr(GInputStream) in = g_unix_input_stream_new (socket_fd, FALSE); /* Closed by parent */
UpdateMonitorData *m = update_monitor_get_data (monitor);
guint32 status;
do
{
g_autoptr(GVariant) v = NULL;
guint32 op;
guint32 n_ops;
guint32 progress;
const char *error_name;
const char *error_message;
v = read_variant (in, m->cancellable, error);
if (v == NULL)
{
g_debug ("Reading message from child update process failed %s", (*error)->message);
return FALSE;
}
g_variant_get (v, "(uuuu&s&s)",
&op, &n_ops, &progress, &status, &error_name, &error_message);
emit_progress (monitor, op, n_ops, progress, status,
*error_name != 0 ? error_name : NULL,
*error_message != 0 ? error_message : NULL);
}
while (status == PROGRESS_STATUS_RUNNING);
/* Don't return an received error as we emited it already, that would cause it to be emitted twice */
return TRUE;
}
static void
handle_update_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
PortalFlatpakUpdateMonitor *monitor = source_object;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GError) error = NULL;
const char *window;
window = (const char *)g_object_get_data (G_OBJECT (task), "window");
if (request_update_permissions_sync (monitor, m->name, window, &error))
{
g_autoptr(GFile) installation_path = update_monitor_get_installation_path (monitor);
g_autofree char *ref = flatpak_build_app_ref (m->name, m->branch, m->arch);
const char *argv[] = { "/proc/self/exe", "flatpak-portal", "--update", flatpak_file_get_path_cached (installation_path), ref, NULL };
int sockets[2];
GPid pid;
if (socketpair (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sockets) != 0)
{
glnx_throw_errno (&error);
}
else
{
gboolean spawn_ok;
spawn_ok = g_spawn_async (NULL, (char **)argv, NULL,
G_SPAWN_FILE_AND_ARGV_ZERO |
G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
update_child_setup_func, &sockets[1],
&pid, &error);
close (sockets[1]); // Close remote side
if (spawn_ok)
{
if (!handle_update_responses (monitor, sockets[0], &error))
{
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
kill (pid, SIGINT);
}
}
close (sockets[0]); // Close local side
}
}
if (error)
emit_progress_error (monitor, error);
g_mutex_lock (&m->lock);
m->installing = FALSE;
g_mutex_unlock (&m->lock);
}
static gboolean
handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GTask) task = NULL;
gboolean already_installing = FALSE;
g_debug ("handle UpdateMonitor.Update");
g_mutex_lock (&m->lock);
if (m->installing)
already_installing = TRUE;
else
m->installing = TRUE;
g_mutex_unlock (&m->lock);
if (already_installing)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR,
G_DBUS_ERROR_FAILED,
"Already installing");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
task = g_task_new (monitor, NULL, NULL, NULL);
g_object_set_data_full (G_OBJECT (task), "window", g_strdup (arg_window), g_free);
g_task_run_in_thread (task, handle_update_in_thread_func);
portal_flatpak_update_monitor_complete_update (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
name_owner_changed (GDBusConnection *connection,
const gchar *sender_name,
const gchar *object_path,
const gchar *interface_name,
const gchar *signal_name,
GVariant *parameters,
gpointer user_data)
{
const char *name, *from, *to;
g_variant_get (parameters, "(&s&s&s)", &name, &from, &to);
if (name[0] == ':' &&
strcmp (name, from) == 0 &&
strcmp (to, "") == 0)
{
GHashTableIter iter;
PidData *pid_data = NULL;
gpointer value = NULL;
GList *list = NULL, *l;
g_hash_table_iter_init (&iter, client_pid_data_hash);
while (g_hash_table_iter_next (&iter, NULL, &value))
{
pid_data = value;
if (pid_data->watch_bus && g_str_equal (pid_data->client, name))
list = g_list_prepend (list, pid_data);
}
for (l = list; l; l = l->next)
{
pid_data = l->data;
g_debug ("%s dropped off the bus, killing %d", pid_data->client, pid_data->pid);
killpg (pid_data->pid, SIGINT);
}
g_list_free (list);
close_update_monitors_for_sender (name);
}
}
#define DBUS_NAME_DBUS "org.freedesktop.DBus"
#define DBUS_INTERFACE_DBUS DBUS_NAME_DBUS
#define DBUS_PATH_DBUS "/org/freedesktop/DBus"
static gboolean
supports_expose_pids (void)
{
const char *path = g_find_program_in_path (flatpak_get_bwrap ());
struct stat st;
/* This is supported only if bwrap exists and is not setuid */
return
path != NULL &&
stat (path, &st) == 0 &&
(st.st_mode & S_ISUID) == 0;
}
static void
on_bus_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
GError *error = NULL;
g_debug ("Bus acquired, creating skeleton");
g_dbus_connection_set_exit_on_close (connection, FALSE);
update_monitors = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
permission_store = xdp_dbus_permission_store_proxy_new_sync (connection,
G_DBUS_PROXY_FLAGS_NONE,
"org.freedesktop.impl.portal.PermissionStore",
"/org/freedesktop/impl/portal/PermissionStore",
NULL, NULL);
portal = portal_flatpak_skeleton_new ();
g_dbus_connection_signal_subscribe (connection,
DBUS_NAME_DBUS,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged",
DBUS_PATH_DBUS,
NULL,
G_DBUS_SIGNAL_FLAGS_NONE,
name_owner_changed,
NULL, NULL);
g_object_set_data_full (G_OBJECT (portal), "track-alive", GINT_TO_POINTER (42), skeleton_died_cb);
g_dbus_interface_skeleton_set_flags (G_DBUS_INTERFACE_SKELETON (portal),
G_DBUS_INTERFACE_SKELETON_FLAGS_HANDLE_METHOD_INVOCATIONS_IN_THREAD);
portal_flatpak_set_version (PORTAL_FLATPAK (portal), 5);
portal_flatpak_set_supports (PORTAL_FLATPAK (portal), supports);
g_signal_connect (portal, "handle-spawn", G_CALLBACK (handle_spawn), NULL);
g_signal_connect (portal, "handle-spawn-signal", G_CALLBACK (handle_spawn_signal), NULL);
g_signal_connect (portal, "handle-create-update-monitor", G_CALLBACK (handle_create_update_monitor), NULL);
g_signal_connect (portal, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (portal),
connection,
"/org/freedesktop/portal/Flatpak",
&error))
{
g_warning ("error: %s", error->message);
g_error_free (error);
}
}
static void
on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name acquired");
}
static void
on_name_lost (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name lost");
unref_skeleton_in_timeout ();
}
static void
binary_file_changed_cb (GFileMonitor *file_monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
gpointer data)
{
static gboolean got_it = FALSE;
if (!got_it)
{
g_debug ("binary file changed");
unref_skeleton_in_timeout ();
}
got_it = TRUE;
}
static void
message_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data)
{
/* Make this look like normal console output */
if (log_level & G_LOG_LEVEL_DEBUG)
g_printerr ("F: %s\n", message);
else
g_printerr ("%s: %s\n", g_get_prgname (), message);
}
int
main (int argc,
char **argv)
{
gchar exe_path[PATH_MAX + 1];
ssize_t exe_path_len;
gboolean replace;
gboolean show_version;
GOptionContext *context;
GBusNameOwnerFlags flags;
g_autoptr(GError) error = NULL;
const GOptionEntry options[] = {
{ "replace", 'r', 0, G_OPTION_ARG_NONE, &replace, "Replace old daemon.", NULL },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &opt_verbose, "Enable debug output.", NULL },
{ "version", 0, 0, G_OPTION_ARG_NONE, &show_version, "Show program version.", NULL},
{ "no-idle-exit", 0, 0, G_OPTION_ARG_NONE, &no_idle_exit, "Don't exit when idle.", NULL },
{ "poll-timeout", 0, 0, G_OPTION_ARG_INT, &opt_poll_timeout, "Delay in seconds between polls for updates.", NULL },
{ "poll-when-metered", 0, 0, G_OPTION_ARG_NONE, &opt_poll_when_metered, "Whether to check for updates on metered networks", NULL },
{ NULL }
};
setlocale (LC_ALL, "");
g_setenv ("GIO_USE_VFS", "local", TRUE);
g_set_prgname (argv[0]);
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, message_handler, NULL);
if (argc >= 4 && strcmp (argv[1], "--update") == 0)
{
return do_update_child_process (argv[2], argv[3], 3);
}
context = g_option_context_new ("");
replace = FALSE;
opt_verbose = FALSE;
show_version = FALSE;
g_option_context_set_summary (context, "Flatpak portal");
g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
if (!g_option_context_parse (context, &argc, &argv, &error))
{
g_printerr ("%s: %s", g_get_application_name (), error->message);
g_printerr ("\n");
g_printerr ("Try \"%s --help\" for more information.",
g_get_prgname ());
g_printerr ("\n");
g_option_context_free (context);
return 1;
}
if (opt_poll_timeout == 0)
opt_poll_timeout = DEFAULT_UPDATE_POLL_TIMEOUT_SEC;
if (show_version)
{
g_print (PACKAGE_STRING "\n");
return 0;
}
if (opt_verbose)
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, message_handler, NULL);
client_pid_data_hash = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) pid_data_free);
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
if (session_bus == NULL)
{
g_printerr ("Can't find bus: %s\n", error->message);
return 1;
}
exe_path_len = readlink ("/proc/self/exe", exe_path, sizeof (exe_path) - 1);
if (exe_path_len > 0 && (size_t) exe_path_len < sizeof (exe_path))
{
exe_path[exe_path_len] = 0;
GFileMonitor *monitor;
g_autoptr(GFile) exe = NULL;
g_autoptr(GError) local_error = NULL;
exe = g_file_new_for_path (exe_path);
monitor = g_file_monitor_file (exe,
G_FILE_MONITOR_NONE,
NULL,
&local_error);
if (monitor == NULL)
g_warning ("Failed to set watch on %s: %s", exe_path, error->message);
else
g_signal_connect (monitor, "changed",
G_CALLBACK (binary_file_changed_cb), NULL);
}
flatpak_connection_track_name_owners (session_bus);
if (supports_expose_pids ())
supports |= FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS;
flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
if (replace)
flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
"org.freedesktop.portal.Flatpak",
flags,
on_bus_acquired,
on_name_acquired,
on_name_lost,
NULL,
NULL);
load_installed_portals (opt_verbose);
/* Ensure we don't idle exit */
schedule_idle_callback ();
network_monitor = g_network_monitor_get_default ();
main_loop = g_main_loop_new (NULL, FALSE);
g_main_loop_run (main_loop);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1908_0 |
crossvul-cpp_data_bad_433_1 | // SPDX-License-Identifier: GPL-3.0-or-later
#include "web_api_v1.h"
static struct {
const char *name;
uint32_t hash;
RRDR_OPTIONS value;
} api_v1_data_options[] = {
{ "nonzero" , 0 , RRDR_OPTION_NONZERO}
, {"flip" , 0 , RRDR_OPTION_REVERSED}
, {"reversed" , 0 , RRDR_OPTION_REVERSED}
, {"reverse" , 0 , RRDR_OPTION_REVERSED}
, {"jsonwrap" , 0 , RRDR_OPTION_JSON_WRAP}
, {"min2max" , 0 , RRDR_OPTION_MIN2MAX}
, {"ms" , 0 , RRDR_OPTION_MILLISECONDS}
, {"milliseconds" , 0 , RRDR_OPTION_MILLISECONDS}
, {"abs" , 0 , RRDR_OPTION_ABSOLUTE}
, {"absolute" , 0 , RRDR_OPTION_ABSOLUTE}
, {"absolute_sum" , 0 , RRDR_OPTION_ABSOLUTE}
, {"absolute-sum" , 0 , RRDR_OPTION_ABSOLUTE}
, {"display_absolute", 0 , RRDR_OPTION_DISPLAY_ABS}
, {"display-absolute", 0 , RRDR_OPTION_DISPLAY_ABS}
, {"seconds" , 0 , RRDR_OPTION_SECONDS}
, {"null2zero" , 0 , RRDR_OPTION_NULL2ZERO}
, {"objectrows" , 0 , RRDR_OPTION_OBJECTSROWS}
, {"google_json" , 0 , RRDR_OPTION_GOOGLE_JSON}
, {"google-json" , 0 , RRDR_OPTION_GOOGLE_JSON}
, {"percentage" , 0 , RRDR_OPTION_PERCENTAGE}
, {"unaligned" , 0 , RRDR_OPTION_NOT_ALIGNED}
, {"match_ids" , 0 , RRDR_OPTION_MATCH_IDS}
, {"match-ids" , 0 , RRDR_OPTION_MATCH_IDS}
, {"match_names" , 0 , RRDR_OPTION_MATCH_NAMES}
, {"match-names" , 0 , RRDR_OPTION_MATCH_NAMES}
, { NULL, 0, 0}
};
static struct {
const char *name;
uint32_t hash;
uint32_t value;
} api_v1_data_formats[] = {
{ DATASOURCE_FORMAT_DATATABLE_JSON , 0 , DATASOURCE_DATATABLE_JSON}
, {DATASOURCE_FORMAT_DATATABLE_JSONP, 0 , DATASOURCE_DATATABLE_JSONP}
, {DATASOURCE_FORMAT_JSON , 0 , DATASOURCE_JSON}
, {DATASOURCE_FORMAT_JSONP , 0 , DATASOURCE_JSONP}
, {DATASOURCE_FORMAT_SSV , 0 , DATASOURCE_SSV}
, {DATASOURCE_FORMAT_CSV , 0 , DATASOURCE_CSV}
, {DATASOURCE_FORMAT_TSV , 0 , DATASOURCE_TSV}
, {"tsv-excel" , 0 , DATASOURCE_TSV}
, {DATASOURCE_FORMAT_HTML , 0 , DATASOURCE_HTML}
, {DATASOURCE_FORMAT_JS_ARRAY , 0 , DATASOURCE_JS_ARRAY}
, {DATASOURCE_FORMAT_SSV_COMMA , 0 , DATASOURCE_SSV_COMMA}
, {DATASOURCE_FORMAT_CSV_JSON_ARRAY , 0 , DATASOURCE_CSV_JSON_ARRAY}
, {DATASOURCE_FORMAT_CSV_MARKDOWN , 0 , DATASOURCE_CSV_MARKDOWN}
, { NULL, 0, 0}
};
static struct {
const char *name;
uint32_t hash;
uint32_t value;
} api_v1_data_google_formats[] = {
// this is not error - when google requests json, it expects javascript
// https://developers.google.com/chart/interactive/docs/dev/implementing_data_source#responseformat
{ "json" , 0 , DATASOURCE_DATATABLE_JSONP}
, {"html" , 0 , DATASOURCE_HTML}
, {"csv" , 0 , DATASOURCE_CSV}
, {"tsv-excel", 0 , DATASOURCE_TSV}
, { NULL, 0, 0}
};
void web_client_api_v1_init(void) {
int i;
for(i = 0; api_v1_data_options[i].name ; i++)
api_v1_data_options[i].hash = simple_hash(api_v1_data_options[i].name);
for(i = 0; api_v1_data_formats[i].name ; i++)
api_v1_data_formats[i].hash = simple_hash(api_v1_data_formats[i].name);
for(i = 0; api_v1_data_google_formats[i].name ; i++)
api_v1_data_google_formats[i].hash = simple_hash(api_v1_data_google_formats[i].name);
web_client_api_v1_init_grouping();
}
inline uint32_t web_client_api_request_v1_data_options(char *o) {
uint32_t ret = 0x00000000;
char *tok;
while(o && *o && (tok = mystrsep(&o, ", |"))) {
if(!*tok) continue;
uint32_t hash = simple_hash(tok);
int i;
for(i = 0; api_v1_data_options[i].name ; i++) {
if (unlikely(hash == api_v1_data_options[i].hash && !strcmp(tok, api_v1_data_options[i].name))) {
ret |= api_v1_data_options[i].value;
break;
}
}
}
return ret;
}
inline uint32_t web_client_api_request_v1_data_format(char *name) {
uint32_t hash = simple_hash(name);
int i;
for(i = 0; api_v1_data_formats[i].name ; i++) {
if (unlikely(hash == api_v1_data_formats[i].hash && !strcmp(name, api_v1_data_formats[i].name))) {
return api_v1_data_formats[i].value;
}
}
return DATASOURCE_JSON;
}
inline uint32_t web_client_api_request_v1_data_google_format(char *name) {
uint32_t hash = simple_hash(name);
int i;
for(i = 0; api_v1_data_google_formats[i].name ; i++) {
if (unlikely(hash == api_v1_data_google_formats[i].hash && !strcmp(name, api_v1_data_google_formats[i].name))) {
return api_v1_data_google_formats[i].value;
}
}
return DATASOURCE_JSON;
}
inline int web_client_api_request_v1_alarms(RRDHOST *host, struct web_client *w, char *url) {
int all = 0;
while(url) {
char *value = mystrsep(&url, "?&");
if (!value || !*value) continue;
if(!strcmp(value, "all")) all = 1;
else if(!strcmp(value, "active")) all = 0;
}
buffer_flush(w->response.data);
w->response.data->contenttype = CT_APPLICATION_JSON;
health_alarms2json(host, w->response.data, all);
return 200;
}
inline int web_client_api_request_v1_alarm_log(RRDHOST *host, struct web_client *w, char *url) {
uint32_t after = 0;
while(url) {
char *value = mystrsep(&url, "?&");
if (!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
if(!strcmp(name, "after")) after = (uint32_t)strtoul(value, NULL, 0);
}
buffer_flush(w->response.data);
w->response.data->contenttype = CT_APPLICATION_JSON;
health_alarm_log2json(host, w->response.data, after);
return 200;
}
inline int web_client_api_request_single_chart(RRDHOST *host, struct web_client *w, char *url, void callback(RRDSET *st, BUFFER *buf)) {
int ret = 400;
char *chart = NULL;
buffer_flush(w->response.data);
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
// name and value are now the parameters
// they are not null and not empty
if(!strcmp(name, "chart")) chart = value;
//else {
/// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
// goto cleanup;
//}
}
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
w->response.data->contenttype = CT_APPLICATION_JSON;
st->last_accessed_time = now_realtime_sec();
callback(st, w->response.data);
return 200;
cleanup:
return ret;
}
inline int web_client_api_request_v1_alarm_variables(RRDHOST *host, struct web_client *w, char *url) {
return web_client_api_request_single_chart(host, w, url, health_api_v1_chart_variables2json);
}
inline int web_client_api_request_v1_charts(RRDHOST *host, struct web_client *w, char *url) {
(void)url;
buffer_flush(w->response.data);
w->response.data->contenttype = CT_APPLICATION_JSON;
charts2json(host, w->response.data);
return 200;
}
inline int web_client_api_request_v1_chart(RRDHOST *host, struct web_client *w, char *url) {
return web_client_api_request_single_chart(host, w, url, rrd_stats_api_v1_chart);
}
// returns the HTTP code
inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {
debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
int ret = 400;
BUFFER *dimensions = NULL;
buffer_flush(w->response.data);
char *google_version = "0.6",
*google_reqId = "0",
*google_sig = "0",
*google_out = "json",
*responseHandler = NULL,
*outFileName = NULL;
time_t last_timestamp_in_data = 0, google_timestamp = 0;
char *chart = NULL
, *before_str = NULL
, *after_str = NULL
, *group_time_str = NULL
, *points_str = NULL;
int group = RRDR_GROUPING_AVERAGE;
uint32_t format = DATASOURCE_JSON;
uint32_t options = 0x00000000;
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
// name and value are now the parameters
// they are not null and not empty
if(!strcmp(name, "chart")) chart = value;
else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
if(!dimensions) dimensions = buffer_create(100);
buffer_strcat(dimensions, "|");
buffer_strcat(dimensions, value);
}
else if(!strcmp(name, "after")) after_str = value;
else if(!strcmp(name, "before")) before_str = value;
else if(!strcmp(name, "points")) points_str = value;
else if(!strcmp(name, "gtime")) group_time_str = value;
else if(!strcmp(name, "group")) {
group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE);
}
else if(!strcmp(name, "format")) {
format = web_client_api_request_v1_data_format(value);
}
else if(!strcmp(name, "options")) {
options |= web_client_api_request_v1_data_options(value);
}
else if(!strcmp(name, "callback")) {
responseHandler = value;
}
else if(!strcmp(name, "filename")) {
outFileName = value;
}
else if(!strcmp(name, "tqx")) {
// parse Google Visualization API options
// https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
char *tqx_name, *tqx_value;
while(value) {
tqx_value = mystrsep(&value, ";");
if(!tqx_value || !*tqx_value) continue;
tqx_name = mystrsep(&tqx_value, ":");
if(!tqx_name || !*tqx_name) continue;
if(!tqx_value || !*tqx_value) continue;
if(!strcmp(tqx_name, "version"))
google_version = tqx_value;
else if(!strcmp(tqx_name, "reqId"))
google_reqId = tqx_value;
else if(!strcmp(tqx_name, "sig")) {
google_sig = tqx_value;
google_timestamp = strtoul(google_sig, NULL, 0);
}
else if(!strcmp(tqx_name, "out")) {
google_out = tqx_value;
format = web_client_api_request_v1_data_google_format(google_out);
}
else if(!strcmp(tqx_name, "responseHandler"))
responseHandler = tqx_value;
else if(!strcmp(tqx_name, "outFileName"))
outFileName = tqx_value;
}
}
}
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
st->last_accessed_time = now_realtime_sec();
long long before = (before_str && *before_str)?str2l(before_str):0;
long long after = (after_str && *after_str) ?str2l(after_str):0;
int points = (points_str && *points_str)?str2i(points_str):0;
long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;
debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
, w->id
, chart
, (dimensions)?buffer_tostring(dimensions):""
, after
, before
, points
, group
, format
, options
);
if(outFileName && *outFileName) {
buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
}
if(format == DATASOURCE_DATATABLE_JSONP) {
if(responseHandler == NULL)
responseHandler = "google.visualization.Query.setResponse";
debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
}
else if(format == DATASOURCE_JSONP) {
if(responseHandler == NULL)
responseHandler = "callback";
buffer_strcat(w->response.data, responseHandler);
buffer_strcat(w->response.data, "(");
}
ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time
, options, &last_timestamp_in_data);
if(format == DATASOURCE_DATATABLE_JSONP) {
if(google_timestamp < last_timestamp_in_data)
buffer_strcat(w->response.data, "});");
else {
// the client already has the latest data
buffer_flush(w->response.data);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
responseHandler, google_version, google_reqId);
}
}
else if(format == DATASOURCE_JSONP)
buffer_strcat(w->response.data, ");");
cleanup:
buffer_free(dimensions);
return ret;
}
inline int web_client_api_request_v1_registry(RRDHOST *host, struct web_client *w, char *url) {
static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0,
hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0,
hash_to = 0 /*, hash_redirects = 0 */;
if(unlikely(!hash_action)) {
hash_action = simple_hash("action");
hash_access = simple_hash("access");
hash_hello = simple_hash("hello");
hash_delete = simple_hash("delete");
hash_search = simple_hash("search");
hash_switch = simple_hash("switch");
hash_machine = simple_hash("machine");
hash_url = simple_hash("url");
hash_name = simple_hash("name");
hash_delete_url = simple_hash("delete_url");
hash_for = simple_hash("for");
hash_to = simple_hash("to");
/*
hash_redirects = simple_hash("redirects");
*/
}
char person_guid[GUID_LEN + 1] = "";
debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
// TODO
// The browser may send multiple cookies with our id
char *cookie = strstr(w->response.data->buffer, NETDATA_REGISTRY_COOKIE_NAME "=");
if(cookie)
strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME)], 36);
char action = '\0';
char *machine_guid = NULL,
*machine_url = NULL,
*url_name = NULL,
*search_machine_guid = NULL,
*delete_url = NULL,
*to_person_guid = NULL;
/*
int redirects = 0;
*/
while(url) {
char *value = mystrsep(&url, "?&");
if (!value || !*value) continue;
char *name = mystrsep(&value, "=");
if (!name || !*name) continue;
if (!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
uint32_t hash = simple_hash(name);
if(hash == hash_action && !strcmp(name, "action")) {
uint32_t vhash = simple_hash(value);
if(vhash == hash_access && !strcmp(value, "access")) action = 'A';
else if(vhash == hash_hello && !strcmp(value, "hello")) action = 'H';
else if(vhash == hash_delete && !strcmp(value, "delete")) action = 'D';
else if(vhash == hash_search && !strcmp(value, "search")) action = 'S';
else if(vhash == hash_switch && !strcmp(value, "switch")) action = 'W';
#ifdef NETDATA_INTERNAL_CHECKS
else error("unknown registry action '%s'", value);
#endif /* NETDATA_INTERNAL_CHECKS */
}
/*
else if(hash == hash_redirects && !strcmp(name, "redirects"))
redirects = atoi(value);
*/
else if(hash == hash_machine && !strcmp(name, "machine"))
machine_guid = value;
else if(hash == hash_url && !strcmp(name, "url"))
machine_url = value;
else if(action == 'A') {
if(hash == hash_name && !strcmp(name, "name"))
url_name = value;
}
else if(action == 'D') {
if(hash == hash_delete_url && !strcmp(name, "delete_url"))
delete_url = value;
}
else if(action == 'S') {
if(hash == hash_for && !strcmp(name, "for"))
search_machine_guid = value;
}
else if(action == 'W') {
if(hash == hash_to && !strcmp(name, "to"))
to_person_guid = value;
}
#ifdef NETDATA_INTERNAL_CHECKS
else error("unused registry URL parameter '%s' with value '%s'", name, value);
#endif /* NETDATA_INTERNAL_CHECKS */
}
if(unlikely(respect_web_browser_do_not_track_policy && web_client_has_donottrack(w))) {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data, "Your web browser is sending 'DNT: 1' (Do Not Track). The registry requires persistent cookies on your browser to work.");
return 400;
}
if(unlikely(action == 'H')) {
// HELLO request, dashboard ACL
if(unlikely(!web_client_can_access_dashboard(w)))
return web_client_permission_denied(w);
}
else {
// everything else, registry ACL
if(unlikely(!web_client_can_access_registry(w)))
return web_client_permission_denied(w);
}
switch(action) {
case 'A':
if(unlikely(!machine_guid || !machine_url || !url_name)) {
error("Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')", machine_guid ? machine_guid : "UNSET", machine_url ? machine_url : "UNSET", url_name ? url_name : "UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Access request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_access_json(host, w, person_guid, machine_guid, machine_url, url_name, now_realtime_sec());
case 'D':
if(unlikely(!machine_guid || !machine_url || !delete_url)) {
error("Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Delete request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_delete_json(host, w, person_guid, machine_guid, machine_url, delete_url, now_realtime_sec());
case 'S':
if(unlikely(!machine_guid || !machine_url || !search_machine_guid)) {
error("Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Search request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_search_json(host, w, person_guid, machine_guid, machine_url, search_machine_guid, now_realtime_sec());
case 'W':
if(unlikely(!machine_guid || !machine_url || !to_person_guid)) {
error("Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Switch request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_switch_json(host, w, person_guid, machine_guid, machine_url, to_person_guid, now_realtime_sec());
case 'H':
return registry_request_hello_json(host, w);
default:
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
return 400;
}
}
static struct api_command {
const char *command;
uint32_t hash;
WEB_CLIENT_ACL acl;
int (*callback)(RRDHOST *host, struct web_client *w, char *url);
} api_commands[] = {
{ "data", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_data },
{ "chart", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_chart },
{ "charts", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_charts },
// registry checks the ACL by itself, so we allow everything
{ "registry", 0, WEB_CLIENT_ACL_NOCHECK, web_client_api_request_v1_registry },
// badges can be fetched with both dashboard and badge permissions
{ "badge.svg", 0, WEB_CLIENT_ACL_DASHBOARD|WEB_CLIENT_ACL_BADGE, web_client_api_request_v1_badge },
{ "alarms", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_alarms },
{ "alarm_log", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_alarm_log },
{ "alarm_variables", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_alarm_variables },
{ "allmetrics", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_allmetrics },
// terminator
{ NULL, 0, WEB_CLIENT_ACL_NONE, NULL },
};
inline int web_client_api_request_v1(RRDHOST *host, struct web_client *w, char *url) {
static int initialized = 0;
int i;
if(unlikely(initialized == 0)) {
initialized = 1;
for(i = 0; api_commands[i].command ; i++)
api_commands[i].hash = simple_hash(api_commands[i].command);
}
// get the command
char *tok = mystrsep(&url, "/?&");
if(tok && *tok) {
debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
uint32_t hash = simple_hash(tok);
for(i = 0; api_commands[i].command ;i++) {
if(unlikely(hash == api_commands[i].hash && !strcmp(tok, api_commands[i].command))) {
if(unlikely(api_commands[i].acl != WEB_CLIENT_ACL_NOCHECK) && !(w->acl & api_commands[i].acl))
return web_client_permission_denied(w);
return api_commands[i].callback(host, w, url);
}
}
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Unsupported v1 API command: ");
buffer_strcat_htmlescape(w->response.data, tok);
return 404;
}
else {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data, "Which API v1 command?");
return 400;
}
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_433_1 |
crossvul-cpp_data_good_5255_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
| Andrei Zmievski <andrei@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef PHP_WIN32
# include "win32/winutil.h"
# include "win32/time.h"
#else
# include <sys/time.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include "php_ini.h"
#include "SAPI.h"
#include "rfc1867.h"
#include "php_variables.h"
#include "php_session.h"
#include "ext/standard/md5.h"
#include "ext/standard/sha1.h"
#include "ext/standard/php_var.h"
#include "ext/date/php_date.h"
#include "ext/standard/php_lcg.h"
#include "ext/standard/url_scanner_ex.h"
#include "ext/standard/php_rand.h" /* for RAND_MAX */
#include "ext/standard/info.h"
#include "ext/standard/php_smart_str.h"
#include "ext/standard/url.h"
#include "ext/standard/basic_functions.h"
#include "mod_files.h"
#include "mod_user.h"
#ifdef HAVE_LIBMM
#include "mod_mm.h"
#endif
PHPAPI ZEND_DECLARE_MODULE_GLOBALS(ps)
static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra TSRMLS_DC);
static int (*php_session_rfc1867_orig_callback)(unsigned int event, void *event_data, void **extra TSRMLS_DC);
/* SessionHandler class */
zend_class_entry *php_session_class_entry;
/* SessionHandlerInterface */
zend_class_entry *php_session_iface_entry;
/* SessionIdInterface */
zend_class_entry *php_session_id_iface_entry;
/* ***********
* Helpers *
*********** */
#define IF_SESSION_VARS() \
if (PS(http_session_vars) && PS(http_session_vars)->type == IS_ARRAY)
#define SESSION_CHECK_ACTIVE_STATE \
if (PS(session_status) == php_session_active) { \
php_error_docref(NULL TSRMLS_CC, E_WARNING, "A session is active. You cannot change the session module's ini settings at this time"); \
return FAILURE; \
}
static void php_session_send_cookie(TSRMLS_D);
/* Dispatched by RINIT and by php_session_destroy */
static inline void php_rinit_session_globals(TSRMLS_D) /* {{{ */
{
PS(id) = NULL;
PS(session_status) = php_session_none;
PS(mod_data) = NULL;
PS(mod_user_is_open) = 0;
/* Do NOT init PS(mod_user_names) here! */
PS(http_session_vars) = NULL;
}
/* }}} */
/* Dispatched by RSHUTDOWN and by php_session_destroy */
static inline void php_rshutdown_session_globals(TSRMLS_D) /* {{{ */
{
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
PS(http_session_vars) = NULL;
}
/* Do NOT destroy PS(mod_user_names) here! */
if (PS(mod_data) || PS(mod_user_implemented)) {
zend_try {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
} zend_end_try();
}
if (PS(id)) {
efree(PS(id));
PS(id) = NULL;
}
}
/* }}} */
static int php_session_destroy(TSRMLS_D) /* {{{ */
{
int retval = SUCCESS;
if (PS(session_status) != php_session_active) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to destroy uninitialized session");
return FAILURE;
}
if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
retval = FAILURE;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
}
php_rshutdown_session_globals(TSRMLS_C);
php_rinit_session_globals(TSRMLS_C);
return retval;
}
/* }}} */
PHPAPI void php_add_session_var(char *name, size_t namelen TSRMLS_DC) /* {{{ */
{
zval **sym_track = NULL;
IF_SESSION_VARS() {
zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void *) &sym_track);
} else {
return;
}
if (sym_track == NULL) {
zval *empty_var;
ALLOC_INIT_ZVAL(empty_var);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), name, namelen+1, empty_var, 1, 0);
}
}
/* }}} */
PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */
{
IF_SESSION_VARS() {
zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars)));
}
}
/* }}} */
PHPAPI int php_get_session_var(char *name, size_t namelen, zval ***state_var TSRMLS_DC) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
ret = zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void **) state_var);
}
return ret;
}
/* }}} */
static void php_session_track_init(TSRMLS_D) /* {{{ */
{
zval *session_vars = NULL;
/* Unconditionally destroy existing array -- possible dirty data */
zend_delete_global_variable("_SESSION", sizeof("_SESSION")-1 TSRMLS_CC);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
MAKE_STD_ZVAL(session_vars);
array_init(session_vars);
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), 2, 1);
}
/* }}} */
static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */
{
char *ret = NULL;
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
ret = NULL;
} else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) {
ret = NULL;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session");
}
return ret;
}
/* }}} */
static int php_session_decode(const char *val, int vallen TSRMLS_DC) /* {{{ */
{
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
return FAILURE;
}
if (PS(serializer)->decode(val, vallen TSRMLS_CC) == FAILURE) {
php_session_destroy(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to decode session object. Session has been destroyed");
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/*
* Note that we cannot use the BASE64 alphabet here, because
* it contains "/" and "+": both are unacceptable for simple inclusion
* into URLs.
*/
static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
enum {
PS_HASH_FUNC_MD5,
PS_HASH_FUNC_SHA1,
PS_HASH_FUNC_OTHER
};
/* returns a pointer to the byte after the last valid character in out */
static char *bin_to_readable(char *in, size_t inlen, char *out, char nbits) /* {{{ */
{
unsigned char *p, *q;
unsigned short w;
int mask;
int have;
p = (unsigned char *) in;
q = (unsigned char *)in + inlen;
w = 0;
have = 0;
mask = (1 << nbits) - 1;
while (1) {
if (have < nbits) {
if (p < q) {
w |= *p++ << have;
have += 8;
} else {
/* consumed everything? */
if (have == 0) break;
/* No? We need a final round */
have = nbits;
}
}
/* consume nbits */
*out++ = hexconvtab[w & mask];
w >>= nbits;
have -= nbits;
}
*out = '\0';
return out;
}
/* }}} */
PHPAPI char *php_session_create_id(PS_CREATE_SID_ARGS) /* {{{ */
{
PHP_MD5_CTX md5_context;
PHP_SHA1_CTX sha1_context;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
void *hash_context = NULL;
#endif
unsigned char *digest;
int digest_len;
int j;
char *buf, *outid;
struct timeval tv;
zval **array;
zval **token;
char *remote_addr = NULL;
gettimeofday(&tv, NULL);
if (zend_hash_find(&EG(symbol_table), "_SERVER", sizeof("_SERVER"), (void **) &array) == SUCCESS &&
Z_TYPE_PP(array) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(array), "REMOTE_ADDR", sizeof("REMOTE_ADDR"), (void **) &token) == SUCCESS &&
Z_TYPE_PP(token) == IS_STRING
) {
remote_addr = Z_STRVAL_PP(token);
}
/* maximum 15+19+19+10 bytes */
spprintf(&buf, 0, "%.15s%ld%ld%0.8F", remote_addr ? remote_addr : "", tv.tv_sec, (long int)tv.tv_usec, php_combined_lcg(TSRMLS_C) * 10);
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Init(&md5_context);
PHP_MD5Update(&md5_context, (unsigned char *) buf, strlen(buf));
digest_len = 16;
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Init(&sha1_context);
PHP_SHA1Update(&sha1_context, (unsigned char *) buf, strlen(buf));
digest_len = 20;
break;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
if (!PS(hash_ops)) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Invalid session hash function");
efree(buf);
return NULL;
}
hash_context = emalloc(PS(hash_ops)->context_size);
PS(hash_ops)->hash_init(hash_context);
PS(hash_ops)->hash_update(hash_context, (unsigned char *) buf, strlen(buf));
digest_len = PS(hash_ops)->digest_size;
break;
#endif /* HAVE_HASH_EXT */
default:
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Invalid session hash function");
efree(buf);
return NULL;
}
efree(buf);
if (PS(entropy_length) > 0) {
#ifdef PHP_WIN32
unsigned char rbuf[2048];
size_t toread = PS(entropy_length);
if (php_win32_get_random_bytes(rbuf, MIN(toread, sizeof(rbuf))) == SUCCESS){
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Update(&md5_context, rbuf, toread);
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Update(&sha1_context, rbuf, toread);
break;
# if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
PS(hash_ops)->hash_update(hash_context, rbuf, toread);
break;
# endif /* HAVE_HASH_EXT */
}
}
#else
int fd;
fd = VCWD_OPEN(PS(entropy_file), O_RDONLY);
if (fd >= 0) {
unsigned char rbuf[2048];
int n;
int to_read = PS(entropy_length);
while (to_read > 0) {
n = read(fd, rbuf, MIN(to_read, sizeof(rbuf)));
if (n <= 0) break;
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Update(&md5_context, rbuf, n);
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Update(&sha1_context, rbuf, n);
break;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
PS(hash_ops)->hash_update(hash_context, rbuf, n);
break;
#endif /* HAVE_HASH_EXT */
}
to_read -= n;
}
close(fd);
}
#endif
}
digest = emalloc(digest_len + 1);
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Final(digest, &md5_context);
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Final(digest, &sha1_context);
break;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
PS(hash_ops)->hash_final(digest, hash_context);
efree(hash_context);
break;
#endif /* HAVE_HASH_EXT */
}
if (PS(hash_bits_per_character) < 4
|| PS(hash_bits_per_character) > 6) {
PS(hash_bits_per_character) = 4;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ini setting hash_bits_per_character is out of range (should be 4, 5, or 6) - using 4 for now");
}
outid = emalloc((size_t)((digest_len + 2) * ((8.0f / PS(hash_bits_per_character)) + 0.5)));
j = (int) (bin_to_readable((char *)digest, digest_len, outid, (char)PS(hash_bits_per_character)) - outid);
efree(digest);
if (newlen) {
*newlen = j;
}
return outid;
}
/* }}} */
/* Default session id char validation function allowed by ps_modules.
* If you change the logic here, please also update the error message in
* ps_modules appropriately */
PHPAPI int php_session_valid_key(const char *key) /* {{{ */
{
size_t len;
const char *p;
char c;
int ret = SUCCESS;
for (p = key; (c = *p); p++) {
/* valid characters are a..z,A..Z,0..9 */
if (!((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == ','
|| c == '-')) {
ret = FAILURE;
break;
}
}
len = p - key;
/* Somewhat arbitrary length limit here, but should be way more than
anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
if (len == 0 || len > 128) {
ret = FAILURE;
}
return ret;
}
/* }}} */
static void php_session_initialize(TSRMLS_D) /* {{{ */
{
char *val = NULL;
int vallen;
if (!PS(mod)) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "No storage module chosen - failed to initialize session");
return;
}
/* Open session handler first */
if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name) TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Failed to initialize storage module: %s (path: %s)", PS(mod)->s_name, PS(save_path));
return;
}
/* If there is no ID, use session module to create one */
if (!PS(id)) {
PS(id) = PS(mod)->s_create_sid(&PS(mod_data), NULL TSRMLS_CC);
if (!PS(id)) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Failed to create session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
return;
}
if (PS(use_cookies)) {
PS(send_cookie) = 1;
}
}
/* Set session ID for compatibility for older/3rd party save handlers */
if (!PS(use_strict_mode)) {
php_session_reset_id(TSRMLS_C);
PS(session_status) = php_session_active;
}
/* Read data */
php_session_track_init(TSRMLS_C);
if (PS(mod)->s_read(&PS(mod_data), PS(id), &val, &vallen TSRMLS_CC) == FAILURE) {
/* Some broken save handler implementation returns FAILURE for non-existent session ID */
/* It's better to raise error for this, but disabled error for better compatibility */
/*
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to read session data: %s (path: %s)", PS(mod)->s_name, PS(save_path));
*/
}
/* Set session ID if session read didn't activated session */
if (PS(use_strict_mode) && PS(session_status) != php_session_active) {
php_session_reset_id(TSRMLS_C);
PS(session_status) = php_session_active;
}
if (val) {
php_session_decode(val, vallen TSRMLS_CC);
str_efree(val);
}
if (!PS(use_cookies) && PS(send_cookie)) {
if (PS(use_trans_sid) && !PS(use_only_cookies)) {
PS(apply_trans_sid) = 1;
}
PS(send_cookie) = 0;
}
}
/* }}} */
static void php_session_save_current_state(TSRMLS_D) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
if (PS(mod_data) || PS(mod_user_implemented)) {
char *val;
int vallen;
val = php_session_encode(&vallen TSRMLS_CC);
if (val) {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), val, vallen TSRMLS_CC);
efree(val);
} else {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), "", 0 TSRMLS_CC);
}
}
if (ret == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to write session data (%s). Please "
"verify that the current setting of session.save_path "
"is correct (%s)",
PS(mod)->s_name,
PS(save_path));
}
}
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
}
}
/* }}} */
/* *************************
* INI Settings/Handlers *
************************* */
static PHP_INI_MH(OnUpdateSaveHandler) /* {{{ */
{
ps_module *tmp;
SESSION_CHECK_ACTIVE_STATE;
tmp = _php_find_ps_module(new_value TSRMLS_CC);
if (PG(modules_activated) && !tmp) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL TSRMLS_CC, err_type, "Cannot find save handler '%s'", new_value);
}
return FAILURE;
}
PS(default_mod) = PS(mod);
PS(mod) = tmp;
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateSerializer) /* {{{ */
{
const ps_serializer *tmp;
SESSION_CHECK_ACTIVE_STATE;
tmp = _php_find_ps_serializer(new_value TSRMLS_CC);
if (PG(modules_activated) && !tmp) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL TSRMLS_CC, err_type, "Cannot find serialization handler '%s'", new_value);
}
return FAILURE;
}
PS(serializer) = tmp;
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateTransSid) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
if (!strncasecmp(new_value, "on", sizeof("on"))) {
PS(use_trans_sid) = (zend_bool) 1;
} else {
PS(use_trans_sid) = (zend_bool) atoi(new_value);
}
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateSaveDir) /* {{{ */
{
/* Only do the safemode/open_basedir check at runtime */
if (stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) {
char *p;
if (memchr(new_value, '\0', new_value_length) != NULL) {
return FAILURE;
}
/* we do not use zend_memrchr() since path can contain ; itself */
if ((p = strchr(new_value, ';'))) {
char *p2;
p++;
if ((p2 = strchr(p, ';'))) {
p = p2 + 1;
}
} else {
p = new_value;
}
if (PG(open_basedir) && *p && php_check_open_basedir(p TSRMLS_CC)) {
return FAILURE;
}
}
OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateName) /* {{{ */
{
/* Numeric session.name won't work at all */
if ((!new_value_length || is_numeric_string(new_value, new_value_length, NULL, NULL, 0))) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME || stage == ZEND_INI_STAGE_ACTIVATE || stage == ZEND_INI_STAGE_STARTUP) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL TSRMLS_CC, err_type, "session.name cannot be a numeric or empty '%s'", new_value);
}
return FAILURE;
}
OnUpdateStringUnempty(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateHashFunc) /* {{{ */
{
long val;
char *endptr = NULL;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
PS(hash_ops) = NULL;
#endif
val = strtol(new_value, &endptr, 10);
if (endptr && (*endptr == '\0')) {
/* Numeric value */
PS(hash_func) = val ? 1 : 0;
return SUCCESS;
}
if (new_value_length == (sizeof("md5") - 1) &&
strncasecmp(new_value, "md5", sizeof("md5") - 1) == 0) {
PS(hash_func) = PS_HASH_FUNC_MD5;
return SUCCESS;
}
if (new_value_length == (sizeof("sha1") - 1) &&
strncasecmp(new_value, "sha1", sizeof("sha1") - 1) == 0) {
PS(hash_func) = PS_HASH_FUNC_SHA1;
return SUCCESS;
}
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH) /* {{{ */
{
php_hash_ops *ops = (php_hash_ops*)php_hash_fetch_ops(new_value, new_value_length);
if (ops) {
PS(hash_func) = PS_HASH_FUNC_OTHER;
PS(hash_ops) = ops;
return SUCCESS;
}
}
#endif /* HAVE_HASH_EXT }}} */
php_error_docref(NULL TSRMLS_CC, E_WARNING, "session.configuration 'session.hash_function' must be existing hash function. %s does not exist.", new_value);
return FAILURE;
}
/* }}} */
static PHP_INI_MH(OnUpdateRfc1867Freq) /* {{{ */
{
int tmp;
tmp = zend_atoi(new_value, new_value_length);
if(tmp < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "session.upload_progress.freq must be greater than or equal to zero");
return FAILURE;
}
if(new_value_length > 0 && new_value[new_value_length-1] == '%') {
if(tmp > 100) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "session.upload_progress.freq cannot be over 100%%");
return FAILURE;
}
PS(rfc1867_freq) = -tmp;
} else {
PS(rfc1867_freq) = tmp;
}
return SUCCESS;
} /* }}} */
static ZEND_INI_MH(OnUpdateSmartStr) /* {{{ */
{
smart_str *p;
#ifndef ZTS
char *base = (char *) mh_arg2;
#else
char *base;
base = (char *) ts_resource(*((int *) mh_arg2));
#endif
p = (smart_str *) (base+(size_t) mh_arg1);
smart_str_sets(p, new_value);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("session.save_path", "", PHP_INI_ALL, OnUpdateSaveDir,save_path, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.name", "PHPSESSID", PHP_INI_ALL, OnUpdateName, session_name, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.save_handler", "files", PHP_INI_ALL, OnUpdateSaveHandler)
STD_PHP_INI_BOOLEAN("session.auto_start", "0", PHP_INI_PERDIR, OnUpdateBool, auto_start, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_probability", "1", PHP_INI_ALL, OnUpdateLong, gc_probability, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_divisor", "100", PHP_INI_ALL, OnUpdateLong, gc_divisor, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_maxlifetime", "1440", PHP_INI_ALL, OnUpdateLong, gc_maxlifetime, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.serialize_handler", "php", PHP_INI_ALL, OnUpdateSerializer)
STD_PHP_INI_ENTRY("session.cookie_lifetime", "0", PHP_INI_ALL, OnUpdateLong, cookie_lifetime, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_path", "/", PHP_INI_ALL, OnUpdateString, cookie_path, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_domain", "", PHP_INI_ALL, OnUpdateString, cookie_domain, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.cookie_secure", "", PHP_INI_ALL, OnUpdateBool, cookie_secure, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.cookie_httponly", "", PHP_INI_ALL, OnUpdateBool, cookie_httponly, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.use_cookies", "1", PHP_INI_ALL, OnUpdateBool, use_cookies, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.use_only_cookies", "1", PHP_INI_ALL, OnUpdateBool, use_only_cookies, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.use_strict_mode", "0", PHP_INI_ALL, OnUpdateBool, use_strict_mode, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.referer_check", "", PHP_INI_ALL, OnUpdateString, extern_referer_chk, php_ps_globals, ps_globals)
#if HAVE_DEV_URANDOM
STD_PHP_INI_ENTRY("session.entropy_file", "/dev/urandom", PHP_INI_ALL, OnUpdateString, entropy_file, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.entropy_length", "32", PHP_INI_ALL, OnUpdateLong, entropy_length, php_ps_globals, ps_globals)
#elif HAVE_DEV_ARANDOM
STD_PHP_INI_ENTRY("session.entropy_file", "/dev/arandom", PHP_INI_ALL, OnUpdateString, entropy_file, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.entropy_length", "32", PHP_INI_ALL, OnUpdateLong, entropy_length, php_ps_globals, ps_globals)
#else
STD_PHP_INI_ENTRY("session.entropy_file", "", PHP_INI_ALL, OnUpdateString, entropy_file, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.entropy_length", "0", PHP_INI_ALL, OnUpdateLong, entropy_length, php_ps_globals, ps_globals)
#endif
STD_PHP_INI_ENTRY("session.cache_limiter", "nocache", PHP_INI_ALL, OnUpdateString, cache_limiter, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cache_expire", "180", PHP_INI_ALL, OnUpdateLong, cache_expire, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.use_trans_sid", "0", PHP_INI_ALL, OnUpdateTransSid)
PHP_INI_ENTRY("session.hash_function", "0", PHP_INI_ALL, OnUpdateHashFunc)
STD_PHP_INI_ENTRY("session.hash_bits_per_character", "4", PHP_INI_ALL, OnUpdateLong, hash_bits_per_character, php_ps_globals, ps_globals)
/* Upload progress */
STD_PHP_INI_BOOLEAN("session.upload_progress.enabled",
"1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_enabled, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.upload_progress.cleanup",
"1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_cleanup, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.prefix",
"upload_progress_", ZEND_INI_PERDIR, OnUpdateSmartStr, rfc1867_prefix, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.name",
"PHP_SESSION_UPLOAD_PROGRESS", ZEND_INI_PERDIR, OnUpdateSmartStr, rfc1867_name, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.freq", "1%", ZEND_INI_PERDIR, OnUpdateRfc1867Freq, rfc1867_freq, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.min_freq",
"1", ZEND_INI_PERDIR, OnUpdateReal, rfc1867_min_freq,php_ps_globals, ps_globals)
/* Commented out until future discussion */
/* PHP_INI_ENTRY("session.encode_sources", "globals,track", PHP_INI_ALL, NULL) */
PHP_INI_END()
/* }}} */
/* ***************
* Serializers *
*************** */
PS_SERIALIZER_ENCODE_FUNC(php_serialize) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &PS(http_session_vars), &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
if (newlen) {
*newlen = buf.len;
}
smart_str_0(&buf);
*newstr = buf.c;
return SUCCESS;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */
{
const char *endptr = val + vallen;
zval *session_vars;
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
ALLOC_INIT_ZVAL(session_vars);
if (php_var_unserialize(&session_vars, &val, endptr, &var_hash TSRMLS_CC)) {
var_push_dtor(&var_hash, &session_vars);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
if (Z_TYPE_P(session_vars) == IS_NULL) {
array_init(session_vars);
}
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), Z_REFCOUNT_P(PS(http_session_vars)) + 1, 1);
return SUCCESS;
}
/* }}} */
#define PS_BIN_NR_OF_BITS 8
#define PS_BIN_UNDEF (1<<(PS_BIN_NR_OF_BITS-1))
#define PS_BIN_MAX (PS_BIN_UNDEF-1)
PS_SERIALIZER_ENCODE_FUNC(php_binary) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PS_ENCODE_VARS;
PHP_VAR_SERIALIZE_INIT(var_hash);
PS_ENCODE_LOOP(
if (key_length > PS_BIN_MAX) continue;
smart_str_appendc(&buf, (unsigned char) key_length);
smart_str_appendl(&buf, key, key_length);
php_var_serialize(&buf, struc, &var_hash TSRMLS_CC);
} else {
if (key_length > PS_BIN_MAX) continue;
smart_str_appendc(&buf, (unsigned char) (key_length & PS_BIN_UNDEF));
smart_str_appendl(&buf, key, key_length);
);
if (newlen) {
*newlen = buf.len;
}
smart_str_0(&buf);
*newstr = buf.c;
PHP_VAR_SERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */
{
const char *p;
char *name;
const char *endptr = val + vallen;
zval *current;
int namelen;
int has_value;
php_unserialize_data_t var_hash;
int skip = 0;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
for (p = val; p < endptr; ) {
zval **tmp;
skip = 0;
namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF);
if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
has_value = *p & PS_BIN_UNDEF ? 0 : 1;
name = estrndup(p + 1, namelen);
p += namelen + 1;
if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) {
if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) {
skip = 1;
}
}
if (has_value) {
ALLOC_INIT_ZVAL(current);
if (php_var_unserialize(¤t, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) {
if (!skip) {
php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC);
}
} else {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
var_push_dtor_no_addref(&var_hash, ¤t);
}
if (!skip) {
PS_ADD_VARL(name, namelen);
}
efree(name);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
#define PS_DELIMITER '|'
#define PS_UNDEF_MARKER '!'
PS_SERIALIZER_ENCODE_FUNC(php) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PS_ENCODE_VARS;
PHP_VAR_SERIALIZE_INIT(var_hash);
PS_ENCODE_LOOP(
smart_str_appendl(&buf, key, key_length);
if (memchr(key, PS_DELIMITER, key_length) || memchr(key, PS_UNDEF_MARKER, key_length)) {
PHP_VAR_SERIALIZE_DESTROY(var_hash);
smart_str_free(&buf);
return FAILURE;
}
smart_str_appendc(&buf, PS_DELIMITER);
php_var_serialize(&buf, struc, &var_hash TSRMLS_CC);
} else {
smart_str_appendc(&buf, PS_UNDEF_MARKER);
smart_str_appendl(&buf, key, key_length);
smart_str_appendc(&buf, PS_DELIMITER);
);
if (newlen) {
*newlen = buf.len;
}
smart_str_0(&buf);
*newstr = buf.c;
PHP_VAR_SERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */
{
const char *p, *q;
char *name;
const char *endptr = val + vallen;
zval *current;
int namelen;
int has_value;
php_unserialize_data_t var_hash;
int skip = 0;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
p = val;
while (p < endptr) {
zval **tmp;
q = p;
skip = 0;
while (*q != PS_DELIMITER) {
if (++q >= endptr) goto break_outer_loop;
}
if (p[0] == PS_UNDEF_MARKER) {
p++;
has_value = 0;
} else {
has_value = 1;
}
namelen = q - p;
name = estrndup(p, namelen);
q++;
if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) {
if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) {
skip = 1;
}
}
if (has_value) {
ALLOC_INIT_ZVAL(current);
if (php_var_unserialize(¤t, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) {
if (!skip) {
php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC);
}
} else {
var_push_dtor_no_addref(&var_hash, ¤t);
efree(name);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
var_push_dtor_no_addref(&var_hash, ¤t);
}
if (!skip) {
PS_ADD_VARL(name, namelen);
}
skip:
efree(name);
p = q;
}
break_outer_loop:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
#define MAX_SERIALIZERS 32
#define PREDEFINED_SERIALIZERS 3
static ps_serializer ps_serializers[MAX_SERIALIZERS + 1] = {
PS_SERIALIZER_ENTRY(php_serialize),
PS_SERIALIZER_ENTRY(php),
PS_SERIALIZER_ENTRY(php_binary)
};
PHPAPI int php_session_register_serializer(const char *name, int (*encode)(PS_SERIALIZER_ENCODE_ARGS), int (*decode)(PS_SERIALIZER_DECODE_ARGS)) /* {{{ */
{
int ret = -1;
int i;
for (i = 0; i < MAX_SERIALIZERS; i++) {
if (ps_serializers[i].name == NULL) {
ps_serializers[i].name = name;
ps_serializers[i].encode = encode;
ps_serializers[i].decode = decode;
ps_serializers[i + 1].name = NULL;
ret = 0;
break;
}
}
return ret;
}
/* }}} */
/* *******************
* Storage Modules *
******************* */
#define MAX_MODULES 10
#define PREDEFINED_MODULES 2
static ps_module *ps_modules[MAX_MODULES + 1] = {
ps_files_ptr,
ps_user_ptr
};
PHPAPI int php_session_register_module(ps_module *ptr) /* {{{ */
{
int ret = -1;
int i;
for (i = 0; i < MAX_MODULES; i++) {
if (!ps_modules[i]) {
ps_modules[i] = ptr;
ret = 0;
break;
}
}
return ret;
}
/* }}} */
/* ******************
* Cache Limiters *
****************** */
typedef struct {
char *name;
void (*func)(TSRMLS_D);
} php_session_cache_limiter_t;
#define CACHE_LIMITER(name) _php_cache_limiter_##name
#define CACHE_LIMITER_FUNC(name) static void CACHE_LIMITER(name)(TSRMLS_D)
#define CACHE_LIMITER_ENTRY(name) { #name, CACHE_LIMITER(name) },
#define ADD_HEADER(a) sapi_add_header(a, strlen(a), 1);
#define MAX_STR 512
static char *month_names[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char *week_days[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
};
static inline void strcpy_gmt(char *ubuf, time_t *when) /* {{{ */
{
char buf[MAX_STR];
struct tm tm, *res;
int n;
res = php_gmtime_r(when, &tm);
if (!res) {
ubuf[0] = '\0';
return;
}
n = slprintf(buf, sizeof(buf), "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */
week_days[tm.tm_wday], tm.tm_mday,
month_names[tm.tm_mon], tm.tm_year + 1900,
tm.tm_hour, tm.tm_min,
tm.tm_sec);
memcpy(ubuf, buf, n);
ubuf[n] = '\0';
}
/* }}} */
static inline void last_modified(TSRMLS_D) /* {{{ */
{
const char *path;
struct stat sb;
char buf[MAX_STR + 1];
path = SG(request_info).path_translated;
if (path) {
if (VCWD_STAT(path, &sb) == -1) {
return;
}
#define LAST_MODIFIED "Last-Modified: "
memcpy(buf, LAST_MODIFIED, sizeof(LAST_MODIFIED) - 1);
strcpy_gmt(buf + sizeof(LAST_MODIFIED) - 1, &sb.st_mtime);
ADD_HEADER(buf);
}
}
/* }}} */
#define EXPIRES "Expires: "
CACHE_LIMITER_FUNC(public) /* {{{ */
{
char buf[MAX_STR + 1];
struct timeval tv;
time_t now;
gettimeofday(&tv, NULL);
now = tv.tv_sec + PS(cache_expire) * 60;
memcpy(buf, EXPIRES, sizeof(EXPIRES) - 1);
strcpy_gmt(buf + sizeof(EXPIRES) - 1, &now);
ADD_HEADER(buf);
snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=%ld", PS(cache_expire) * 60); /* SAFE */
ADD_HEADER(buf);
last_modified(TSRMLS_C);
}
/* }}} */
CACHE_LIMITER_FUNC(private_no_expire) /* {{{ */
{
char buf[MAX_STR + 1];
snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=%ld, pre-check=%ld", PS(cache_expire) * 60, PS(cache_expire) * 60); /* SAFE */
ADD_HEADER(buf);
last_modified(TSRMLS_C);
}
/* }}} */
CACHE_LIMITER_FUNC(private) /* {{{ */
{
ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
CACHE_LIMITER(private_no_expire)(TSRMLS_C);
}
/* }}} */
CACHE_LIMITER_FUNC(nocache) /* {{{ */
{
ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
/* For HTTP/1.1 conforming clients and the rest (MSIE 5) */
ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
/* For HTTP/1.0 conforming clients */
ADD_HEADER("Pragma: no-cache");
}
/* }}} */
static php_session_cache_limiter_t php_session_cache_limiters[] = {
CACHE_LIMITER_ENTRY(public)
CACHE_LIMITER_ENTRY(private)
CACHE_LIMITER_ENTRY(private_no_expire)
CACHE_LIMITER_ENTRY(nocache)
{0}
};
static int php_session_cache_limiter(TSRMLS_D) /* {{{ */
{
php_session_cache_limiter_t *lim;
if (PS(cache_limiter)[0] == '\0') return 0;
if (SG(headers_sent)) {
const char *output_start_filename = php_output_get_start_filename(TSRMLS_C);
int output_start_lineno = php_output_get_start_lineno(TSRMLS_C);
if (output_start_filename) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cache limiter - headers already sent (output started at %s:%d)", output_start_filename, output_start_lineno);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cache limiter - headers already sent");
}
return -2;
}
for (lim = php_session_cache_limiters; lim->name; lim++) {
if (!strcasecmp(lim->name, PS(cache_limiter))) {
lim->func(TSRMLS_C);
return 0;
}
}
return -1;
}
/* }}} */
/* *********************
* Cookie Management *
********************* */
#define COOKIE_SET_COOKIE "Set-Cookie: "
#define COOKIE_EXPIRES "; expires="
#define COOKIE_MAX_AGE "; Max-Age="
#define COOKIE_PATH "; path="
#define COOKIE_DOMAIN "; domain="
#define COOKIE_SECURE "; secure"
#define COOKIE_HTTPONLY "; HttpOnly"
/*
* Remove already sent session ID cookie.
* It must be directly removed from SG(sapi_header) because sapi_add_header_ex()
* removes all of matching cookie. i.e. It deletes all of Set-Cookie headers.
*/
static void php_session_remove_cookie(TSRMLS_D) {
sapi_header_struct *header;
zend_llist *l = &SG(sapi_headers).headers;
zend_llist_element *next;
zend_llist_element *current;
char *session_cookie, *e_session_name;
int session_cookie_len, len = sizeof("Set-Cookie")-1;
e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)), NULL);
spprintf(&session_cookie, 0, "Set-Cookie: %s=", e_session_name);
efree(e_session_name);
session_cookie_len = strlen(session_cookie);
current = l->head;
while (current) {
header = (sapi_header_struct *)(current->data);
next = current->next;
if (header->header_len > len && header->header[len] == ':'
&& !strncmp(header->header, session_cookie, session_cookie_len)) {
if (current->prev) {
current->prev->next = next;
} else {
l->head = next;
}
if (next) {
next->prev = current->prev;
} else {
l->tail = current->prev;
}
sapi_free_header(header);
efree(current);
--l->count;
}
current = next;
}
efree(session_cookie);
}
static void php_session_send_cookie(TSRMLS_D) /* {{{ */
{
smart_str ncookie = {0};
char *date_fmt = NULL;
char *e_session_name, *e_id;
if (SG(headers_sent)) {
const char *output_start_filename = php_output_get_start_filename(TSRMLS_C);
int output_start_lineno = php_output_get_start_lineno(TSRMLS_C);
if (output_start_filename) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent by (output started at %s:%d)", output_start_filename, output_start_lineno);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent");
}
return;
}
/* URL encode session_name and id because they might be user supplied */
e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)), NULL);
e_id = php_url_encode(PS(id), strlen(PS(id)), NULL);
smart_str_appends(&ncookie, COOKIE_SET_COOKIE);
smart_str_appends(&ncookie, e_session_name);
smart_str_appendc(&ncookie, '=');
smart_str_appends(&ncookie, e_id);
efree(e_session_name);
efree(e_id);
if (PS(cookie_lifetime) > 0) {
struct timeval tv;
time_t t;
gettimeofday(&tv, NULL);
t = tv.tv_sec + PS(cookie_lifetime);
if (t > 0) {
date_fmt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0 TSRMLS_CC);
smart_str_appends(&ncookie, COOKIE_EXPIRES);
smart_str_appends(&ncookie, date_fmt);
efree(date_fmt);
smart_str_appends(&ncookie, COOKIE_MAX_AGE);
smart_str_append_long(&ncookie, PS(cookie_lifetime));
}
}
if (PS(cookie_path)[0]) {
smart_str_appends(&ncookie, COOKIE_PATH);
smart_str_appends(&ncookie, PS(cookie_path));
}
if (PS(cookie_domain)[0]) {
smart_str_appends(&ncookie, COOKIE_DOMAIN);
smart_str_appends(&ncookie, PS(cookie_domain));
}
if (PS(cookie_secure)) {
smart_str_appends(&ncookie, COOKIE_SECURE);
}
if (PS(cookie_httponly)) {
smart_str_appends(&ncookie, COOKIE_HTTPONLY);
}
smart_str_0(&ncookie);
php_session_remove_cookie(TSRMLS_C); /* remove already sent session ID cookie */
sapi_add_header_ex(ncookie.c, ncookie.len, 0, 0 TSRMLS_CC);
}
/* }}} */
PHPAPI ps_module *_php_find_ps_module(char *name TSRMLS_DC) /* {{{ */
{
ps_module *ret = NULL;
ps_module **mod;
int i;
for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
if (*mod && !strcasecmp(name, (*mod)->s_name)) {
ret = *mod;
break;
}
}
return ret;
}
/* }}} */
PHPAPI const ps_serializer *_php_find_ps_serializer(char *name TSRMLS_DC) /* {{{ */
{
const ps_serializer *ret = NULL;
const ps_serializer *mod;
for (mod = ps_serializers; mod->name; mod++) {
if (!strcasecmp(name, mod->name)) {
ret = mod;
break;
}
}
return ret;
}
/* }}} */
static void ppid2sid(zval **ppid TSRMLS_DC) {
if (Z_TYPE_PP(ppid) != IS_STRING) {
PS(id) = NULL;
PS(send_cookie) = 1;
} else {
convert_to_string((*ppid));
PS(id) = estrndup(Z_STRVAL_PP(ppid), Z_STRLEN_PP(ppid));
PS(send_cookie) = 0;
}
}
PHPAPI void php_session_reset_id(TSRMLS_D) /* {{{ */
{
int module_number = PS(module_number);
if (!PS(id)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot set session ID - session ID is not initialized");
return;
}
if (PS(use_cookies) && PS(send_cookie)) {
php_session_send_cookie(TSRMLS_C);
PS(send_cookie) = 0;
}
/* if the SID constant exists, destroy it. */
zend_hash_del(EG(zend_constants), "sid", sizeof("sid"));
if (PS(define_sid)) {
smart_str var = {0};
smart_str_appends(&var, PS(session_name));
smart_str_appendc(&var, '=');
smart_str_appends(&var, PS(id));
smart_str_0(&var);
REGISTER_STRINGL_CONSTANT("SID", var.c, var.len, 0);
} else {
REGISTER_STRINGL_CONSTANT("SID", STR_EMPTY_ALLOC(), 0, 0);
}
if (PS(apply_trans_sid)) {
php_url_scanner_reset_vars(TSRMLS_C);
php_url_scanner_add_var(PS(session_name), strlen(PS(session_name)), PS(id), strlen(PS(id)), 1 TSRMLS_CC);
}
}
/* }}} */
PHPAPI void php_session_start(TSRMLS_D) /* {{{ */
{
zval **ppid;
zval **data;
char *p, *value;
int nrand;
int lensess;
if (PS(use_only_cookies)) {
PS(apply_trans_sid) = 0;
} else {
PS(apply_trans_sid) = PS(use_trans_sid);
}
switch (PS(session_status)) {
case php_session_active:
php_error(E_NOTICE, "A session had already been started - ignoring session_start()");
return;
break;
case php_session_disabled:
value = zend_ini_string("session.save_handler", sizeof("session.save_handler"), 0);
if (!PS(mod) && value) {
PS(mod) = _php_find_ps_module(value TSRMLS_CC);
if (!PS(mod)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find save handler '%s' - session startup failed", value);
return;
}
}
value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler"), 0);
if (!PS(serializer) && value) {
PS(serializer) = _php_find_ps_serializer(value TSRMLS_CC);
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find serialization handler '%s' - session startup failed", value);
return;
}
}
PS(session_status) = php_session_none;
/* fallthrough */
default:
case php_session_none:
PS(define_sid) = 1;
PS(send_cookie) = 1;
}
lensess = strlen(PS(session_name));
/* Cookies are preferred, because initially
* cookie and get variables will be available. */
if (!PS(id)) {
if (PS(use_cookies) && zend_hash_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS
) {
ppid2sid(ppid TSRMLS_CC);
PS(apply_trans_sid) = 0;
PS(define_sid) = 0;
}
if (!PS(use_only_cookies) && !PS(id) &&
zend_hash_find(&EG(symbol_table), "_GET", sizeof("_GET"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS
) {
ppid2sid(ppid TSRMLS_CC);
}
if (!PS(use_only_cookies) && !PS(id) &&
zend_hash_find(&EG(symbol_table), "_POST", sizeof("_POST"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS
) {
ppid2sid(ppid TSRMLS_CC);
}
}
/* Check the REQUEST_URI symbol for a string of the form
* '<session-name>=<session-id>' to allow URLs of the form
* http://yoursite/<session-name>=<session-id>/script.php */
if (!PS(use_only_cookies) && !PS(id) && PG(http_globals)[TRACK_VARS_SERVER] &&
zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_STRING &&
(p = strstr(Z_STRVAL_PP(data), PS(session_name))) &&
p[lensess] == '='
) {
char *q;
p += lensess + 1;
if ((q = strpbrk(p, "/?\\"))) {
PS(id) = estrndup(p, q - p);
PS(send_cookie) = 0;
}
}
/* Check whether the current request was referred to by
* an external site which invalidates the previously found id. */
if (PS(id) &&
PS(extern_referer_chk)[0] != '\0' &&
PG(http_globals)[TRACK_VARS_SERVER] &&
zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_REFERER", sizeof("HTTP_REFERER"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_STRING &&
Z_STRLEN_PP(data) != 0 &&
strstr(Z_STRVAL_PP(data), PS(extern_referer_chk)) == NULL
) {
efree(PS(id));
PS(id) = NULL;
PS(send_cookie) = 1;
if (PS(use_trans_sid) && !PS(use_only_cookies)) {
PS(apply_trans_sid) = 1;
}
}
/* Finally check session id for dangarous characters
* Security note: session id may be embedded in HTML pages.*/
if (PS(id) && strpbrk(PS(id), "\r\n\t <>'\"\\")) {
efree(PS(id));
PS(id) = NULL;
}
php_session_initialize(TSRMLS_C);
php_session_cache_limiter(TSRMLS_C);
if ((PS(mod_data) || PS(mod_user_implemented)) && PS(gc_probability) > 0) {
int nrdels = -1;
nrand = (int) ((float) PS(gc_divisor) * php_combined_lcg(TSRMLS_C));
if (nrand < PS(gc_probability)) {
PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &nrdels TSRMLS_CC);
#ifdef SESSION_DEBUG
if (nrdels != -1) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "purged %d expired session objects", nrdels);
}
#endif
}
}
}
/* }}} */
static void php_session_flush(TSRMLS_D) /* {{{ */
{
if (PS(session_status) == php_session_active) {
PS(session_status) = php_session_none;
php_session_save_current_state(TSRMLS_C);
}
}
/* }}} */
static void php_session_abort(TSRMLS_D) /* {{{ */
{
if (PS(session_status) == php_session_active) {
PS(session_status) = php_session_none;
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
}
}
}
/* }}} */
static void php_session_reset(TSRMLS_D) /* {{{ */
{
if (PS(session_status) == php_session_active) {
php_session_initialize(TSRMLS_C);
}
}
/* }}} */
PHPAPI void session_adapt_url(const char *url, size_t urllen, char **new, size_t *newlen TSRMLS_DC) /* {{{ */
{
if (PS(apply_trans_sid) && (PS(session_status) == php_session_active)) {
*new = php_url_scanner_adapt_single_url(url, urllen, PS(session_name), PS(id), newlen TSRMLS_CC);
}
}
/* }}} */
/* ********************************
* Userspace exported functions *
******************************** */
/* {{{ proto void session_set_cookie_params(int lifetime [, string path [, string domain [, bool secure[, bool httponly]]]])
Set session cookie parameters */
static PHP_FUNCTION(session_set_cookie_params)
{
zval **lifetime = NULL;
char *path = NULL, *domain = NULL;
int path_len, domain_len, argc = ZEND_NUM_ARGS();
zend_bool secure = 0, httponly = 0;
if (!PS(use_cookies) ||
zend_parse_parameters(argc TSRMLS_CC, "Z|ssbb", &lifetime, &path, &path_len, &domain, &domain_len, &secure, &httponly) == FAILURE) {
return;
}
convert_to_string_ex(lifetime);
zend_alter_ini_entry("session.cookie_lifetime", sizeof("session.cookie_lifetime"), Z_STRVAL_PP(lifetime), Z_STRLEN_PP(lifetime), PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
if (path) {
zend_alter_ini_entry("session.cookie_path", sizeof("session.cookie_path"), path, path_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
if (domain) {
zend_alter_ini_entry("session.cookie_domain", sizeof("session.cookie_domain"), domain, domain_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
if (argc > 3) {
zend_alter_ini_entry("session.cookie_secure", sizeof("session.cookie_secure"), secure ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
if (argc > 4) {
zend_alter_ini_entry("session.cookie_httponly", sizeof("session.cookie_httponly"), httponly ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto array session_get_cookie_params(void)
Return the session cookie parameters */
static PHP_FUNCTION(session_get_cookie_params)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_assoc_long(return_value, "lifetime", PS(cookie_lifetime));
add_assoc_string(return_value, "path", PS(cookie_path), 1);
add_assoc_string(return_value, "domain", PS(cookie_domain), 1);
add_assoc_bool(return_value, "secure", PS(cookie_secure));
add_assoc_bool(return_value, "httponly", PS(cookie_httponly));
}
/* }}} */
/* {{{ proto string session_name([string newname])
Return the current session name. If newname is given, the session name is replaced with newname */
static PHP_FUNCTION(session_name)
{
char *name = NULL;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
RETVAL_STRING(PS(session_name), 1);
if (name) {
zend_alter_ini_entry("session.name", sizeof("session.name"), name, name_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto string session_module_name([string newname])
Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname */
static PHP_FUNCTION(session_module_name)
{
char *name = NULL;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
/* Set return_value to current module name */
if (PS(mod) && PS(mod)->s_name) {
RETVAL_STRING(safe_estrdup(PS(mod)->s_name), 0);
} else {
RETVAL_EMPTY_STRING();
}
if (name) {
if (!_php_find_ps_module(name TSRMLS_CC)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find named PHP session module (%s)", name);
zval_dtor(return_value);
RETURN_FALSE;
}
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
}
PS(mod_data) = NULL;
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), name, name_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto void session_set_save_handler(string open, string close, string read, string write, string destroy, string gc, string create_sid)
Sets user-level functions */
static PHP_FUNCTION(session_set_save_handler)
{
zval ***args = NULL;
int i, num_args, argc = ZEND_NUM_ARGS();
char *name;
if (PS(session_status) != php_session_none) {
RETURN_FALSE;
}
if (argc > 0 && argc <= 2) {
zval *obj = NULL, *callback = NULL;
zend_uint func_name_len;
char *func_name;
HashPosition pos;
zend_function *default_mptr, *current_mptr;
ulong func_index;
php_shutdown_function_entry shutdown_function_entry;
zend_bool register_shutdown = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|b", &obj, php_session_iface_entry, ®ister_shutdown) == FAILURE) {
RETURN_FALSE;
}
/* Find implemented methods - SessionHandlerInterface */
zend_hash_internal_pointer_reset_ex(&php_session_iface_entry->function_table, &pos);
i = 0;
while (zend_hash_get_current_data_ex(&php_session_iface_entry->function_table, (void **) &default_mptr, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_session_iface_entry->function_table, &func_name, &func_name_len, &func_index, 0, &pos);
if (zend_hash_find(&Z_OBJCE_P(obj)->function_table, func_name, func_name_len, (void **)¤t_mptr) == SUCCESS) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
MAKE_STD_ZVAL(callback);
array_init_size(callback, 2);
Z_ADDREF_P(obj);
add_next_index_zval(callback, obj);
add_next_index_stringl(callback, func_name, func_name_len - 1, 1);
PS(mod_user_names).names[i] = callback;
} else {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Session handler's function table is corrupt");
RETURN_FALSE;
}
zend_hash_move_forward_ex(&php_session_iface_entry->function_table, &pos);
++i;
}
/* Find implemented methods - SessionIdInterface (optional) */
zend_hash_internal_pointer_reset_ex(&php_session_id_iface_entry->function_table, &pos);
while (zend_hash_get_current_data_ex(&php_session_id_iface_entry->function_table, (void **) &default_mptr, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_session_id_iface_entry->function_table, &func_name, &func_name_len, &func_index, 0, &pos);
if (zend_hash_find(&Z_OBJCE_P(obj)->function_table, func_name, func_name_len, (void **)¤t_mptr) == SUCCESS) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
MAKE_STD_ZVAL(callback);
array_init_size(callback, 2);
Z_ADDREF_P(obj);
add_next_index_zval(callback, obj);
add_next_index_stringl(callback, func_name, func_name_len - 1, 1);
PS(mod_user_names).names[i] = callback;
}
zend_hash_move_forward_ex(&php_session_id_iface_entry->function_table, &pos);
++i;
}
if (register_shutdown) {
/* create shutdown function */
shutdown_function_entry.arg_count = 1;
shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), 1, 0);
MAKE_STD_ZVAL(callback);
ZVAL_STRING(callback, "session_register_shutdown", 1);
shutdown_function_entry.arguments[0] = callback;
/* add shutdown function, removing the old one if it exists */
if (!register_user_shutdown_function("session_shutdown", sizeof("session_shutdown"), &shutdown_function_entry TSRMLS_CC)) {
zval_ptr_dtor(&callback);
efree(shutdown_function_entry.arguments);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to register session shutdown function");
RETURN_FALSE;
}
} else {
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);
}
if (PS(mod) && PS(session_status) == php_session_none && PS(mod) != &ps_mod_user) {
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
RETURN_TRUE;
}
if (argc != 6 && argc != 7) {
WRONG_PARAM_COUNT;
}
if (zend_parse_parameters(argc TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
return;
}
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);
/* at this point argc can only be 6 or 7 */
for (i = 0; i < argc; i++) {
if (!zend_is_callable(*args[i], 0, &name TSRMLS_CC)) {
efree(args);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument %d is not a valid callback", i+1);
efree(name);
RETURN_FALSE;
}
efree(name);
}
if (PS(mod) && PS(mod) != &ps_mod_user) {
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
for (i = 0; i < argc; i++) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
Z_ADDREF_PP(args[i]);
PS(mod_user_names).names[i] = *args[i];
}
efree(args);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string session_save_path([string newname])
Return the current save path passed to module_name. If newname is given, the save path is replaced with newname */
static PHP_FUNCTION(session_save_path)
{
char *name = NULL;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
RETVAL_STRING(PS(save_path), 1);
if (name) {
if (memchr(name, '\0', name_len) != NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The save_path cannot contain NULL characters");
zval_dtor(return_value);
RETURN_FALSE;
}
zend_alter_ini_entry("session.save_path", sizeof("session.save_path"), name, name_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto string session_id([string newid])
Return the current session id. If newid is given, the session id is replaced with newid */
static PHP_FUNCTION(session_id)
{
char *name = NULL;
int name_len, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
if (PS(id)) {
RETVAL_STRING(PS(id), 1);
} else {
RETVAL_EMPTY_STRING();
}
if (name) {
if (PS(id)) {
efree(PS(id));
}
PS(id) = estrndup(name, name_len);
}
}
/* }}} */
/* {{{ proto bool session_regenerate_id([bool delete_old_session])
Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session. */
static PHP_FUNCTION(session_regenerate_id)
{
zend_bool del_ses = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &del_ses) == FAILURE) {
return;
}
if (SG(headers_sent) && PS(use_cookies)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot regenerate session id - headers already sent");
RETURN_FALSE;
}
if (PS(session_status) == php_session_active) {
if (PS(id)) {
if (del_ses && PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
RETURN_FALSE;
}
efree(PS(id));
}
PS(id) = PS(mod)->s_create_sid(&PS(mod_data), NULL TSRMLS_CC);
if (PS(id)) {
PS(send_cookie) = 1;
php_session_reset_id(TSRMLS_C);
RETURN_TRUE;
} else {
PS(id) = STR_EMPTY_ALLOC();
}
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto string session_cache_limiter([string new_cache_limiter])
Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter */
static PHP_FUNCTION(session_cache_limiter)
{
char *limiter = NULL;
int limiter_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &limiter, &limiter_len) == FAILURE) {
return;
}
RETVAL_STRING(PS(cache_limiter), 1);
if (limiter) {
zend_alter_ini_entry("session.cache_limiter", sizeof("session.cache_limiter"), limiter, limiter_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto int session_cache_expire([int new_cache_expire])
Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire */
static PHP_FUNCTION(session_cache_expire)
{
zval **expires = NULL;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|Z", &expires) == FAILURE) {
return;
}
RETVAL_LONG(PS(cache_expire));
if (argc == 1) {
convert_to_string_ex(expires);
zend_alter_ini_entry("session.cache_expire", sizeof("session.cache_expire"), Z_STRVAL_PP(expires), Z_STRLEN_PP(expires), ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto string session_encode(void)
Serializes the current setup and returns the serialized representation */
static PHP_FUNCTION(session_encode)
{
int len;
char *enc;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
enc = php_session_encode(&len TSRMLS_CC);
if (enc == NULL) {
RETURN_FALSE;
}
RETVAL_STRINGL(enc, len, 0);
}
/* }}} */
/* {{{ proto bool session_decode(string data)
Deserializes data and reinitializes the variables */
static PHP_FUNCTION(session_decode)
{
char *str;
int str_len;
if (PS(session_status) == php_session_none) {
RETURN_FALSE;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) {
return;
}
RETVAL_BOOL(php_session_decode(str, str_len TSRMLS_CC) == SUCCESS);
}
/* }}} */
/* {{{ proto bool session_start(void)
Begin session - reinitializes freezed variables, registers browsers etc */
static PHP_FUNCTION(session_start)
{
/* skipping check for non-zero args for performance reasons here ?*/
if (PS(id) && !strlen(PS(id))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot start session with empty session ID");
RETURN_FALSE;
}
php_session_start(TSRMLS_C);
if (PS(session_status) != php_session_active) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool session_destroy(void)
Destroy the current session and all data associated with it */
static PHP_FUNCTION(session_destroy)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(php_session_destroy(TSRMLS_C) == SUCCESS);
}
/* }}} */
/* {{{ proto void session_unset(void)
Unset all registered variables */
static PHP_FUNCTION(session_unset)
{
if (PS(session_status) == php_session_none) {
RETURN_FALSE;
}
IF_SESSION_VARS() {
HashTable *ht_sess_var;
SEPARATE_ZVAL_IF_NOT_REF(&PS(http_session_vars));
ht_sess_var = Z_ARRVAL_P(PS(http_session_vars));
/* Clean $_SESSION. */
zend_hash_clean(ht_sess_var);
}
}
/* }}} */
/* {{{ proto void session_write_close(void)
Write session data and end session */
static PHP_FUNCTION(session_write_close)
{
php_session_flush(TSRMLS_C);
}
/* }}} */
/* {{{ proto void session_abort(void)
Abort session and end session. Session data will not be written */
static PHP_FUNCTION(session_abort)
{
php_session_abort(TSRMLS_C);
}
/* }}} */
/* {{{ proto void session_reset(void)
Reset session data from saved session data */
static PHP_FUNCTION(session_reset)
{
php_session_reset(TSRMLS_C);
}
/* }}} */
/* {{{ proto int session_status(void)
Returns the current session status */
static PHP_FUNCTION(session_status)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(PS(session_status));
}
/* }}} */
/* {{{ proto void session_register_shutdown(void)
Registers session_write_close() as a shutdown function */
static PHP_FUNCTION(session_register_shutdown)
{
php_shutdown_function_entry shutdown_function_entry;
zval *callback;
/* This function is registered itself as a shutdown function by
* session_set_save_handler($obj). The reason we now register another
* shutdown function is in case the user registered their own shutdown
* function after calling session_set_save_handler(), which expects
* the session still to be available.
*/
shutdown_function_entry.arg_count = 1;
shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), 1, 0);
MAKE_STD_ZVAL(callback);
ZVAL_STRING(callback, "session_write_close", 1);
shutdown_function_entry.arguments[0] = callback;
if (!append_user_shutdown_function(shutdown_function_entry TSRMLS_CC)) {
zval_ptr_dtor(&callback);
efree(shutdown_function_entry.arguments);
/* Unable to register shutdown function, presumably because of lack
* of memory, so flush the session now. It would be done in rshutdown
* anyway but the handler will have had it's dtor called by then.
* If the user does have a later shutdown function which needs the
* session then tough luck.
*/
php_session_flush(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to register session flush function");
}
}
/* }}} */
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_name, 0, 0, 0)
ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_module_name, 0, 0, 0)
ZEND_ARG_INFO(0, module)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_save_path, 0, 0, 0)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_id, 0, 0, 0)
ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_regenerate_id, 0, 0, 0)
ZEND_ARG_INFO(0, delete_old_session)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_decode, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_void, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_set_save_handler, 0, 0, 1)
ZEND_ARG_INFO(0, open)
ZEND_ARG_INFO(0, close)
ZEND_ARG_INFO(0, read)
ZEND_ARG_INFO(0, write)
ZEND_ARG_INFO(0, destroy)
ZEND_ARG_INFO(0, gc)
ZEND_ARG_INFO(0, create_sid)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_cache_limiter, 0, 0, 0)
ZEND_ARG_INFO(0, cache_limiter)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_cache_expire, 0, 0, 0)
ZEND_ARG_INFO(0, new_cache_expire)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_set_cookie_params, 0, 0, 1)
ZEND_ARG_INFO(0, lifetime)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, domain)
ZEND_ARG_INFO(0, secure)
ZEND_ARG_INFO(0, httponly)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_open, 0)
ZEND_ARG_INFO(0, save_path)
ZEND_ARG_INFO(0, session_name)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_close, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_read, 0)
ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_write, 0)
ZEND_ARG_INFO(0, key)
ZEND_ARG_INFO(0, val)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_destroy, 0)
ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_gc, 0)
ZEND_ARG_INFO(0, maxlifetime)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_create_sid, 0)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ session_functions[]
*/
static const zend_function_entry session_functions[] = {
PHP_FE(session_name, arginfo_session_name)
PHP_FE(session_module_name, arginfo_session_module_name)
PHP_FE(session_save_path, arginfo_session_save_path)
PHP_FE(session_id, arginfo_session_id)
PHP_FE(session_regenerate_id, arginfo_session_regenerate_id)
PHP_FE(session_decode, arginfo_session_decode)
PHP_FE(session_encode, arginfo_session_void)
PHP_FE(session_start, arginfo_session_void)
PHP_FE(session_destroy, arginfo_session_void)
PHP_FE(session_unset, arginfo_session_void)
PHP_FE(session_set_save_handler, arginfo_session_set_save_handler)
PHP_FE(session_cache_limiter, arginfo_session_cache_limiter)
PHP_FE(session_cache_expire, arginfo_session_cache_expire)
PHP_FE(session_set_cookie_params, arginfo_session_set_cookie_params)
PHP_FE(session_get_cookie_params, arginfo_session_void)
PHP_FE(session_write_close, arginfo_session_void)
PHP_FE(session_abort, arginfo_session_void)
PHP_FE(session_reset, arginfo_session_void)
PHP_FE(session_status, arginfo_session_void)
PHP_FE(session_register_shutdown, arginfo_session_void)
PHP_FALIAS(session_commit, session_write_close, arginfo_session_void)
PHP_FE_END
};
/* }}} */
/* {{{ SessionHandlerInterface functions[]
*/
static const zend_function_entry php_session_iface_functions[] = {
PHP_ABSTRACT_ME(SessionHandlerInterface, open, arginfo_session_class_open)
PHP_ABSTRACT_ME(SessionHandlerInterface, close, arginfo_session_class_close)
PHP_ABSTRACT_ME(SessionHandlerInterface, read, arginfo_session_class_read)
PHP_ABSTRACT_ME(SessionHandlerInterface, write, arginfo_session_class_write)
PHP_ABSTRACT_ME(SessionHandlerInterface, destroy, arginfo_session_class_destroy)
PHP_ABSTRACT_ME(SessionHandlerInterface, gc, arginfo_session_class_gc)
{ NULL, NULL, NULL }
};
/* }}} */
/* {{{ SessionIdInterface functions[]
*/
static const zend_function_entry php_session_id_iface_functions[] = {
PHP_ABSTRACT_ME(SessionIdInterface, create_sid, arginfo_session_class_create_sid)
{ NULL, NULL, NULL }
};
/* }}} */
/* {{{ SessionHandler functions[]
*/
static const zend_function_entry php_session_class_functions[] = {
PHP_ME(SessionHandler, open, arginfo_session_class_open, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, close, arginfo_session_class_close, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, read, arginfo_session_class_read, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, write, arginfo_session_class_write, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, destroy, arginfo_session_class_destroy, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, gc, arginfo_session_class_gc, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, create_sid, arginfo_session_class_create_sid, ZEND_ACC_PUBLIC)
{ NULL, NULL, NULL }
};
/* }}} */
/* ********************************
* Module Setup and Destruction *
******************************** */
static int php_rinit_session(zend_bool auto_start TSRMLS_DC) /* {{{ */
{
php_rinit_session_globals(TSRMLS_C);
if (PS(mod) == NULL) {
char *value;
value = zend_ini_string("session.save_handler", sizeof("session.save_handler"), 0);
if (value) {
PS(mod) = _php_find_ps_module(value TSRMLS_CC);
}
}
if (PS(serializer) == NULL) {
char *value;
value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler"), 0);
if (value) {
PS(serializer) = _php_find_ps_serializer(value TSRMLS_CC);
}
}
if (PS(mod) == NULL || PS(serializer) == NULL) {
/* current status is unusable */
PS(session_status) = php_session_disabled;
return SUCCESS;
}
if (auto_start) {
php_session_start(TSRMLS_C);
}
return SUCCESS;
} /* }}} */
static PHP_RINIT_FUNCTION(session) /* {{{ */
{
return php_rinit_session(PS(auto_start) TSRMLS_CC);
}
/* }}} */
static PHP_RSHUTDOWN_FUNCTION(session) /* {{{ */
{
int i;
zend_try {
php_session_flush(TSRMLS_C);
} zend_end_try();
php_rshutdown_session_globals(TSRMLS_C);
/* this should NOT be done in php_rshutdown_session_globals() */
for (i = 0; i < 7; i++) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
PS(mod_user_names).names[i] = NULL;
}
}
return SUCCESS;
}
/* }}} */
static PHP_GINIT_FUNCTION(ps) /* {{{ */
{
int i;
ps_globals->save_path = NULL;
ps_globals->session_name = NULL;
ps_globals->id = NULL;
ps_globals->mod = NULL;
ps_globals->serializer = NULL;
ps_globals->mod_data = NULL;
ps_globals->session_status = php_session_none;
ps_globals->default_mod = NULL;
ps_globals->mod_user_implemented = 0;
ps_globals->mod_user_is_open = 0;
for (i = 0; i < 7; i++) {
ps_globals->mod_user_names.names[i] = NULL;
}
ps_globals->http_session_vars = NULL;
}
/* }}} */
static PHP_MINIT_FUNCTION(session) /* {{{ */
{
zend_class_entry ce;
zend_register_auto_global("_SESSION", sizeof("_SESSION")-1, 0, NULL TSRMLS_CC);
PS(module_number) = module_number; /* if we really need this var we need to init it in zts mode as well! */
PS(session_status) = php_session_none;
REGISTER_INI_ENTRIES();
#ifdef HAVE_LIBMM
PHP_MINIT(ps_mm) (INIT_FUNC_ARGS_PASSTHRU);
#endif
php_session_rfc1867_orig_callback = php_rfc1867_callback;
php_rfc1867_callback = php_session_rfc1867_callback;
/* Register interfaces */
INIT_CLASS_ENTRY(ce, PS_IFACE_NAME, php_session_iface_functions);
php_session_iface_entry = zend_register_internal_class(&ce TSRMLS_CC);
php_session_iface_entry->ce_flags |= ZEND_ACC_INTERFACE;
INIT_CLASS_ENTRY(ce, PS_SID_IFACE_NAME, php_session_id_iface_functions);
php_session_id_iface_entry = zend_register_internal_class(&ce TSRMLS_CC);
php_session_id_iface_entry->ce_flags |= ZEND_ACC_INTERFACE;
/* Register base class */
INIT_CLASS_ENTRY(ce, PS_CLASS_NAME, php_session_class_functions);
php_session_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_class_implements(php_session_class_entry TSRMLS_CC, 1, php_session_iface_entry);
zend_class_implements(php_session_class_entry TSRMLS_CC, 1, php_session_id_iface_entry);
REGISTER_LONG_CONSTANT("PHP_SESSION_DISABLED", php_session_disabled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_SESSION_NONE", php_session_none, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_SESSION_ACTIVE", php_session_active, CONST_CS | CONST_PERSISTENT);
return SUCCESS;
}
/* }}} */
static PHP_MSHUTDOWN_FUNCTION(session) /* {{{ */
{
UNREGISTER_INI_ENTRIES();
#ifdef HAVE_LIBMM
PHP_MSHUTDOWN(ps_mm) (SHUTDOWN_FUNC_ARGS_PASSTHRU);
#endif
/* reset rfc1867 callbacks */
php_session_rfc1867_orig_callback = NULL;
if (php_rfc1867_callback == php_session_rfc1867_callback) {
php_rfc1867_callback = NULL;
}
ps_serializers[PREDEFINED_SERIALIZERS].name = NULL;
memset(&ps_modules[PREDEFINED_MODULES], 0, (MAX_MODULES-PREDEFINED_MODULES)*sizeof(ps_module *));
return SUCCESS;
}
/* }}} */
static PHP_MINFO_FUNCTION(session) /* {{{ */
{
ps_module **mod;
ps_serializer *ser;
smart_str save_handlers = {0};
smart_str ser_handlers = {0};
int i;
/* Get save handlers */
for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
if (*mod && (*mod)->s_name) {
smart_str_appends(&save_handlers, (*mod)->s_name);
smart_str_appendc(&save_handlers, ' ');
}
}
/* Get serializer handlers */
for (i = 0, ser = ps_serializers; i < MAX_SERIALIZERS; i++, ser++) {
if (ser && ser->name) {
smart_str_appends(&ser_handlers, ser->name);
smart_str_appendc(&ser_handlers, ' ');
}
}
php_info_print_table_start();
php_info_print_table_row(2, "Session Support", "enabled" );
if (save_handlers.c) {
smart_str_0(&save_handlers);
php_info_print_table_row(2, "Registered save handlers", save_handlers.c);
smart_str_free(&save_handlers);
} else {
php_info_print_table_row(2, "Registered save handlers", "none");
}
if (ser_handlers.c) {
smart_str_0(&ser_handlers);
php_info_print_table_row(2, "Registered serializer handlers", ser_handlers.c);
smart_str_free(&ser_handlers);
} else {
php_info_print_table_row(2, "Registered serializer handlers", "none");
}
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
static const zend_module_dep session_deps[] = { /* {{{ */
ZEND_MOD_OPTIONAL("hash")
ZEND_MOD_REQUIRED("spl")
ZEND_MOD_END
};
/* }}} */
/* ************************
* Upload hook handling *
************************ */
static zend_bool early_find_sid_in(zval *dest, int where, php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
zval **ppid;
if (!PG(http_globals)[where]) {
return 0;
}
if (zend_hash_find(Z_ARRVAL_P(PG(http_globals)[where]), PS(session_name), progress->sname_len+1, (void **)&ppid) == SUCCESS
&& Z_TYPE_PP(ppid) == IS_STRING) {
zval_dtor(dest);
ZVAL_ZVAL(dest, *ppid, 1, 0);
return 1;
}
return 0;
} /* }}} */
static void php_session_rfc1867_early_find_sid(php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
if (PS(use_cookies)) {
sapi_module.treat_data(PARSE_COOKIE, NULL, NULL TSRMLS_CC);
if (early_find_sid_in(&progress->sid, TRACK_VARS_COOKIE, progress TSRMLS_CC)) {
progress->apply_trans_sid = 0;
return;
}
}
if (PS(use_only_cookies)) {
return;
}
sapi_module.treat_data(PARSE_GET, NULL, NULL TSRMLS_CC);
early_find_sid_in(&progress->sid, TRACK_VARS_GET, progress TSRMLS_CC);
} /* }}} */
static zend_bool php_check_cancel_upload(php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
zval **progress_ary, **cancel_upload;
if (zend_symtable_find(Z_ARRVAL_P(PS(http_session_vars)), progress->key.c, progress->key.len+1, (void**)&progress_ary) != SUCCESS) {
return 0;
}
if (Z_TYPE_PP(progress_ary) != IS_ARRAY) {
return 0;
}
if (zend_hash_find(Z_ARRVAL_PP(progress_ary), "cancel_upload", sizeof("cancel_upload"), (void**)&cancel_upload) != SUCCESS) {
return 0;
}
return Z_TYPE_PP(cancel_upload) == IS_BOOL && Z_LVAL_PP(cancel_upload);
} /* }}} */
static void php_session_rfc1867_update(php_session_rfc1867_progress *progress, int force_update TSRMLS_DC) /* {{{ */
{
if (!force_update) {
if (Z_LVAL_P(progress->post_bytes_processed) < progress->next_update) {
return;
}
#ifdef HAVE_GETTIMEOFDAY
if (PS(rfc1867_min_freq) > 0.0) {
struct timeval tv = {0};
double dtv;
gettimeofday(&tv, NULL);
dtv = (double) tv.tv_sec + tv.tv_usec / 1000000.0;
if (dtv < progress->next_update_time) {
return;
}
progress->next_update_time = dtv + PS(rfc1867_min_freq);
}
#endif
progress->next_update = Z_LVAL_P(progress->post_bytes_processed) + progress->update_step;
}
php_session_initialize(TSRMLS_C);
PS(session_status) = php_session_active;
IF_SESSION_VARS() {
progress->cancel_upload |= php_check_cancel_upload(progress TSRMLS_CC);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), progress->key.c, progress->key.len+1, progress->data, 2, 0);
}
php_session_flush(TSRMLS_C);
} /* }}} */
static void php_session_rfc1867_cleanup(php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
php_session_initialize(TSRMLS_C);
PS(session_status) = php_session_active;
IF_SESSION_VARS() {
zend_hash_del(Z_ARRVAL_P(PS(http_session_vars)), progress->key.c, progress->key.len+1);
}
php_session_flush(TSRMLS_C);
} /* }}} */
static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra TSRMLS_DC) /* {{{ */
{
php_session_rfc1867_progress *progress;
int retval = SUCCESS;
if (php_session_rfc1867_orig_callback) {
retval = php_session_rfc1867_orig_callback(event, event_data, extra TSRMLS_CC);
}
if (!PS(rfc1867_enabled)) {
return retval;
}
progress = PS(rfc1867_progress);
switch(event) {
case MULTIPART_EVENT_START: {
multipart_event_start *data = (multipart_event_start *) event_data;
progress = ecalloc(1, sizeof(php_session_rfc1867_progress));
progress->content_length = data->content_length;
progress->sname_len = strlen(PS(session_name));
PS(rfc1867_progress) = progress;
}
break;
case MULTIPART_EVENT_FORMDATA: {
multipart_event_formdata *data = (multipart_event_formdata *) event_data;
size_t value_len;
if (Z_TYPE(progress->sid) && progress->key.c) {
break;
}
/* orig callback may have modified *data->newlength */
if (data->newlength) {
value_len = *data->newlength;
} else {
value_len = data->length;
}
if (data->name && data->value && value_len) {
size_t name_len = strlen(data->name);
if (name_len == progress->sname_len && memcmp(data->name, PS(session_name), name_len) == 0) {
zval_dtor(&progress->sid);
ZVAL_STRINGL(&progress->sid, (*data->value), value_len, 1);
} else if (name_len == PS(rfc1867_name).len && memcmp(data->name, PS(rfc1867_name).c, name_len) == 0) {
smart_str_free(&progress->key);
smart_str_appendl(&progress->key, PS(rfc1867_prefix).c, PS(rfc1867_prefix).len);
smart_str_appendl(&progress->key, *data->value, value_len);
smart_str_0(&progress->key);
progress->apply_trans_sid = PS(use_trans_sid);
php_session_rfc1867_early_find_sid(progress TSRMLS_CC);
}
}
}
break;
case MULTIPART_EVENT_FILE_START: {
multipart_event_file_start *data = (multipart_event_file_start *) event_data;
/* Do nothing when $_POST["PHP_SESSION_UPLOAD_PROGRESS"] is not set
* or when we have no session id */
if (!Z_TYPE(progress->sid) || !progress->key.c) {
break;
}
/* First FILE_START event, initializing data */
if (!progress->data) {
if (PS(rfc1867_freq) >= 0) {
progress->update_step = PS(rfc1867_freq);
} else if (PS(rfc1867_freq) < 0) { /* % of total size */
progress->update_step = progress->content_length * -PS(rfc1867_freq) / 100;
}
progress->next_update = 0;
progress->next_update_time = 0.0;
ALLOC_INIT_ZVAL(progress->data);
array_init(progress->data);
ALLOC_INIT_ZVAL(progress->post_bytes_processed);
ZVAL_LONG(progress->post_bytes_processed, data->post_bytes_processed);
ALLOC_INIT_ZVAL(progress->files);
array_init(progress->files);
add_assoc_long_ex(progress->data, "start_time", sizeof("start_time"), (long)sapi_get_request_time(TSRMLS_C));
add_assoc_long_ex(progress->data, "content_length", sizeof("content_length"), progress->content_length);
add_assoc_zval_ex(progress->data, "bytes_processed", sizeof("bytes_processed"), progress->post_bytes_processed);
add_assoc_bool_ex(progress->data, "done", sizeof("done"), 0);
add_assoc_zval_ex(progress->data, "files", sizeof("files"), progress->files);
php_rinit_session(0 TSRMLS_CC);
PS(id) = estrndup(Z_STRVAL(progress->sid), Z_STRLEN(progress->sid));
PS(apply_trans_sid) = progress->apply_trans_sid;
PS(send_cookie) = 0;
}
ALLOC_INIT_ZVAL(progress->current_file);
array_init(progress->current_file);
ALLOC_INIT_ZVAL(progress->current_file_bytes_processed);
ZVAL_LONG(progress->current_file_bytes_processed, 0);
/* Each uploaded file has its own array. Trying to make it close to $_FILES entries. */
add_assoc_string_ex(progress->current_file, "field_name", sizeof("field_name"), data->name, 1);
add_assoc_string_ex(progress->current_file, "name", sizeof("name"), *data->filename, 1);
add_assoc_null_ex(progress->current_file, "tmp_name", sizeof("tmp_name"));
add_assoc_long_ex(progress->current_file, "error", sizeof("error"), 0);
add_assoc_bool_ex(progress->current_file, "done", sizeof("done"), 0);
add_assoc_long_ex(progress->current_file, "start_time", sizeof("start_time"), (long)time(NULL));
add_assoc_zval_ex(progress->current_file, "bytes_processed", sizeof("bytes_processed"), progress->current_file_bytes_processed);
add_next_index_zval(progress->files, progress->current_file);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0 TSRMLS_CC);
}
break;
case MULTIPART_EVENT_FILE_DATA: {
multipart_event_file_data *data = (multipart_event_file_data *) event_data;
if (!Z_TYPE(progress->sid) || !progress->key.c) {
break;
}
Z_LVAL_P(progress->current_file_bytes_processed) = data->offset + data->length;
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0 TSRMLS_CC);
}
break;
case MULTIPART_EVENT_FILE_END: {
multipart_event_file_end *data = (multipart_event_file_end *) event_data;
if (!Z_TYPE(progress->sid) || !progress->key.c) {
break;
}
if (data->temp_filename) {
add_assoc_string_ex(progress->current_file, "tmp_name", sizeof("tmp_name"), data->temp_filename, 1);
}
add_assoc_long_ex(progress->current_file, "error", sizeof("error"), data->cancel_upload);
add_assoc_bool_ex(progress->current_file, "done", sizeof("done"), 1);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0 TSRMLS_CC);
}
break;
case MULTIPART_EVENT_END: {
multipart_event_end *data = (multipart_event_end *) event_data;
if (Z_TYPE(progress->sid) && progress->key.c) {
if (PS(rfc1867_cleanup)) {
php_session_rfc1867_cleanup(progress TSRMLS_CC);
} else {
add_assoc_bool_ex(progress->data, "done", sizeof("done"), 1);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 1 TSRMLS_CC);
}
php_rshutdown_session_globals(TSRMLS_C);
}
if (progress->data) {
zval_ptr_dtor(&progress->data);
}
zval_dtor(&progress->sid);
smart_str_free(&progress->key);
efree(progress);
progress = NULL;
PS(rfc1867_progress) = NULL;
}
break;
}
if (progress && progress->cancel_upload) {
return FAILURE;
}
return retval;
} /* }}} */
zend_module_entry session_module_entry = {
STANDARD_MODULE_HEADER_EX,
NULL,
session_deps,
"session",
session_functions,
PHP_MINIT(session), PHP_MSHUTDOWN(session),
PHP_RINIT(session), PHP_RSHUTDOWN(session),
PHP_MINFO(session),
NO_VERSION_YET,
PHP_MODULE_GLOBALS(ps),
PHP_GINIT(ps),
NULL,
NULL,
STANDARD_MODULE_PROPERTIES_EX
};
#ifdef COMPILE_DL_SESSION
ZEND_GET_MODULE(session)
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_5255_0 |
crossvul-cpp_data_good_1907_0 | /*
* Copyright © 2014-2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/personality.h>
#include <grp.h>
#include <unistd.h>
#include <gio/gunixfdlist.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include "libglnx/libglnx.h"
#include "flatpak-run-private.h"
#include "flatpak-proxy.h"
#include "flatpak-utils-private.h"
#include "flatpak-dir-private.h"
#include "flatpak-systemd-dbus-generated.h"
#include "flatpak-error.h"
/* Same order as enum */
const char *flatpak_context_shares[] = {
"network",
"ipc",
NULL
};
/* Same order as enum */
const char *flatpak_context_sockets[] = {
"x11",
"wayland",
"pulseaudio",
"session-bus",
"system-bus",
"fallback-x11",
"ssh-auth",
"pcsc",
"cups",
NULL
};
const char *flatpak_context_devices[] = {
"dri",
"all",
"kvm",
"shm",
NULL
};
const char *flatpak_context_features[] = {
"devel",
"multiarch",
"bluetooth",
"canbus",
NULL
};
const char *flatpak_context_special_filesystems[] = {
"home",
"host",
"host-etc",
"host-os",
NULL
};
FlatpakContext *
flatpak_context_new (void)
{
FlatpakContext *context;
context = g_slice_new0 (FlatpakContext);
context->env_vars = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
context->persistent = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
/* filename or special filesystem name => FlatpakFilesystemMode */
context->filesystems = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
context->session_bus_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
context->system_bus_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
context->generic_policy = g_hash_table_new_full (g_str_hash, g_str_equal,
g_free, (GDestroyNotify) g_strfreev);
return context;
}
void
flatpak_context_free (FlatpakContext *context)
{
g_hash_table_destroy (context->env_vars);
g_hash_table_destroy (context->persistent);
g_hash_table_destroy (context->filesystems);
g_hash_table_destroy (context->session_bus_policy);
g_hash_table_destroy (context->system_bus_policy);
g_hash_table_destroy (context->generic_policy);
g_slice_free (FlatpakContext, context);
}
static guint32
flatpak_context_bitmask_from_string (const char *name, const char **names)
{
guint32 i;
for (i = 0; names[i] != NULL; i++)
{
if (strcmp (names[i], name) == 0)
return 1 << i;
}
return 0;
}
static char **
flatpak_context_bitmask_to_string (guint32 enabled, guint32 valid, const char **names)
{
guint32 i;
GPtrArray *array;
array = g_ptr_array_new ();
for (i = 0; names[i] != NULL; i++)
{
guint32 bitmask = 1 << i;
if (valid & bitmask)
{
if (enabled & bitmask)
g_ptr_array_add (array, g_strdup (names[i]));
else
g_ptr_array_add (array, g_strdup_printf ("!%s", names[i]));
}
}
g_ptr_array_add (array, NULL);
return (char **) g_ptr_array_free (array, FALSE);
}
static void
flatpak_context_bitmask_to_args (guint32 enabled, guint32 valid, const char **names,
const char *enable_arg, const char *disable_arg,
GPtrArray *args)
{
guint32 i;
for (i = 0; names[i] != NULL; i++)
{
guint32 bitmask = 1 << i;
if (valid & bitmask)
{
if (enabled & bitmask)
g_ptr_array_add (args, g_strdup_printf ("%s=%s", enable_arg, names[i]));
else
g_ptr_array_add (args, g_strdup_printf ("%s=%s", disable_arg, names[i]));
}
}
}
static FlatpakContextShares
flatpak_context_share_from_string (const char *string, GError **error)
{
FlatpakContextShares shares = flatpak_context_bitmask_from_string (string, flatpak_context_shares);
if (shares == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_shares);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown share type %s, valid types are: %s"), string, values);
}
return shares;
}
static char **
flatpak_context_shared_to_string (FlatpakContextShares shares, FlatpakContextShares valid)
{
return flatpak_context_bitmask_to_string (shares, valid, flatpak_context_shares);
}
static void
flatpak_context_shared_to_args (FlatpakContextShares shares,
FlatpakContextShares valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (shares, valid, flatpak_context_shares, "--share", "--unshare", args);
}
static FlatpakPolicy
flatpak_policy_from_string (const char *string, GError **error)
{
const char *policies[] = { "none", "see", "talk", "own", NULL };
int i;
g_autofree char *values = NULL;
for (i = 0; policies[i]; i++)
{
if (strcmp (string, policies[i]) == 0)
return i;
}
values = g_strjoinv (", ", (char **) policies);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown policy type %s, valid types are: %s"), string, values);
return -1;
}
static const char *
flatpak_policy_to_string (FlatpakPolicy policy)
{
if (policy == FLATPAK_POLICY_SEE)
return "see";
if (policy == FLATPAK_POLICY_TALK)
return "talk";
if (policy == FLATPAK_POLICY_OWN)
return "own";
return "none";
}
static gboolean
flatpak_verify_dbus_name (const char *name, GError **error)
{
const char *name_part;
g_autofree char *tmp = NULL;
if (g_str_has_suffix (name, ".*"))
{
tmp = g_strndup (name, strlen (name) - 2);
name_part = tmp;
}
else
{
name_part = name;
}
if (g_dbus_is_name (name_part) && !g_dbus_is_unique_name (name_part))
return TRUE;
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Invalid dbus name %s"), name);
return FALSE;
}
static FlatpakContextSockets
flatpak_context_socket_from_string (const char *string, GError **error)
{
FlatpakContextSockets sockets = flatpak_context_bitmask_from_string (string, flatpak_context_sockets);
if (sockets == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_sockets);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown socket type %s, valid types are: %s"), string, values);
}
return sockets;
}
static char **
flatpak_context_sockets_to_string (FlatpakContextSockets sockets, FlatpakContextSockets valid)
{
return flatpak_context_bitmask_to_string (sockets, valid, flatpak_context_sockets);
}
static void
flatpak_context_sockets_to_args (FlatpakContextSockets sockets,
FlatpakContextSockets valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (sockets, valid, flatpak_context_sockets, "--socket", "--nosocket", args);
}
static FlatpakContextDevices
flatpak_context_device_from_string (const char *string, GError **error)
{
FlatpakContextDevices devices = flatpak_context_bitmask_from_string (string, flatpak_context_devices);
if (devices == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_devices);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown device type %s, valid types are: %s"), string, values);
}
return devices;
}
static char **
flatpak_context_devices_to_string (FlatpakContextDevices devices, FlatpakContextDevices valid)
{
return flatpak_context_bitmask_to_string (devices, valid, flatpak_context_devices);
}
static void
flatpak_context_devices_to_args (FlatpakContextDevices devices,
FlatpakContextDevices valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (devices, valid, flatpak_context_devices, "--device", "--nodevice", args);
}
static FlatpakContextFeatures
flatpak_context_feature_from_string (const char *string, GError **error)
{
FlatpakContextFeatures feature = flatpak_context_bitmask_from_string (string, flatpak_context_features);
if (feature == 0)
{
g_autofree char *values = g_strjoinv (", ", (char **) flatpak_context_features);
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown feature type %s, valid types are: %s"), string, values);
}
return feature;
}
static char **
flatpak_context_features_to_string (FlatpakContextFeatures features, FlatpakContextFeatures valid)
{
return flatpak_context_bitmask_to_string (features, valid, flatpak_context_features);
}
static void
flatpak_context_features_to_args (FlatpakContextFeatures features,
FlatpakContextFeatures valid,
GPtrArray *args)
{
return flatpak_context_bitmask_to_args (features, valid, flatpak_context_features, "--allow", "--disallow", args);
}
static void
flatpak_context_add_shares (FlatpakContext *context,
FlatpakContextShares shares)
{
context->shares_valid |= shares;
context->shares |= shares;
}
static void
flatpak_context_remove_shares (FlatpakContext *context,
FlatpakContextShares shares)
{
context->shares_valid |= shares;
context->shares &= ~shares;
}
static void
flatpak_context_add_sockets (FlatpakContext *context,
FlatpakContextSockets sockets)
{
context->sockets_valid |= sockets;
context->sockets |= sockets;
}
static void
flatpak_context_remove_sockets (FlatpakContext *context,
FlatpakContextSockets sockets)
{
context->sockets_valid |= sockets;
context->sockets &= ~sockets;
}
static void
flatpak_context_add_devices (FlatpakContext *context,
FlatpakContextDevices devices)
{
context->devices_valid |= devices;
context->devices |= devices;
}
static void
flatpak_context_remove_devices (FlatpakContext *context,
FlatpakContextDevices devices)
{
context->devices_valid |= devices;
context->devices &= ~devices;
}
static void
flatpak_context_add_features (FlatpakContext *context,
FlatpakContextFeatures features)
{
context->features_valid |= features;
context->features |= features;
}
static void
flatpak_context_remove_features (FlatpakContext *context,
FlatpakContextFeatures features)
{
context->features_valid |= features;
context->features &= ~features;
}
static void
flatpak_context_set_env_var (FlatpakContext *context,
const char *name,
const char *value)
{
g_hash_table_insert (context->env_vars, g_strdup (name), g_strdup (value));
}
void
flatpak_context_set_session_bus_policy (FlatpakContext *context,
const char *name,
FlatpakPolicy policy)
{
g_hash_table_insert (context->session_bus_policy, g_strdup (name), GINT_TO_POINTER (policy));
}
GStrv
flatpak_context_get_session_bus_policy_allowed_own_names (FlatpakContext *context)
{
GHashTableIter iter;
gpointer key, value;
g_autoptr(GPtrArray) names = g_ptr_array_new_with_free_func (g_free);
g_hash_table_iter_init (&iter, context->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
if (GPOINTER_TO_INT (value) == FLATPAK_POLICY_OWN)
g_ptr_array_add (names, g_strdup (key));
g_ptr_array_add (names, NULL);
return (GStrv) g_ptr_array_free (g_steal_pointer (&names), FALSE);
}
void
flatpak_context_set_system_bus_policy (FlatpakContext *context,
const char *name,
FlatpakPolicy policy)
{
g_hash_table_insert (context->system_bus_policy, g_strdup (name), GINT_TO_POINTER (policy));
}
static void
flatpak_context_apply_generic_policy (FlatpakContext *context,
const char *key,
const char *value)
{
GPtrArray *new = g_ptr_array_new ();
const char **old_v;
int i;
g_assert (strchr (key, '.') != NULL);
old_v = g_hash_table_lookup (context->generic_policy, key);
for (i = 0; old_v != NULL && old_v[i] != NULL; i++)
{
const char *old = old_v[i];
const char *cmp1 = old;
const char *cmp2 = value;
if (*cmp1 == '!')
cmp1++;
if (*cmp2 == '!')
cmp2++;
if (strcmp (cmp1, cmp2) != 0)
g_ptr_array_add (new, g_strdup (old));
}
g_ptr_array_add (new, g_strdup (value));
g_ptr_array_add (new, NULL);
g_hash_table_insert (context->generic_policy, g_strdup (key),
g_ptr_array_free (new, FALSE));
}
static void
flatpak_context_set_persistent (FlatpakContext *context,
const char *path)
{
g_hash_table_insert (context->persistent, g_strdup (path), GINT_TO_POINTER (1));
}
static gboolean
get_xdg_dir_from_prefix (const char *prefix,
const char **where,
const char **dir)
{
if (strcmp (prefix, "xdg-data") == 0)
{
if (where)
*where = "data";
if (dir)
*dir = g_get_user_data_dir ();
return TRUE;
}
if (strcmp (prefix, "xdg-cache") == 0)
{
if (where)
*where = "cache";
if (dir)
*dir = g_get_user_cache_dir ();
return TRUE;
}
if (strcmp (prefix, "xdg-config") == 0)
{
if (where)
*where = "config";
if (dir)
*dir = g_get_user_config_dir ();
return TRUE;
}
return FALSE;
}
/* This looks only in the xdg dirs (config, cache, data), not the user
definable ones */
static char *
get_xdg_dir_from_string (const char *filesystem,
const char **suffix,
const char **where)
{
char *slash;
const char *rest;
g_autofree char *prefix = NULL;
const char *dir = NULL;
gsize len;
slash = strchr (filesystem, '/');
if (slash)
len = slash - filesystem;
else
len = strlen (filesystem);
rest = filesystem + len;
while (*rest == '/')
rest++;
if (suffix != NULL)
*suffix = rest;
prefix = g_strndup (filesystem, len);
if (get_xdg_dir_from_prefix (prefix, where, &dir))
return g_build_filename (dir, rest, NULL);
return NULL;
}
static gboolean
get_xdg_user_dir_from_string (const char *filesystem,
const char **config_key,
const char **suffix,
const char **dir)
{
char *slash;
const char *rest;
g_autofree char *prefix = NULL;
gsize len;
slash = strchr (filesystem, '/');
if (slash)
len = slash - filesystem;
else
len = strlen (filesystem);
rest = filesystem + len;
while (*rest == '/')
rest++;
if (suffix)
*suffix = rest;
prefix = g_strndup (filesystem, len);
if (strcmp (prefix, "xdg-desktop") == 0)
{
if (config_key)
*config_key = "XDG_DESKTOP_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP);
return TRUE;
}
if (strcmp (prefix, "xdg-documents") == 0)
{
if (config_key)
*config_key = "XDG_DOCUMENTS_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS);
return TRUE;
}
if (strcmp (prefix, "xdg-download") == 0)
{
if (config_key)
*config_key = "XDG_DOWNLOAD_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD);
return TRUE;
}
if (strcmp (prefix, "xdg-music") == 0)
{
if (config_key)
*config_key = "XDG_MUSIC_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_MUSIC);
return TRUE;
}
if (strcmp (prefix, "xdg-pictures") == 0)
{
if (config_key)
*config_key = "XDG_PICTURES_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
return TRUE;
}
if (strcmp (prefix, "xdg-public-share") == 0)
{
if (config_key)
*config_key = "XDG_PUBLICSHARE_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE);
return TRUE;
}
if (strcmp (prefix, "xdg-templates") == 0)
{
if (config_key)
*config_key = "XDG_TEMPLATES_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES);
return TRUE;
}
if (strcmp (prefix, "xdg-videos") == 0)
{
if (config_key)
*config_key = "XDG_VIDEOS_DIR";
if (dir)
*dir = g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS);
return TRUE;
}
if (get_xdg_dir_from_prefix (prefix, NULL, dir))
{
if (config_key)
*config_key = NULL;
return TRUE;
}
/* Don't support xdg-run without suffix, because that doesn't work */
if (strcmp (prefix, "xdg-run") == 0 &&
*rest != 0)
{
if (config_key)
*config_key = NULL;
if (dir)
*dir = flatpak_get_real_xdg_runtime_dir ();
return TRUE;
}
return FALSE;
}
static char *
unparse_filesystem_flags (const char *path,
FlatpakFilesystemMode mode)
{
g_autoptr(GString) s = g_string_new ("");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else if (*p == '\\')
g_string_append (s, "\\\\");
else
g_string_append_c (s, *p);
}
switch (mode)
{
case FLATPAK_FILESYSTEM_MODE_READ_ONLY:
g_string_append (s, ":ro");
break;
case FLATPAK_FILESYSTEM_MODE_CREATE:
g_string_append (s, ":create");
break;
case FLATPAK_FILESYSTEM_MODE_READ_WRITE:
break;
case FLATPAK_FILESYSTEM_MODE_NONE:
g_string_insert_c (s, 0, '!');
break;
default:
g_warning ("Unexpected filesystem mode %d", mode);
break;
}
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
parse_filesystem_flags (const char *filesystem,
FlatpakFilesystemMode *mode_out)
{
g_autoptr(GString) s = g_string_new ("");
const char *p, *suffix;
FlatpakFilesystemMode mode;
p = filesystem;
while (*p != 0 && *p != ':')
{
if (*p == '\\')
{
p++;
if (*p != 0)
g_string_append_c (s, *p++);
}
else
g_string_append_c (s, *p++);
}
mode = FLATPAK_FILESYSTEM_MODE_READ_WRITE;
if (*p == ':')
{
suffix = p + 1;
if (strcmp (suffix, "ro") == 0)
mode = FLATPAK_FILESYSTEM_MODE_READ_ONLY;
else if (strcmp (suffix, "rw") == 0)
mode = FLATPAK_FILESYSTEM_MODE_READ_WRITE;
else if (strcmp (suffix, "create") == 0)
mode = FLATPAK_FILESYSTEM_MODE_CREATE;
else if (*suffix != 0)
g_warning ("Unexpected filesystem suffix %s, ignoring", suffix);
}
if (mode_out)
*mode_out = mode;
return g_string_free (g_steal_pointer (&s), FALSE);
}
gboolean
flatpak_context_parse_filesystem (const char *filesystem_and_mode,
char **filesystem_out,
FlatpakFilesystemMode *mode_out,
GError **error)
{
g_autofree char *filesystem = parse_filesystem_flags (filesystem_and_mode, mode_out);
char *slash;
slash = strchr (filesystem, '/');
/* Forbid /../ in paths */
if (slash != NULL)
{
if (g_str_has_prefix (slash + 1, "../") ||
g_str_has_suffix (slash + 1, "/..") ||
strstr (slash + 1, "/../") != NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("Filesystem location \"%s\" contains \"..\""),
filesystem);
return FALSE;
}
/* Convert "//" and "/./" to "/" */
for (; slash != NULL; slash = strchr (slash + 1, '/'))
{
while (TRUE)
{
if (slash[1] == '/')
memmove (slash + 1, slash + 2, strlen (slash + 2) + 1);
else if (slash[1] == '.' && slash[2] == '/')
memmove (slash + 1, slash + 3, strlen (slash + 3) + 1);
else
break;
}
}
/* Eliminate trailing "/." or "/". */
while (TRUE)
{
slash = strrchr (filesystem, '/');
if (slash != NULL &&
((slash != filesystem && slash[1] == '\0') ||
(slash[1] == '.' && slash[2] == '\0')))
*slash = '\0';
else
break;
}
if (filesystem[0] == '/' && filesystem[1] == '\0')
{
/* We don't allow --filesystem=/ as equivalent to host, because
* it doesn't do what you'd think: --filesystem=host mounts some
* host directories in /run/host, not in the root. */
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--filesystem=/ is not available, "
"use --filesystem=host for a similar result"));
return FALSE;
}
}
if (g_strv_contains (flatpak_context_special_filesystems, filesystem) ||
get_xdg_user_dir_from_string (filesystem, NULL, NULL, NULL) ||
g_str_has_prefix (filesystem, "~/") ||
g_str_has_prefix (filesystem, "/"))
{
if (filesystem_out != NULL)
*filesystem_out = g_steal_pointer (&filesystem);
return TRUE;
}
if (strcmp (filesystem, "~") == 0)
{
if (filesystem_out != NULL)
*filesystem_out = g_strdup ("home");
return TRUE;
}
if (g_str_has_prefix (filesystem, "home/"))
{
if (filesystem_out != NULL)
*filesystem_out = g_strconcat ("~/", filesystem + 5, NULL);
return TRUE;
}
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Unknown filesystem location %s, valid locations are: host, host-os, host-etc, home, xdg-*[/…], ~/dir, /dir"), filesystem);
return FALSE;
}
static void
flatpak_context_take_filesystem (FlatpakContext *context,
char *fs,
FlatpakFilesystemMode mode)
{
g_hash_table_insert (context->filesystems, fs, GINT_TO_POINTER (mode));
}
void
flatpak_context_merge (FlatpakContext *context,
FlatpakContext *other)
{
GHashTableIter iter;
gpointer key, value;
context->shares &= ~other->shares_valid;
context->shares |= other->shares;
context->shares_valid |= other->shares_valid;
context->sockets &= ~other->sockets_valid;
context->sockets |= other->sockets;
context->sockets_valid |= other->sockets_valid;
context->devices &= ~other->devices_valid;
context->devices |= other->devices;
context->devices_valid |= other->devices_valid;
context->features &= ~other->features_valid;
context->features |= other->features;
context->features_valid |= other->features_valid;
g_hash_table_iter_init (&iter, other->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->env_vars, g_strdup (key), g_strdup (value));
g_hash_table_iter_init (&iter, other->persistent);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->persistent, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->filesystems, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->session_bus_policy, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->system_bus_policy, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
g_hash_table_insert (context->system_bus_policy, g_strdup (key), value);
g_hash_table_iter_init (&iter, other->generic_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char **policy_values = (const char **) value;
int i;
for (i = 0; policy_values[i] != NULL; i++)
flatpak_context_apply_generic_policy (context, (char *) key, policy_values[i]);
}
}
static gboolean
option_share_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextShares share;
share = flatpak_context_share_from_string (value, error);
if (share == 0)
return FALSE;
flatpak_context_add_shares (context, share);
return TRUE;
}
static gboolean
option_unshare_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextShares share;
share = flatpak_context_share_from_string (value, error);
if (share == 0)
return FALSE;
flatpak_context_remove_shares (context, share);
return TRUE;
}
static gboolean
option_socket_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextSockets socket;
socket = flatpak_context_socket_from_string (value, error);
if (socket == 0)
return FALSE;
if (socket == FLATPAK_CONTEXT_SOCKET_FALLBACK_X11)
socket |= FLATPAK_CONTEXT_SOCKET_X11;
flatpak_context_add_sockets (context, socket);
return TRUE;
}
static gboolean
option_nosocket_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextSockets socket;
socket = flatpak_context_socket_from_string (value, error);
if (socket == 0)
return FALSE;
if (socket == FLATPAK_CONTEXT_SOCKET_FALLBACK_X11)
socket |= FLATPAK_CONTEXT_SOCKET_X11;
flatpak_context_remove_sockets (context, socket);
return TRUE;
}
static gboolean
option_device_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextDevices device;
device = flatpak_context_device_from_string (value, error);
if (device == 0)
return FALSE;
flatpak_context_add_devices (context, device);
return TRUE;
}
static gboolean
option_nodevice_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextDevices device;
device = flatpak_context_device_from_string (value, error);
if (device == 0)
return FALSE;
flatpak_context_remove_devices (context, device);
return TRUE;
}
static gboolean
option_allow_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextFeatures feature;
feature = flatpak_context_feature_from_string (value, error);
if (feature == 0)
return FALSE;
flatpak_context_add_features (context, feature);
return TRUE;
}
static gboolean
option_disallow_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
FlatpakContextFeatures feature;
feature = flatpak_context_feature_from_string (value, error);
if (feature == 0)
return FALSE;
flatpak_context_remove_features (context, feature);
return TRUE;
}
static gboolean
option_filesystem_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
g_autofree char *fs = NULL;
FlatpakFilesystemMode mode;
if (!flatpak_context_parse_filesystem (value, &fs, &mode, error))
return FALSE;
flatpak_context_take_filesystem (context, g_steal_pointer (&fs), mode);
return TRUE;
}
static gboolean
option_nofilesystem_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
g_autofree char *fs = NULL;
FlatpakFilesystemMode mode;
if (!flatpak_context_parse_filesystem (value, &fs, &mode, error))
return FALSE;
flatpak_context_take_filesystem (context, g_steal_pointer (&fs),
FLATPAK_FILESYSTEM_MODE_NONE);
return TRUE;
}
static gboolean
option_env_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
g_auto(GStrv) split = g_strsplit (value, "=", 2);
if (split == NULL || split[0] == NULL || split[0][0] == 0 || split[1] == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
_("Invalid env format %s"), value);
return FALSE;
}
flatpak_context_set_env_var (context, split[0], split[1]);
return TRUE;
}
static gboolean
option_env_fd_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
g_autoptr(GBytes) env_block = NULL;
gsize remaining;
const char *p;
guint64 fd;
gchar *endptr;
fd = g_ascii_strtoull (value, &endptr, 10);
if (endptr == NULL || *endptr != '\0' || fd > G_MAXINT)
return glnx_throw (error, "Not a valid file descriptor: %s", value);
env_block = glnx_fd_readall_bytes ((int) fd, NULL, error);
if (env_block == NULL)
return FALSE;
p = g_bytes_get_data (env_block, &remaining);
/* env_block might not be \0-terminated */
while (remaining > 0)
{
size_t len = strnlen (p, remaining);
const char *equals;
g_assert (len <= remaining);
equals = memchr (p, '=', len);
if (equals == NULL || equals == p)
return glnx_throw (error,
"Environment variable must be given in the form VARIABLE=VALUE, not %.*s", (int) len, p);
flatpak_context_set_env_var (context,
g_strndup (p, equals - p),
g_strndup (equals + 1, len - (equals - p) - 1));
p += len;
remaining -= len;
if (remaining > 0)
{
g_assert (*p == '\0');
p += 1;
remaining -= 1;
}
}
if (fd >= 3)
close (fd);
return TRUE;
}
static gboolean
option_own_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_session_bus_policy (context, value, FLATPAK_POLICY_OWN);
return TRUE;
}
static gboolean
option_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_session_bus_policy (context, value, FLATPAK_POLICY_TALK);
return TRUE;
}
static gboolean
option_no_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_session_bus_policy (context, value, FLATPAK_POLICY_NONE);
return TRUE;
}
static gboolean
option_system_own_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_system_bus_policy (context, value, FLATPAK_POLICY_OWN);
return TRUE;
}
static gboolean
option_system_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_system_bus_policy (context, value, FLATPAK_POLICY_TALK);
return TRUE;
}
static gboolean
option_system_no_talk_name_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
if (!flatpak_verify_dbus_name (value, error))
return FALSE;
flatpak_context_set_system_bus_policy (context, value, FLATPAK_POLICY_NONE);
return TRUE;
}
static gboolean
option_add_generic_policy_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
char *t;
g_autofree char *key = NULL;
const char *policy_value;
t = strchr (value, '=');
if (t == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--add-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
policy_value = t + 1;
key = g_strndup (value, t - value);
if (strchr (key, '.') == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--add-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
if (policy_value[0] == '!')
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--add-policy values can't start with \"!\""));
return FALSE;
}
flatpak_context_apply_generic_policy (context, key, policy_value);
return TRUE;
}
static gboolean
option_remove_generic_policy_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
char *t;
g_autofree char *key = NULL;
const char *policy_value;
g_autofree char *extended_value = NULL;
t = strchr (value, '=');
if (t == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--remove-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
policy_value = t + 1;
key = g_strndup (value, t - value);
if (strchr (key, '.') == NULL)
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--remove-policy arguments must be in the form SUBSYSTEM.KEY=VALUE"));
return FALSE;
}
if (policy_value[0] == '!')
{
g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
_("--remove-policy values can't start with \"!\""));
return FALSE;
}
extended_value = g_strconcat ("!", policy_value, NULL);
flatpak_context_apply_generic_policy (context, key, extended_value);
return TRUE;
}
static gboolean
option_persist_cb (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
FlatpakContext *context = data;
flatpak_context_set_persistent (context, value);
return TRUE;
}
static gboolean option_no_desktop_deprecated;
static GOptionEntry context_options[] = {
{ "share", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_share_cb, N_("Share with host"), N_("SHARE") },
{ "unshare", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_unshare_cb, N_("Unshare with host"), N_("SHARE") },
{ "socket", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_socket_cb, N_("Expose socket to app"), N_("SOCKET") },
{ "nosocket", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_nosocket_cb, N_("Don't expose socket to app"), N_("SOCKET") },
{ "device", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_device_cb, N_("Expose device to app"), N_("DEVICE") },
{ "nodevice", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_nodevice_cb, N_("Don't expose device to app"), N_("DEVICE") },
{ "allow", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_allow_cb, N_("Allow feature"), N_("FEATURE") },
{ "disallow", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_disallow_cb, N_("Don't allow feature"), N_("FEATURE") },
{ "filesystem", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_filesystem_cb, N_("Expose filesystem to app (:ro for read-only)"), N_("FILESYSTEM[:ro]") },
{ "nofilesystem", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_nofilesystem_cb, N_("Don't expose filesystem to app"), N_("FILESYSTEM") },
{ "env", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_env_cb, N_("Set environment variable"), N_("VAR=VALUE") },
{ "env-fd", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_env_fd_cb, N_("Read environment variables in env -0 format from FD"), N_("FD") },
{ "own-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_own_name_cb, N_("Allow app to own name on the session bus"), N_("DBUS_NAME") },
{ "talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_talk_name_cb, N_("Allow app to talk to name on the session bus"), N_("DBUS_NAME") },
{ "no-talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_no_talk_name_cb, N_("Don't allow app to talk to name on the session bus"), N_("DBUS_NAME") },
{ "system-own-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_system_own_name_cb, N_("Allow app to own name on the system bus"), N_("DBUS_NAME") },
{ "system-talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_system_talk_name_cb, N_("Allow app to talk to name on the system bus"), N_("DBUS_NAME") },
{ "system-no-talk-name", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_system_no_talk_name_cb, N_("Don't allow app to talk to name on the system bus"), N_("DBUS_NAME") },
{ "add-policy", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_add_generic_policy_cb, N_("Add generic policy option"), N_("SUBSYSTEM.KEY=VALUE") },
{ "remove-policy", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_remove_generic_policy_cb, N_("Remove generic policy option"), N_("SUBSYSTEM.KEY=VALUE") },
{ "persist", 0, G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_CALLBACK, &option_persist_cb, N_("Persist home directory subpath"), N_("FILENAME") },
/* This is not needed/used anymore, so hidden, but we accept it for backwards compat */
{ "no-desktop", 0, G_OPTION_FLAG_IN_MAIN | G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &option_no_desktop_deprecated, N_("Don't require a running session (no cgroups creation)"), NULL },
{ NULL }
};
GOptionEntry *
flatpak_context_get_option_entries (void)
{
return context_options;
}
GOptionGroup *
flatpak_context_get_options (FlatpakContext *context)
{
GOptionGroup *group;
group = g_option_group_new ("environment",
"Runtime Environment",
"Runtime Environment",
context,
NULL);
g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
g_option_group_add_entries (group, context_options);
return group;
}
static const char *
parse_negated (const char *option, gboolean *negated)
{
if (option[0] == '!')
{
option++;
*negated = TRUE;
}
else
{
*negated = FALSE;
}
return option;
}
/*
* Merge the FLATPAK_METADATA_GROUP_CONTEXT,
* FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,
* FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY and
* FLATPAK_METADATA_GROUP_ENVIRONMENT groups, and all groups starting
* with FLATPAK_METADATA_GROUP_PREFIX_POLICY, from metakey into context.
*
* This is a merge, not a replace!
*/
gboolean
flatpak_context_load_metadata (FlatpakContext *context,
GKeyFile *metakey,
GError **error)
{
gboolean remove;
g_auto(GStrv) groups = NULL;
gsize i;
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_SHARED, NULL))
{
g_auto(GStrv) shares = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED, NULL, error);
if (shares == NULL)
return FALSE;
for (i = 0; shares[i] != NULL; i++)
{
FlatpakContextShares share;
share = flatpak_context_share_from_string (parse_negated (shares[i], &remove), NULL);
if (share == 0)
g_debug ("Unknown share type %s", shares[i]);
else
{
if (remove)
flatpak_context_remove_shares (context, share);
else
flatpak_context_add_shares (context, share);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_SOCKETS, NULL))
{
g_auto(GStrv) sockets = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS, NULL, error);
if (sockets == NULL)
return FALSE;
for (i = 0; sockets[i] != NULL; i++)
{
FlatpakContextSockets socket = flatpak_context_socket_from_string (parse_negated (sockets[i], &remove), NULL);
if (socket == 0)
g_debug ("Unknown socket type %s", sockets[i]);
else
{
if (remove)
flatpak_context_remove_sockets (context, socket);
else
flatpak_context_add_sockets (context, socket);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_DEVICES, NULL))
{
g_auto(GStrv) devices = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES, NULL, error);
if (devices == NULL)
return FALSE;
for (i = 0; devices[i] != NULL; i++)
{
FlatpakContextDevices device = flatpak_context_device_from_string (parse_negated (devices[i], &remove), NULL);
if (device == 0)
g_debug ("Unknown device type %s", devices[i]);
else
{
if (remove)
flatpak_context_remove_devices (context, device);
else
flatpak_context_add_devices (context, device);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_FEATURES, NULL))
{
g_auto(GStrv) features = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FEATURES, NULL, error);
if (features == NULL)
return FALSE;
for (i = 0; features[i] != NULL; i++)
{
FlatpakContextFeatures feature = flatpak_context_feature_from_string (parse_negated (features[i], &remove), NULL);
if (feature == 0)
g_debug ("Unknown feature type %s", features[i]);
else
{
if (remove)
flatpak_context_remove_features (context, feature);
else
flatpak_context_add_features (context, feature);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_FILESYSTEMS, NULL))
{
g_auto(GStrv) filesystems = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FILESYSTEMS, NULL, error);
if (filesystems == NULL)
return FALSE;
for (i = 0; filesystems[i] != NULL; i++)
{
const char *fs = parse_negated (filesystems[i], &remove);
g_autofree char *filesystem = NULL;
FlatpakFilesystemMode mode;
if (!flatpak_context_parse_filesystem (fs, &filesystem, &mode, NULL))
g_debug ("Unknown filesystem type %s", filesystems[i]);
else
{
if (remove)
flatpak_context_take_filesystem (context, g_steal_pointer (&filesystem),
FLATPAK_FILESYSTEM_MODE_NONE);
else
flatpak_context_take_filesystem (context, g_steal_pointer (&filesystem), mode);
}
}
}
if (g_key_file_has_key (metakey, FLATPAK_METADATA_GROUP_CONTEXT, FLATPAK_METADATA_KEY_PERSISTENT, NULL))
{
g_auto(GStrv) persistent = g_key_file_get_string_list (metakey, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_PERSISTENT, NULL, error);
if (persistent == NULL)
return FALSE;
for (i = 0; persistent[i] != NULL; i++)
flatpak_context_set_persistent (context, persistent[i]);
}
if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY))
{
g_auto(GStrv) keys = NULL;
gsize keys_count;
keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, &keys_count, NULL);
for (i = 0; i < keys_count; i++)
{
const char *key = keys[i];
g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, key, NULL);
FlatpakPolicy policy;
if (!flatpak_verify_dbus_name (key, error))
return FALSE;
policy = flatpak_policy_from_string (value, NULL);
if ((int) policy != -1)
flatpak_context_set_session_bus_policy (context, key, policy);
}
}
if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY))
{
g_auto(GStrv) keys = NULL;
gsize keys_count;
keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, &keys_count, NULL);
for (i = 0; i < keys_count; i++)
{
const char *key = keys[i];
g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, key, NULL);
FlatpakPolicy policy;
if (!flatpak_verify_dbus_name (key, error))
return FALSE;
policy = flatpak_policy_from_string (value, NULL);
if ((int) policy != -1)
flatpak_context_set_system_bus_policy (context, key, policy);
}
}
if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT))
{
g_auto(GStrv) keys = NULL;
gsize keys_count;
keys = g_key_file_get_keys (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, &keys_count, NULL);
for (i = 0; i < keys_count; i++)
{
const char *key = keys[i];
g_autofree char *value = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, key, NULL);
flatpak_context_set_env_var (context, key, value);
}
}
groups = g_key_file_get_groups (metakey, NULL);
for (i = 0; groups[i] != NULL; i++)
{
const char *group = groups[i];
const char *subsystem;
int j;
if (g_str_has_prefix (group, FLATPAK_METADATA_GROUP_PREFIX_POLICY))
{
g_auto(GStrv) keys = NULL;
subsystem = group + strlen (FLATPAK_METADATA_GROUP_PREFIX_POLICY);
keys = g_key_file_get_keys (metakey, group, NULL, NULL);
for (j = 0; keys != NULL && keys[j] != NULL; j++)
{
const char *key = keys[j];
g_autofree char *policy_key = g_strdup_printf ("%s.%s", subsystem, key);
g_auto(GStrv) values = NULL;
int k;
values = g_key_file_get_string_list (metakey, group, key, NULL, NULL);
for (k = 0; values != NULL && values[k] != NULL; k++)
flatpak_context_apply_generic_policy (context, policy_key,
values[k]);
}
}
}
return TRUE;
}
/*
* Save the FLATPAK_METADATA_GROUP_CONTEXT,
* FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,
* FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY and
* FLATPAK_METADATA_GROUP_ENVIRONMENT groups, and all groups starting
* with FLATPAK_METADATA_GROUP_PREFIX_POLICY, into metakey
*/
void
flatpak_context_save_metadata (FlatpakContext *context,
gboolean flatten,
GKeyFile *metakey)
{
g_auto(GStrv) shared = NULL;
g_auto(GStrv) sockets = NULL;
g_auto(GStrv) devices = NULL;
g_auto(GStrv) features = NULL;
GHashTableIter iter;
gpointer key, value;
FlatpakContextShares shares_mask = context->shares;
FlatpakContextShares shares_valid = context->shares_valid;
FlatpakContextSockets sockets_mask = context->sockets;
FlatpakContextSockets sockets_valid = context->sockets_valid;
FlatpakContextDevices devices_mask = context->devices;
FlatpakContextDevices devices_valid = context->devices_valid;
FlatpakContextFeatures features_mask = context->features;
FlatpakContextFeatures features_valid = context->features_valid;
g_auto(GStrv) groups = NULL;
int i;
if (flatten)
{
/* A flattened format means we don't expect this to be merged on top of
another context. In that case we never need to negate any flags.
We calculate this by removing the zero parts of the mask from the valid set.
*/
/* First we make sure only the valid parts of the mask are set, in case we
got some leftover */
shares_mask &= shares_valid;
sockets_mask &= sockets_valid;
devices_mask &= devices_valid;
features_mask &= features_valid;
/* Then just set the valid set to be the mask set */
shares_valid = shares_mask;
sockets_valid = sockets_mask;
devices_valid = devices_mask;
features_valid = features_mask;
}
shared = flatpak_context_shared_to_string (shares_mask, shares_valid);
sockets = flatpak_context_sockets_to_string (sockets_mask, sockets_valid);
devices = flatpak_context_devices_to_string (devices_mask, devices_valid);
features = flatpak_context_features_to_string (features_mask, features_valid);
if (shared[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED,
(const char * const *) shared, g_strv_length (shared));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED,
NULL);
}
if (sockets[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS,
(const char * const *) sockets, g_strv_length (sockets));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS,
NULL);
}
if (devices[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES,
(const char * const *) devices, g_strv_length (devices));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES,
NULL);
}
if (features[0] != NULL)
{
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FEATURES,
(const char * const *) features, g_strv_length (features));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FEATURES,
NULL);
}
if (g_hash_table_size (context->filesystems) > 0)
{
g_autoptr(GPtrArray) array = g_ptr_array_new_with_free_func (g_free);
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
g_ptr_array_add (array, unparse_filesystem_flags (key, mode));
}
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FILESYSTEMS,
(const char * const *) array->pdata, array->len);
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_FILESYSTEMS,
NULL);
}
if (g_hash_table_size (context->persistent) > 0)
{
g_autofree char **keys = (char **) g_hash_table_get_keys_as_array (context->persistent, NULL);
g_key_file_set_string_list (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_PERSISTENT,
(const char * const *) keys, g_strv_length (keys));
}
else
{
g_key_file_remove_key (metakey,
FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_PERSISTENT,
NULL);
}
g_key_file_remove_group (metakey, FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY, NULL);
g_hash_table_iter_init (&iter, context->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakPolicy policy = GPOINTER_TO_INT (value);
if (flatten && (policy == 0))
continue;
g_key_file_set_string (metakey,
FLATPAK_METADATA_GROUP_SESSION_BUS_POLICY,
(char *) key, flatpak_policy_to_string (policy));
}
g_key_file_remove_group (metakey, FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY, NULL);
g_hash_table_iter_init (&iter, context->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakPolicy policy = GPOINTER_TO_INT (value);
if (flatten && (policy == 0))
continue;
g_key_file_set_string (metakey,
FLATPAK_METADATA_GROUP_SYSTEM_BUS_POLICY,
(char *) key, flatpak_policy_to_string (policy));
}
g_key_file_remove_group (metakey, FLATPAK_METADATA_GROUP_ENVIRONMENT, NULL);
g_hash_table_iter_init (&iter, context->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
{
g_key_file_set_string (metakey,
FLATPAK_METADATA_GROUP_ENVIRONMENT,
(char *) key, (char *) value);
}
groups = g_key_file_get_groups (metakey, NULL);
for (i = 0; groups[i] != NULL; i++)
{
const char *group = groups[i];
if (g_str_has_prefix (group, FLATPAK_METADATA_GROUP_PREFIX_POLICY))
g_key_file_remove_group (metakey, group, NULL);
}
g_hash_table_iter_init (&iter, context->generic_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
g_auto(GStrv) parts = g_strsplit ((const char *) key, ".", 2);
g_autofree char *group = NULL;
g_assert (parts[1] != NULL);
const char **policy_values = (const char **) value;
g_autoptr(GPtrArray) new = g_ptr_array_new ();
for (i = 0; policy_values[i] != NULL; i++)
{
const char *policy_value = policy_values[i];
if (!flatten || policy_value[0] != '!')
g_ptr_array_add (new, (char *) policy_value);
}
if (new->len > 0)
{
group = g_strconcat (FLATPAK_METADATA_GROUP_PREFIX_POLICY,
parts[0], NULL);
g_key_file_set_string_list (metakey, group, parts[1],
(const char * const *) new->pdata,
new->len);
}
}
}
void
flatpak_context_allow_host_fs (FlatpakContext *context)
{
flatpak_context_take_filesystem (context, g_strdup ("host"), FLATPAK_FILESYSTEM_MODE_READ_WRITE);
}
gboolean
flatpak_context_get_needs_session_bus_proxy (FlatpakContext *context)
{
return g_hash_table_size (context->session_bus_policy) > 0;
}
gboolean
flatpak_context_get_needs_system_bus_proxy (FlatpakContext *context)
{
return g_hash_table_size (context->system_bus_policy) > 0;
}
static gboolean
adds_flags (guint32 old_flags, guint32 new_flags)
{
return (new_flags & ~old_flags) != 0;
}
static gboolean
adds_bus_policy (GHashTable *old, GHashTable *new)
{
GLNX_HASH_TABLE_FOREACH_KV (new, const char *, name, gpointer, _new_policy)
{
int new_policy = GPOINTER_TO_INT (_new_policy);
int old_policy = GPOINTER_TO_INT (g_hash_table_lookup (old, name));
if (new_policy > old_policy)
return TRUE;
}
return FALSE;
}
static gboolean
adds_generic_policy (GHashTable *old, GHashTable *new)
{
GLNX_HASH_TABLE_FOREACH_KV (new, const char *, key, GPtrArray *, new_values)
{
GPtrArray *old_values = g_hash_table_lookup (old, key);
int i;
if (new_values == NULL || new_values->len == 0)
continue;
if (old_values == NULL || old_values->len == 0)
return TRUE;
for (i = 0; i < new_values->len; i++)
{
const char *new_value = g_ptr_array_index (new_values, i);
if (!flatpak_g_ptr_array_contains_string (old_values, new_value))
return TRUE;
}
}
return FALSE;
}
static gboolean
adds_filesystem_access (GHashTable *old, GHashTable *new)
{
FlatpakFilesystemMode old_host_mode = GPOINTER_TO_INT (g_hash_table_lookup (old, "host"));
GLNX_HASH_TABLE_FOREACH_KV (new, const char *, location, gpointer, _new_mode)
{
FlatpakFilesystemMode new_mode = GPOINTER_TO_INT (_new_mode);
FlatpakFilesystemMode old_mode = GPOINTER_TO_INT (g_hash_table_lookup (old, location));
/* Allow more limited access to the same thing */
if (new_mode <= old_mode)
continue;
/* Allow more limited access if we used to have access to everything */
if (new_mode <= old_host_mode)
continue;
/* For the remainder we have to be pessimistic, for instance even
if we have home access we can't allow adding access to ~/foo,
because foo might be a symlink outside home which didn't work
before but would work with an explicit access to that
particular file. */
return TRUE;
}
return FALSE;
}
gboolean
flatpak_context_adds_permissions (FlatpakContext *old,
FlatpakContext *new)
{
guint32 old_sockets;
if (adds_flags (old->shares & old->shares_valid,
new->shares & new->shares_valid))
return TRUE;
old_sockets = old->sockets & old->sockets_valid;
/* If we used to allow X11, also allow new fallback X11,
as that is actually less permissions */
if (old_sockets & FLATPAK_CONTEXT_SOCKET_X11)
old_sockets |= FLATPAK_CONTEXT_SOCKET_FALLBACK_X11;
if (adds_flags (old_sockets,
new->sockets & new->sockets_valid))
return TRUE;
if (adds_flags (old->devices & old->devices_valid,
new->devices & new->devices_valid))
return TRUE;
/* We allow upgrade to multiarch, that is really not a huge problem */
if (adds_flags ((old->features & old->features_valid) | FLATPAK_CONTEXT_FEATURE_MULTIARCH,
new->features & new->features_valid))
return TRUE;
if (adds_bus_policy (old->session_bus_policy, new->session_bus_policy))
return TRUE;
if (adds_bus_policy (old->system_bus_policy, new->system_bus_policy))
return TRUE;
if (adds_generic_policy (old->generic_policy, new->generic_policy))
return TRUE;
if (adds_filesystem_access (old->filesystems, new->filesystems))
return TRUE;
return FALSE;
}
gboolean
flatpak_context_allows_features (FlatpakContext *context,
FlatpakContextFeatures features)
{
return (context->features & features) == features;
}
void
flatpak_context_to_args (FlatpakContext *context,
GPtrArray *args)
{
GHashTableIter iter;
gpointer key, value;
flatpak_context_shared_to_args (context->shares, context->shares_valid, args);
flatpak_context_sockets_to_args (context->sockets, context->sockets_valid, args);
flatpak_context_devices_to_args (context->devices, context->devices_valid, args);
flatpak_context_features_to_args (context->features, context->features_valid, args);
g_hash_table_iter_init (&iter, context->env_vars);
while (g_hash_table_iter_next (&iter, &key, &value))
g_ptr_array_add (args, g_strdup_printf ("--env=%s=%s", (char *) key, (char *) value));
g_hash_table_iter_init (&iter, context->persistent);
while (g_hash_table_iter_next (&iter, &key, &value))
g_ptr_array_add (args, g_strdup_printf ("--persist=%s", (char *) key));
g_hash_table_iter_init (&iter, context->session_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
FlatpakPolicy policy = GPOINTER_TO_INT (value);
g_ptr_array_add (args, g_strdup_printf ("--%s-name=%s", flatpak_policy_to_string (policy), name));
}
g_hash_table_iter_init (&iter, context->system_bus_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
FlatpakPolicy policy = GPOINTER_TO_INT (value);
g_ptr_array_add (args, g_strdup_printf ("--system-%s-name=%s", flatpak_policy_to_string (policy), name));
}
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
if (mode != FLATPAK_FILESYSTEM_MODE_NONE)
{
g_autofree char *fs = unparse_filesystem_flags (key, mode);
g_ptr_array_add (args, g_strdup_printf ("--filesystem=%s", fs));
}
else
g_ptr_array_add (args, g_strdup_printf ("--nofilesystem=%s", (char *) key));
}
}
void
flatpak_context_add_bus_filters (FlatpakContext *context,
const char *app_id,
gboolean session_bus,
gboolean sandboxed,
FlatpakBwrap *bwrap)
{
GHashTable *ht;
GHashTableIter iter;
gpointer key, value;
flatpak_bwrap_add_arg (bwrap, "--filter");
if (app_id && session_bus)
{
if (!sandboxed)
{
flatpak_bwrap_add_arg_printf (bwrap, "--own=%s.*", app_id);
flatpak_bwrap_add_arg_printf (bwrap, "--own=org.mpris.MediaPlayer2.%s.*", app_id);
}
else
flatpak_bwrap_add_arg_printf (bwrap, "--own=%s.Sandboxed.*", app_id);
}
if (session_bus)
ht = context->session_bus_policy;
else
ht = context->system_bus_policy;
g_hash_table_iter_init (&iter, ht);
while (g_hash_table_iter_next (&iter, &key, &value))
{
FlatpakPolicy policy = GPOINTER_TO_INT (value);
if (policy > 0)
flatpak_bwrap_add_arg_printf (bwrap, "--%s=%s",
flatpak_policy_to_string (policy),
(char *) key);
}
}
void
flatpak_context_reset_non_permissions (FlatpakContext *context)
{
g_hash_table_remove_all (context->env_vars);
}
void
flatpak_context_reset_permissions (FlatpakContext *context)
{
context->shares_valid = 0;
context->sockets_valid = 0;
context->devices_valid = 0;
context->features_valid = 0;
context->shares = 0;
context->sockets = 0;
context->devices = 0;
context->features = 0;
g_hash_table_remove_all (context->persistent);
g_hash_table_remove_all (context->filesystems);
g_hash_table_remove_all (context->session_bus_policy);
g_hash_table_remove_all (context->system_bus_policy);
g_hash_table_remove_all (context->generic_policy);
}
void
flatpak_context_make_sandboxed (FlatpakContext *context)
{
/* We drop almost everything from the app permission, except
* multiarch which is inherited, to make sure app code keeps
* running. */
context->shares_valid &= 0;
context->sockets_valid &= 0;
context->devices_valid &= 0;
context->features_valid &= FLATPAK_CONTEXT_FEATURE_MULTIARCH;
context->shares &= context->shares_valid;
context->sockets &= context->sockets_valid;
context->devices &= context->devices_valid;
context->features &= context->features_valid;
g_hash_table_remove_all (context->persistent);
g_hash_table_remove_all (context->filesystems);
g_hash_table_remove_all (context->session_bus_policy);
g_hash_table_remove_all (context->system_bus_policy);
g_hash_table_remove_all (context->generic_policy);
}
const char *dont_mount_in_root[] = {
".", "..", "lib", "lib32", "lib64", "bin", "sbin", "usr", "boot", "root",
"tmp", "etc", "app", "run", "proc", "sys", "dev", "var", NULL
};
static void
flatpak_context_export (FlatpakContext *context,
FlatpakExports *exports,
GFile *app_id_dir,
GPtrArray *extra_app_id_dirs,
gboolean do_create,
GString *xdg_dirs_conf,
gboolean *home_access_out)
{
gboolean home_access = FALSE;
FlatpakFilesystemMode fs_mode, os_mode, etc_mode, home_mode;
GHashTableIter iter;
gpointer key, value;
fs_mode = GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "host"));
if (fs_mode != FLATPAK_FILESYSTEM_MODE_NONE)
{
DIR *dir;
struct dirent *dirent;
g_debug ("Allowing host-fs access");
home_access = TRUE;
/* Bind mount most dirs in / into the new root */
dir = opendir ("/");
if (dir != NULL)
{
while ((dirent = readdir (dir)))
{
g_autofree char *path = NULL;
if (g_strv_contains (dont_mount_in_root, dirent->d_name))
continue;
path = g_build_filename ("/", dirent->d_name, NULL);
flatpak_exports_add_path_expose (exports, fs_mode, path);
}
closedir (dir);
}
flatpak_exports_add_path_expose (exports, fs_mode, "/run/media");
}
os_mode = MAX (GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "host-os")),
fs_mode);
if (os_mode != FLATPAK_FILESYSTEM_MODE_NONE)
flatpak_exports_add_host_os_expose (exports, os_mode);
etc_mode = MAX (GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "host-etc")),
fs_mode);
if (etc_mode != FLATPAK_FILESYSTEM_MODE_NONE)
flatpak_exports_add_host_etc_expose (exports, etc_mode);
home_mode = GPOINTER_TO_INT (g_hash_table_lookup (context->filesystems, "home"));
if (home_mode != FLATPAK_FILESYSTEM_MODE_NONE)
{
g_debug ("Allowing homedir access");
home_access = TRUE;
flatpak_exports_add_path_expose (exports, MAX (home_mode, fs_mode), g_get_home_dir ());
}
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *filesystem = key;
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
if (g_strv_contains (flatpak_context_special_filesystems, filesystem))
continue;
if (g_str_has_prefix (filesystem, "xdg-"))
{
const char *path, *rest = NULL;
const char *config_key = NULL;
g_autofree char *subpath = NULL;
if (!get_xdg_user_dir_from_string (filesystem, &config_key, &rest, &path))
{
g_warning ("Unsupported xdg dir %s", filesystem);
continue;
}
if (path == NULL)
continue; /* Unconfigured, ignore */
if (strcmp (path, g_get_home_dir ()) == 0)
{
/* xdg-user-dirs sets disabled dirs to $HOME, and its in general not a good
idea to set full access to $HOME other than explicitly, so we ignore
these */
g_debug ("Xdg dir %s is $HOME (i.e. disabled), ignoring", filesystem);
continue;
}
subpath = g_build_filename (path, rest, NULL);
if (mode == FLATPAK_FILESYSTEM_MODE_CREATE && do_create)
g_mkdir_with_parents (subpath, 0755);
if (g_file_test (subpath, G_FILE_TEST_EXISTS))
{
if (config_key && xdg_dirs_conf)
g_string_append_printf (xdg_dirs_conf, "%s=\"%s\"\n",
config_key, path);
flatpak_exports_add_path_expose_or_hide (exports, mode, subpath);
}
}
else if (g_str_has_prefix (filesystem, "~/"))
{
g_autofree char *path = NULL;
path = g_build_filename (g_get_home_dir (), filesystem + 2, NULL);
if (mode == FLATPAK_FILESYSTEM_MODE_CREATE && do_create)
g_mkdir_with_parents (path, 0755);
if (g_file_test (path, G_FILE_TEST_EXISTS))
flatpak_exports_add_path_expose_or_hide (exports, mode, path);
}
else if (g_str_has_prefix (filesystem, "/"))
{
if (mode == FLATPAK_FILESYSTEM_MODE_CREATE && do_create)
g_mkdir_with_parents (filesystem, 0755);
if (g_file_test (filesystem, G_FILE_TEST_EXISTS))
flatpak_exports_add_path_expose_or_hide (exports, mode, filesystem);
}
else
{
g_warning ("Unexpected filesystem arg %s", filesystem);
}
}
if (app_id_dir)
{
g_autoptr(GFile) apps_dir = g_file_get_parent (app_id_dir);
int i;
/* Hide the .var/app dir by default (unless explicitly made visible) */
flatpak_exports_add_path_tmpfs (exports, flatpak_file_get_path_cached (apps_dir));
/* But let the app write to the per-app dir in it */
flatpak_exports_add_path_expose (exports, FLATPAK_FILESYSTEM_MODE_READ_WRITE,
flatpak_file_get_path_cached (app_id_dir));
if (extra_app_id_dirs != NULL)
{
for (i = 0; i < extra_app_id_dirs->len; i++)
{
GFile *extra_app_id_dir = g_ptr_array_index (extra_app_id_dirs, i);
flatpak_exports_add_path_expose (exports, FLATPAK_FILESYSTEM_MODE_READ_WRITE,
flatpak_file_get_path_cached (extra_app_id_dir));
}
}
}
if (home_access_out != NULL)
*home_access_out = home_access;
}
FlatpakExports *
flatpak_context_get_exports (FlatpakContext *context,
const char *app_id)
{
g_autoptr(FlatpakExports) exports = flatpak_exports_new ();
g_autoptr(GFile) app_id_dir = flatpak_get_data_dir (app_id);
flatpak_context_export (context, exports, app_id_dir, NULL, FALSE, NULL, NULL);
return g_steal_pointer (&exports);
}
FlatpakRunFlags
flatpak_context_get_run_flags (FlatpakContext *context)
{
FlatpakRunFlags flags = 0;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_DEVEL))
flags |= FLATPAK_RUN_FLAG_DEVEL;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_MULTIARCH))
flags |= FLATPAK_RUN_FLAG_MULTIARCH;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_BLUETOOTH))
flags |= FLATPAK_RUN_FLAG_BLUETOOTH;
if (flatpak_context_allows_features (context, FLATPAK_CONTEXT_FEATURE_CANBUS))
flags |= FLATPAK_RUN_FLAG_CANBUS;
return flags;
}
void
flatpak_context_append_bwrap_filesystem (FlatpakContext *context,
FlatpakBwrap *bwrap,
const char *app_id,
GFile *app_id_dir,
GPtrArray *extra_app_id_dirs,
FlatpakExports **exports_out)
{
g_autoptr(FlatpakExports) exports = flatpak_exports_new ();
g_autoptr(GString) xdg_dirs_conf = g_string_new ("");
g_autoptr(GFile) user_flatpak_dir = NULL;
gboolean home_access = FALSE;
GHashTableIter iter;
gpointer key, value;
flatpak_context_export (context, exports, app_id_dir, extra_app_id_dirs, TRUE, xdg_dirs_conf, &home_access);
if (app_id_dir != NULL)
flatpak_run_apply_env_appid (bwrap, app_id_dir);
if (!home_access)
{
/* Enable persistent mapping only if no access to real home dir */
g_hash_table_iter_init (&iter, context->persistent);
while (g_hash_table_iter_next (&iter, &key, NULL))
{
const char *persist = key;
g_autofree char *src = g_build_filename (g_get_home_dir (), ".var/app", app_id, persist, NULL);
g_autofree char *dest = g_build_filename (g_get_home_dir (), persist, NULL);
g_mkdir_with_parents (src, 0755);
flatpak_bwrap_add_bind_arg (bwrap, "--bind", src, dest);
}
}
if (app_id_dir != NULL)
{
g_autofree char *user_runtime_dir = flatpak_get_real_xdg_runtime_dir ();
g_autofree char *run_user_app_dst = g_strdup_printf ("/run/user/%d/app/%s", getuid (), app_id);
g_autofree char *run_user_app_src = g_build_filename (user_runtime_dir, "app", app_id, NULL);
if (glnx_shutil_mkdir_p_at (AT_FDCWD,
run_user_app_src,
0700,
NULL,
NULL))
flatpak_bwrap_add_args (bwrap,
"--bind", run_user_app_src, run_user_app_dst,
NULL);
}
/* Hide the flatpak dir by default (unless explicitly made visible) */
user_flatpak_dir = flatpak_get_user_base_dir_location ();
flatpak_exports_add_path_tmpfs (exports, flatpak_file_get_path_cached (user_flatpak_dir));
/* Ensure we always have a homedir */
flatpak_exports_add_path_dir (exports, g_get_home_dir ());
/* This actually outputs the args for the hide/expose operations above */
flatpak_exports_append_bwrap_args (exports, bwrap);
/* Special case subdirectories of the cache, config and data xdg
* dirs. If these are accessible explicitly, then we bind-mount
* these in the app-id dir. This allows applications to explicitly
* opt out of keeping some config/cache/data in the app-specific
* directory.
*/
if (app_id_dir)
{
g_hash_table_iter_init (&iter, context->filesystems);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *filesystem = key;
FlatpakFilesystemMode mode = GPOINTER_TO_INT (value);
g_autofree char *xdg_path = NULL;
const char *rest, *where;
xdg_path = get_xdg_dir_from_string (filesystem, &rest, &where);
if (xdg_path != NULL && *rest != 0 &&
mode >= FLATPAK_FILESYSTEM_MODE_READ_ONLY)
{
g_autoptr(GFile) app_version = g_file_get_child (app_id_dir, where);
g_autoptr(GFile) app_version_subdir = g_file_resolve_relative_path (app_version, rest);
if (g_file_test (xdg_path, G_FILE_TEST_IS_DIR) ||
g_file_test (xdg_path, G_FILE_TEST_IS_REGULAR))
{
g_autofree char *xdg_path_in_app = g_file_get_path (app_version_subdir);
flatpak_bwrap_add_bind_arg (bwrap,
mode == FLATPAK_FILESYSTEM_MODE_READ_ONLY ? "--ro-bind" : "--bind",
xdg_path, xdg_path_in_app);
}
}
}
}
if (home_access && app_id_dir != NULL)
{
g_autofree char *src_path = g_build_filename (g_get_user_config_dir (),
"user-dirs.dirs",
NULL);
g_autofree char *path = g_build_filename (flatpak_file_get_path_cached (app_id_dir),
"config/user-dirs.dirs", NULL);
if (g_file_test (src_path, G_FILE_TEST_EXISTS))
flatpak_bwrap_add_bind_arg (bwrap, "--ro-bind", src_path, path);
}
else if (xdg_dirs_conf->len > 0 && app_id_dir != NULL)
{
g_autofree char *path =
g_build_filename (flatpak_file_get_path_cached (app_id_dir),
"config/user-dirs.dirs", NULL);
flatpak_bwrap_add_args_data (bwrap, "xdg-config-dirs",
xdg_dirs_conf->str, xdg_dirs_conf->len, path, NULL);
}
if (exports_out)
*exports_out = g_steal_pointer (&exports);
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1907_0 |
crossvul-cpp_data_good_1909_0 | /*
* Copyright © 2018 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
/* NOTE: This code was copied mostly as-is from xdg-desktop-portal */
#include <locale.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
#include <gio/gdesktopappinfo.h>
#include "flatpak-portal-dbus.h"
#include "flatpak-portal.h"
#include "flatpak-dir-private.h"
#include "flatpak-utils-private.h"
#include "flatpak-transaction.h"
#include "flatpak-installation-private.h"
#include "flatpak-instance-private.h"
#include "flatpak-portal-app-info.h"
#include "flatpak-portal-error.h"
#include "flatpak-utils-base-private.h"
#include "portal-impl.h"
#include "flatpak-permission-dbus.h"
/* GLib 2.47.92 was the first release to define these in gdbus-codegen */
#if !GLIB_CHECK_VERSION (2, 47, 92)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakSkeleton, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorProxy, g_object_unref)
G_DEFINE_AUTOPTR_CLEANUP_FUNC (PortalFlatpakUpdateMonitorSkeleton, g_object_unref)
#endif
#define IDLE_TIMEOUT_SECS 10 * 60
/* Should be roughly 2 seconds */
#define CHILD_STATUS_CHECK_ATTEMPTS 20
static GHashTable *client_pid_data_hash = NULL;
static GDBusConnection *session_bus = NULL;
static GNetworkMonitor *network_monitor = NULL;
static gboolean no_idle_exit = FALSE;
static guint name_owner_id = 0;
static GMainLoop *main_loop;
static PortalFlatpak *portal;
static gboolean opt_verbose;
static int opt_poll_timeout;
static gboolean opt_poll_when_metered;
static FlatpakSpawnSupportFlags supports = 0;
G_LOCK_DEFINE (update_monitors); /* This protects the three variables below */
static GHashTable *update_monitors;
static guint update_monitors_timeout = 0;
static gboolean update_monitors_timeout_running_thread = FALSE;
/* Poll all update monitors twice an hour */
#define DEFAULT_UPDATE_POLL_TIMEOUT_SEC (30 * 60)
#define PERMISSION_TABLE "flatpak"
#define PERMISSION_ID "updates"
/* Instance IDs are 32-bit unsigned integers */
#define INSTANCE_ID_BUFFER_SIZE 16
typedef enum { UNSET, ASK, YES, NO } Permission;
typedef enum {
PROGRESS_STATUS_RUNNING = 0,
PROGRESS_STATUS_EMPTY = 1,
PROGRESS_STATUS_DONE = 2,
PROGRESS_STATUS_ERROR = 3
} UpdateStatus;
static XdpDbusPermissionStore *permission_store;
typedef struct {
GMutex lock; /* This protects the closed, running and installed state */
gboolean closed;
gboolean running; /* While this is set, don't close the monitor */
gboolean installing;
char *sender;
char *obj_path;
GCancellable *cancellable;
/* Static data */
char *name;
char *arch;
char *branch;
char *commit;
char *app_path;
/* Last reported values, starting at the instance commit */
char *reported_local_commit;
char *reported_remote_commit;
} UpdateMonitorData;
static gboolean check_all_for_updates_cb (void *data);
static gboolean has_update_monitors (void);
static UpdateMonitorData *update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor);
static gboolean handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation);
static gboolean handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options);
static void
skeleton_died_cb (gpointer data)
{
g_debug ("skeleton finalized, exiting");
g_main_loop_quit (main_loop);
}
static gboolean
unref_skeleton_in_timeout_cb (gpointer user_data)
{
static gboolean unreffed = FALSE;
g_debug ("unreffing portal main ref");
if (!unreffed)
{
g_object_unref (portal);
unreffed = TRUE;
}
return G_SOURCE_REMOVE;
}
static void
unref_skeleton_in_timeout (void)
{
if (name_owner_id)
g_bus_unown_name (name_owner_id);
name_owner_id = 0;
/* After we've lost the name or idled we drop the main ref on the helper
so that we'll exit when it drops to zero. However, if there are
outstanding calls these will keep the refcount up during the
execution of them. We do the unref on a timeout to make sure
we're completely draining the queue of (stale) requests. */
g_timeout_add (500, unref_skeleton_in_timeout_cb, NULL);
}
static guint idle_timeout_id = 0;
static gboolean
idle_timeout_cb (gpointer user_data)
{
if (name_owner_id &&
g_hash_table_size (client_pid_data_hash) == 0 &&
!has_update_monitors ())
{
g_debug ("Idle - unowning name");
unref_skeleton_in_timeout ();
}
idle_timeout_id = 0;
return G_SOURCE_REMOVE;
}
G_LOCK_DEFINE_STATIC (idle);
static void
schedule_idle_callback (void)
{
G_LOCK (idle);
if (!no_idle_exit)
{
if (idle_timeout_id != 0)
g_source_remove (idle_timeout_id);
idle_timeout_id = g_timeout_add_seconds (IDLE_TIMEOUT_SECS, idle_timeout_cb, NULL);
}
G_UNLOCK (idle);
}
typedef struct
{
GPid pid;
char *client;
guint child_watch;
gboolean watch_bus;
gboolean expose_or_share_pids;
} PidData;
static void
pid_data_free (PidData *data)
{
g_free (data->client);
g_free (data);
}
static void
child_watch_died (GPid pid,
gint status,
gpointer user_data)
{
PidData *pid_data = user_data;
g_autoptr(GVariant) signal_variant = NULL;
g_debug ("Client Pid %d died", pid_data->pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, status));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnExited",
signal_variant,
NULL);
/* This frees the pid_data, so be careful */
g_hash_table_remove (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid));
/* This might have caused us to go to idle (zero children) */
schedule_idle_callback ();
}
typedef struct
{
int from;
int to;
int final;
} FdMapEntry;
typedef struct
{
FdMapEntry *fd_map;
int fd_map_len;
int instance_id_fd;
gboolean set_tty;
int tty;
int env_fd;
} ChildSetupData;
typedef struct
{
guint pid;
gchar buffer[INSTANCE_ID_BUFFER_SIZE];
} InstanceIdReadData;
typedef struct
{
FlatpakInstance *instance;
guint pid;
guint attempt;
} BwrapinfoWatcherData;
static void
bwrapinfo_watcher_data_free (BwrapinfoWatcherData* data)
{
g_object_unref (data->instance);
g_free (data);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC (BwrapinfoWatcherData, bwrapinfo_watcher_data_free)
static int
get_child_pid_relative_to_parent_sandbox (int pid,
GError **error)
{
g_autofree char *status_file_path = NULL;
g_autoptr(GFile) status_file = NULL;
g_autoptr(GFileInputStream) input_stream = NULL;
g_autoptr(GDataInputStream) data_stream = NULL;
int relative_pid = 0;
status_file_path = g_strdup_printf ("/proc/%u/status", pid);
status_file = g_file_new_for_path (status_file_path);
input_stream = g_file_read (status_file, NULL, error);
if (input_stream == NULL)
return 0;
data_stream = g_data_input_stream_new (G_INPUT_STREAM (input_stream));
while (TRUE)
{
g_autofree char *line = g_data_input_stream_read_line_utf8 (data_stream, NULL, NULL, error);
if (line == NULL)
break;
g_strchug (line);
if (g_str_has_prefix (line, "NSpid:"))
{
g_auto(GStrv) fields = NULL;
guint nfields = 0;
char *endptr = NULL;
fields = g_strsplit (line, "\t", -1);
nfields = g_strv_length (fields);
if (nfields < 3)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"NSpid line has too few fields: %s", line);
return 0;
}
/* The second to last PID namespace is the one that spawned this process */
relative_pid = strtol (fields[nfields - 2], &endptr, 10);
if (*endptr)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
"Invalid parent-relative PID in NSpid line: %s", line);
return 0;
}
return relative_pid;
}
}
if (*error == NULL)
/* EOF was reached while reading the file */
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND, "NSpid not found");
return 0;
}
static int
check_child_pid_status (void *user_data)
{
/* Stores a sequence of the time interval to use until the child PID is checked again.
In general from testing, bwrapinfo is never ready before 25ms have passed at minimum,
thus 25ms is the first interval, doubling until a max interval of 100ms is reached.
In addition, if the program is not available after 100ms for an extended period of time,
the timeout is further increased to a full second. */
static gint timeouts[] = {25, 50, 100};
g_autoptr(GVariant) signal_variant = NULL;
g_autoptr(BwrapinfoWatcherData) data = user_data;
PidData *pid_data;
guint pid;
int child_pid;
int relative_child_pid = 0;
pid = data->pid;
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (pid));
/* Process likely already exited if pid_data == NULL, so don't send the
signal to avoid an awkward out-of-order SpawnExited -> SpawnStarted. */
if (pid_data == NULL)
{
g_warning ("%u already exited, skipping SpawnStarted", pid);
return G_SOURCE_REMOVE;
}
child_pid = flatpak_instance_get_child_pid (data->instance);
if (child_pid == 0)
{
gint timeout;
gboolean readd_timer = FALSE;
if (data->attempt >= CHILD_STATUS_CHECK_ATTEMPTS)
/* If too many attempts, use a 1 second timeout */
timeout = 1000;
else
timeout = timeouts[MIN (data->attempt, G_N_ELEMENTS (timeouts) - 1)];
g_debug ("Failed to read child PID, trying again in %d ms", timeout);
/* The timer source only needs to be re-added if the timeout has changed,
which won't happen while staying on the 100 or 1000ms timeouts.
This test must happen *before* the attempt counter is incremented, since the
attempt counter represents the *current* timeout. */
readd_timer = data->attempt <= G_N_ELEMENTS (timeouts) || data->attempt == CHILD_STATUS_CHECK_ATTEMPTS;
data->attempt++;
/* Make sure the data isn't destroyed */
data = NULL;
if (readd_timer)
{
g_timeout_add (timeout, check_child_pid_status, user_data);
return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
/* Only send the child PID if it's exposed */
if (pid_data->expose_or_share_pids)
{
g_autoptr(GError) error = NULL;
relative_child_pid = get_child_pid_relative_to_parent_sandbox (child_pid, &error);
if (relative_child_pid == 0)
g_warning ("Failed to find relative PID for %d: %s", child_pid, error->message);
}
g_debug ("Emitting SpawnStarted(%u, %d)", pid, relative_child_pid);
signal_variant = g_variant_ref_sink (g_variant_new ("(uu)", pid, relative_child_pid));
g_dbus_connection_emit_signal (session_bus,
pid_data->client,
"/org/freedesktop/portal/Flatpak",
"org.freedesktop.portal.Flatpak",
"SpawnStarted",
signal_variant,
NULL);
return G_SOURCE_REMOVE;
}
static void
instance_id_read_finish (GObject *source,
GAsyncResult *res,
gpointer user_data)
{
g_autoptr(GInputStream) stream = NULL;
g_autofree InstanceIdReadData *data = NULL;
g_autoptr(FlatpakInstance) instance = NULL;
g_autoptr(GError) error = NULL;
BwrapinfoWatcherData *watcher_data = NULL;
gssize bytes_read;
stream = G_INPUT_STREAM (source);
data = (InstanceIdReadData *) user_data;
bytes_read = g_input_stream_read_finish (stream, res, &error);
if (bytes_read <= 0)
{
/* 0 means EOF, so the process could never have been started. */
if (bytes_read == -1)
g_warning ("Failed to read instance id: %s", error->message);
return;
}
data->buffer[bytes_read] = 0;
instance = flatpak_instance_new_for_id (data->buffer);
watcher_data = g_new0 (BwrapinfoWatcherData, 1);
watcher_data->instance = g_steal_pointer (&instance);
watcher_data->pid = data->pid;
check_child_pid_status (watcher_data);
}
static void
drop_cloexec (int fd)
{
fcntl (fd, F_SETFD, 0);
}
static void
child_setup_func (gpointer user_data)
{
ChildSetupData *data = (ChildSetupData *) user_data;
FdMapEntry *fd_map = data->fd_map;
sigset_t set;
int i;
flatpak_close_fds_workaround (3);
if (data->instance_id_fd != -1)
drop_cloexec (data->instance_id_fd);
if (data->env_fd != -1)
drop_cloexec (data->env_fd);
/* Unblock all signals */
sigemptyset (&set);
if (pthread_sigmask (SIG_SETMASK, &set, NULL) == -1)
{
g_warning ("Failed to unblock signals when starting child");
return;
}
/* Reset the handlers for all signals to their defaults. */
for (i = 1; i < NSIG; i++)
{
if (i != SIGSTOP && i != SIGKILL)
signal (i, SIG_DFL);
}
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from != fd_map[i].to)
{
dup2 (fd_map[i].from, fd_map[i].to);
close (fd_map[i].from);
}
}
/* Second pass in case we needed an in-between fd value to avoid conflicts */
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].to != fd_map[i].final)
{
dup2 (fd_map[i].to, fd_map[i].final);
close (fd_map[i].to);
}
/* Ensure we inherit the final fd value */
drop_cloexec (fd_map[i].final);
}
/* We become our own session and process group, because it never makes sense
to share the flatpak-session-helper dbus activated process group */
setsid ();
setpgid (0, 0);
if (data->set_tty)
{
/* data->tty is our from fd which is closed at this point.
* so locate the destination fd and use it for the ioctl.
*/
for (i = 0; i < data->fd_map_len; i++)
{
if (fd_map[i].from == data->tty)
{
if (ioctl (fd_map[i].final, TIOCSCTTY, 0) == -1)
g_debug ("ioctl(%d, TIOCSCTTY, 0) failed: %s",
fd_map[i].final, strerror (errno));
break;
}
}
}
}
static gboolean
is_valid_expose (const char *expose,
GError **error)
{
/* No subdirs or absolute paths */
if (expose[0] == '/')
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: absolute paths not allowed");
return FALSE;
}
else if (strchr (expose, '/'))
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose: subdirectories not allowed");
return FALSE;
}
return TRUE;
}
static char *
filesystem_arg (const char *path,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
filesystem_sandbox_arg (const char *path,
const char *sandbox,
gboolean readonly)
{
g_autoptr(GString) s = g_string_new ("--filesystem=");
const char *p;
for (p = path; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
g_string_append (s, "/sandbox/");
for (p = sandbox; *p != 0; p++)
{
if (*p == ':')
g_string_append (s, "\\:");
else
g_string_append_c (s, *p);
}
if (readonly)
g_string_append (s, ":ro");
return g_string_free (g_steal_pointer (&s), FALSE);
}
static char *
bubblewrap_remap_path (const char *path)
{
if (g_str_has_prefix (path, "/newroot/"))
path = path + strlen ("/newroot");
return g_strdup (path);
}
static char *
verify_proc_self_fd (const char *proc_path,
GError **error)
{
char path_buffer[PATH_MAX + 1];
ssize_t symlink_size;
symlink_size = readlink (proc_path, path_buffer, PATH_MAX);
if (symlink_size < 0)
return glnx_null_throw_errno_prefix (error, "readlink");
path_buffer[symlink_size] = 0;
/* All normal paths start with /, but some weird things
don't, such as socket:[27345] or anon_inode:[eventfd].
We don't support any of these */
if (path_buffer[0] != '/')
return glnx_null_throw (error, "%s resolves to non-absolute path %s",
proc_path, path_buffer);
/* File descriptors to actually deleted files have " (deleted)"
appended to them. This also happens to some fake fd types
like shmem which are "/<name> (deleted)". All such
files are considered invalid. Unfortunatelly this also
matches files with filenames that actually end in " (deleted)",
but there is not much to do about this. */
if (g_str_has_suffix (path_buffer, " (deleted)"))
return glnx_null_throw (error, "%s resolves to deleted path %s",
proc_path, path_buffer);
/* remap from sandbox to host if needed */
return bubblewrap_remap_path (path_buffer);
}
static char *
get_path_for_fd (int fd,
gboolean *writable_out,
GError **error)
{
g_autofree char *proc_path = NULL;
int fd_flags;
struct stat st_buf;
struct stat real_st_buf;
g_autofree char *path = NULL;
gboolean writable = FALSE;
int read_access_mode;
/* Must be able to get fd flags */
fd_flags = fcntl (fd, F_GETFL);
if (fd_flags == -1)
return glnx_null_throw_errno_prefix (error, "fcntl F_GETFL");
/* Must be O_PATH */
if ((fd_flags & O_PATH) != O_PATH)
return glnx_null_throw (error, "not opened with O_PATH");
/* We don't want to allow exposing symlinks, because if they are
* under the callers control they could be changed between now and
* starting the child allowing it to point anywhere, so enforce NOFOLLOW.
* and verify that stat is not a link.
*/
if ((fd_flags & O_NOFOLLOW) != O_NOFOLLOW)
return glnx_null_throw (error, "not opened with O_NOFOLLOW");
/* Must be able to fstat */
if (fstat (fd, &st_buf) < 0)
return glnx_null_throw_errno_prefix (error, "fstat");
/* As per above, no symlinks */
if (S_ISLNK (st_buf.st_mode))
return glnx_null_throw (error, "is a symbolic link");
proc_path = g_strdup_printf ("/proc/self/fd/%d", fd);
/* Must be able to read valid path from /proc/self/fd */
/* This is an absolute and (at least at open time) symlink-expanded path */
path = verify_proc_self_fd (proc_path, error);
if (path == NULL)
return NULL;
/* Verify that this is the same file as the app opened */
if (stat (path, &real_st_buf) < 0 ||
st_buf.st_dev != real_st_buf.st_dev ||
st_buf.st_ino != real_st_buf.st_ino)
{
/* Different files on the inside and the outside, reject the request */
return glnx_null_throw (error,
"different file inside and outside sandbox");
}
read_access_mode = R_OK;
if (S_ISDIR (st_buf.st_mode))
read_access_mode |= X_OK;
/* Must be able to access the path via the sandbox supplied O_PATH fd,
which applies the sandbox side mount options (like readonly). */
if (access (proc_path, read_access_mode) != 0)
return glnx_null_throw (error, "not %s in sandbox",
read_access_mode & X_OK ? "accessible" : "readable");
if (access (proc_path, W_OK) == 0)
writable = TRUE;
*writable_out = writable;
return g_steal_pointer (&path);
}
static gboolean
handle_spawn (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GUnixFDList *fd_list,
const gchar *arg_cwd_path,
const gchar *const *arg_argv,
GVariant *arg_fds,
GVariant *arg_envs,
guint arg_flags,
GVariant *arg_options)
{
g_autoptr(GError) error = NULL;
ChildSetupData child_setup_data = { NULL };
GPid pid;
PidData *pid_data;
InstanceIdReadData *instance_id_read_data = NULL;
gsize i, j, n_fds, n_envs;
const gint *fds = NULL;
gint fds_len = 0;
g_autofree FdMapEntry *fd_map = NULL;
gchar **env;
gint32 max_fd;
GKeyFile *app_info;
g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);
g_autofree char *app_id = NULL;
g_autofree char *branch = NULL;
g_autofree char *arch = NULL;
g_autofree char *app_commit = NULL;
g_autofree char *runtime_ref = NULL;
g_auto(GStrv) runtime_parts = NULL;
g_autofree char *runtime_commit = NULL;
g_autofree char *instance_path = NULL;
g_auto(GStrv) extra_args = NULL;
g_auto(GStrv) shares = NULL;
g_auto(GStrv) sockets = NULL;
g_auto(GStrv) devices = NULL;
g_auto(GStrv) sandbox_expose = NULL;
g_auto(GStrv) sandbox_expose_ro = NULL;
g_autoptr(GVariant) sandbox_expose_fd = NULL;
g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;
g_autoptr(GOutputStream) instance_id_out_stream = NULL;
guint sandbox_flags = 0;
gboolean sandboxed;
gboolean expose_pids;
gboolean share_pids;
gboolean notify_start;
gboolean devel;
g_autoptr(GString) env_string = g_string_new ("");
child_setup_data.instance_id_fd = -1;
child_setup_data.env_fd = -1;
if (fd_list != NULL)
fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);
app_info = g_object_get_data (G_OBJECT (invocation), "app-info");
g_assert (app_info != NULL);
app_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, NULL);
g_assert (app_id != NULL);
g_debug ("spawn() called from app: '%s'", app_id);
if (*app_id == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (*arg_cwd_path == 0)
arg_cwd_path = NULL;
if (arg_argv == NULL || *arg_argv == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No command given");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_ref = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_RUNTIME, NULL);
if (runtime_ref == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"No runtime found");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
runtime_parts = g_strsplit (runtime_ref, "/", -1);
branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_BRANCH, NULL);
instance_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);
arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_ARCH, NULL);
extra_args = g_key_file_get_string_list (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);
app_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_APP_COMMIT, NULL);
runtime_commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);
shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SHARED, NULL, NULL);
sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);
devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,
FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);
devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_DEVEL, NULL);
g_variant_lookup (arg_options, "sandbox-expose", "^as", &sandbox_expose);
g_variant_lookup (arg_options, "sandbox-expose-ro", "^as", &sandbox_expose_ro);
g_variant_lookup (arg_options, "sandbox-flags", "u", &sandbox_flags);
sandbox_expose_fd = g_variant_lookup_value (arg_options, "sandbox-expose-fd", G_VARIANT_TYPE ("ah"));
sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, "sandbox-expose-fd-ro", G_VARIANT_TYPE ("ah"));
if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
"Unsupported sandbox flags enabled: 0x%x", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_path == NULL &&
((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||
(sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Invalid sandbox expose, caller has no instance path");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
{
const char *expose = sandbox_expose[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
if (!is_valid_expose (expose, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
g_debug ("Running spawn command %s", arg_argv[0]);
n_fds = 0;
if (fds != NULL)
n_fds = g_variant_n_children (arg_fds);
fd_map = g_new0 (FdMapEntry, n_fds);
child_setup_data.fd_map = fd_map;
child_setup_data.fd_map_len = n_fds;
max_fd = -1;
for (i = 0; i < n_fds; i++)
{
gint32 handle, dest_fd;
int handle_fd;
g_variant_get_child (arg_fds, i, "{uh}", &dest_fd, &handle);
if (handle >= fds_len || handle < 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
handle_fd = fds[handle];
fd_map[i].to = dest_fd;
fd_map[i].from = handle_fd;
fd_map[i].final = fd_map[i].to;
/* If stdin/out/err is a tty we try to set it as the controlling
tty for the app, this way we can use this to run in a terminal. */
if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&
!child_setup_data.set_tty &&
isatty (handle_fd))
{
child_setup_data.set_tty = TRUE;
child_setup_data.tty = handle_fd;
}
max_fd = MAX (max_fd, fd_map[i].to);
max_fd = MAX (max_fd, fd_map[i].from);
}
/* We make a second pass over the fds to find if any "to" fd index
overlaps an already in use fd (i.e. one in the "from" category
that are allocated randomly). If a fd overlaps "to" fd then its
a caller issue and not our fault, so we ignore that. */
for (i = 0; i < n_fds; i++)
{
int to_fd = fd_map[i].to;
gboolean conflict = FALSE;
/* At this point we're fine with using "from" values for this
value (because we handle to==from in the code), or values
that are before "i" in the fd_map (because those will be
closed at this point when dup:ing). However, we can't
reuse a fd that is in "from" for j > i. */
for (j = i + 1; j < n_fds; j++)
{
int from_fd = fd_map[j].from;
if (from_fd == to_fd)
{
conflict = TRUE;
break;
}
}
if (conflict)
fd_map[i].to = ++max_fd;
}
if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)
{
char *empty[] = { NULL };
env = g_strdupv (empty);
}
else
env = g_get_environ ();
/* Let the environment variables given by the caller override the ones
* from extra_args. Don't add them to @env, because they are controlled
* by our caller, which might be trying to use them to inject code into
* flatpak(1); add them to the environment block instead.
*
* We don't use --env= here, so that if the values are something that
* should not be exposed to other uids, they can remain confidential. */
n_envs = g_variant_n_children (arg_envs);
for (i = 0; i < n_envs; i++)
{
const char *var = NULL;
const char *val = NULL;
g_variant_get_child (arg_envs, i, "{&s&s}", &var, &val);
if (var[0] == '\0')
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Environment variable cannot have empty name");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (strchr (var, '=') != NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Environment variable name cannot contain '='");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_string_append (env_string, var);
g_string_append_c (env_string, '=');
g_string_append (env_string, val);
g_string_append_c (env_string, '\0');
}
g_ptr_array_add (flatpak_argv, g_strdup ("flatpak"));
g_ptr_array_add (flatpak_argv, g_strdup ("run"));
sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;
if (sandboxed)
{
g_ptr_array_add (flatpak_argv, g_strdup ("--sandbox"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "wayland"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=wayland"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "fallback-x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=fallback-x11"));
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "x11"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=x11"));
if (shares != NULL && g_strv_contains ((const char * const *) shares, "ipc") &&
sockets != NULL && (g_strv_contains ((const char * const *) sockets, "fallback-x11") ||
g_strv_contains ((const char * const *) sockets, "x11")))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=ipc"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)
{
if (sockets != NULL && g_strv_contains ((const char * const *) sockets, "pulseaudio"))
g_ptr_array_add (flatpak_argv, g_strdup ("--socket=pulseaudio"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)
{
if (devices != NULL &&
(g_strv_contains ((const char * const *) devices, "dri") ||
g_strv_contains ((const char * const *) devices, "all")))
g_ptr_array_add (flatpak_argv, g_strdup ("--device=dri"));
}
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)
g_ptr_array_add (flatpak_argv, g_strdup ("--session-bus"));
if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)
g_ptr_array_add (flatpak_argv, g_strdup ("--a11y-bus"));
}
else
{
for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)
{
if (g_str_has_prefix (extra_args[i], "--env="))
{
const char *var_val = extra_args[i] + strlen ("--env=");
if (var_val[0] == '\0' || var_val[0] == '=')
{
g_warning ("Environment variable in extra-args has empty name");
continue;
}
if (strchr (var_val, '=') == NULL)
{
g_warning ("Environment variable in extra-args has no value");
continue;
}
g_string_append (env_string, var_val);
g_string_append_c (env_string, '\0');
}
else
{
g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));
}
}
}
if (env_string->len > 0)
{
g_auto(GLnxTmpfile) env_tmpf = { 0, };
if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&env_tmpf, "environ",
env_string->str,
env_string->len, &error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
child_setup_data.env_fd = glnx_steal_fd (&env_tmpf.fd);
g_ptr_array_add (flatpak_argv,
g_strdup_printf ("--env-fd=%d",
child_setup_data.env_fd));
}
expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;
share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;
if (expose_pids || share_pids)
{
g_autofree char *instance_id = NULL;
int sender_pid1 = 0;
if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_NOT_SUPPORTED,
"Expose pids not supported with setuid bwrap");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
instance_id = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);
if (instance_id)
{
g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);
sender_pid1 = flatpak_instance_get_child_pid (instance);
}
if (sender_pid1 == 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"Could not find requesting pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--parent-pid=%d", sender_pid1));
if (share_pids)
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-share-pids"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--parent-expose-pids"));
}
notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;
if (notify_start)
{
int pipe_fds[2];
if (pipe (pipe_fds) == -1)
{
int errsv = errno;
g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,
g_io_error_from_errno (errsv),
"Failed to create instance ID pipe: %s",
g_strerror (errsv));
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));
/* This is saved to ensure the portal's end gets closed after the exec. */
instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));
instance_id_read_data = g_new0 (InstanceIdReadData, 1);
g_input_stream_read_async (in_stream, instance_id_read_data->buffer,
INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,
instance_id_read_finish, instance_id_read_data);
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--instance-id-fd=%d", pipe_fds[1]));
child_setup_data.instance_id_fd = pipe_fds[1];
}
if (devel)
g_ptr_array_add (flatpak_argv, g_strdup ("--devel"));
/* Inherit launcher network access from launcher, unless
NO_NETWORK set. */
if (shares != NULL && g_strv_contains ((const char * const *) shares, "network") &&
!(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))
g_ptr_array_add (flatpak_argv, g_strdup ("--share=network"));
else
g_ptr_array_add (flatpak_argv, g_strdup ("--unshare=network"));
if (instance_path)
{
for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
g_ptr_array_add (flatpak_argv,
filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));
}
for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)
{
const char *expose = sandbox_expose_ro[i];
g_debug ("exposing %s", expose);
}
if (sandbox_expose_fd != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
if (sandbox_expose_fd_ro != NULL)
{
gsize len = g_variant_n_children (sandbox_expose_fd_ro);
for (i = 0; i < len; i++)
{
gint32 handle;
g_variant_get_child (sandbox_expose_fd_ro, i, "h", &handle);
if (handle >= 0 && handle < fds_len)
{
int handle_fd = fds[handle];
g_autofree char *path = NULL;
gboolean writable = FALSE;
path = get_path_for_fd (handle_fd, &writable, &error);
if (path)
{
g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));
}
else
{
g_debug ("unable to get path for sandbox-exposed fd %d, ignoring: %s",
handle_fd, error->message);
g_clear_error (&error);
}
}
else
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_INVALID_ARGS,
"No file descriptor for handle %d",
handle);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
}
}
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime=%s", runtime_parts[1]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-version=%s", runtime_parts[3]));
if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)
{
if (app_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--commit=%s", app_commit));
if (runtime_commit)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--runtime-commit=%s", runtime_commit));
}
if (arg_cwd_path != NULL)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--cwd=%s", arg_cwd_path));
if (arg_argv[0][0] != 0)
g_ptr_array_add (flatpak_argv, g_strdup_printf ("--command=%s", arg_argv[0]));
g_ptr_array_add (flatpak_argv, g_strdup_printf ("%s/%s/%s", app_id, arch ? arch : "", branch ? branch : ""));
for (i = 1; arg_argv[i] != NULL; i++)
g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));
g_ptr_array_add (flatpak_argv, NULL);
if (opt_verbose)
{
g_autoptr(GString) cmd = g_string_new ("");
for (i = 0; flatpak_argv->pdata[i] != NULL; i++)
{
if (i > 0)
g_string_append (cmd, " ");
g_string_append (cmd, flatpak_argv->pdata[i]);
}
g_debug ("Starting: %s\n", cmd->str);
}
/* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */
if (!g_spawn_async_with_pipes (NULL,
(char **) flatpak_argv->pdata,
env,
G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
child_setup_func, &child_setup_data,
&pid,
NULL,
NULL,
NULL,
&error))
{
gint code = G_DBUS_ERROR_FAILED;
if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))
code = G_DBUS_ERROR_ACCESS_DENIED;
else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))
code = G_DBUS_ERROR_FILE_NOT_FOUND;
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,
"Failed to start command: %s",
error->message);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
if (instance_id_read_data)
instance_id_read_data->pid = pid;
pid_data = g_new0 (PidData, 1);
pid_data->pid = pid;
pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));
pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;
pid_data->expose_or_share_pids = (expose_pids || share_pids);
pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,
pid,
child_watch_died,
pid_data,
NULL);
g_debug ("Client Pid is %d", pid_data->pid);
g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),
pid_data);
portal_flatpak_complete_spawn (object, invocation, NULL, pid);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
handle_spawn_signal (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
guint arg_pid,
guint arg_signal,
gboolean arg_to_process_group)
{
PidData *pid_data = NULL;
g_debug ("spawn_signal(%d %d)", arg_pid, arg_signal);
pid_data = g_hash_table_lookup (client_pid_data_hash, GUINT_TO_POINTER (arg_pid));
if (pid_data == NULL ||
strcmp (pid_data->client, g_dbus_method_invocation_get_sender (invocation)) != 0)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,
G_DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,
"No such pid");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_debug ("Sending signal %d to client pid %d", arg_signal, arg_pid);
if (arg_to_process_group)
killpg (pid_data->pid, arg_signal);
else
kill (pid_data->pid, arg_signal);
portal_flatpak_complete_spawn_signal (portal, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static gboolean
authorize_method_handler (GDBusInterfaceSkeleton *interface,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
g_autoptr(GError) error = NULL;
g_autoptr(GKeyFile) keyfile = NULL;
g_autofree char *app_id = NULL;
const char *required_sender;
/* Ensure we don't idle exit */
schedule_idle_callback ();
required_sender = g_object_get_data (G_OBJECT (interface), "required-sender");
if (required_sender)
{
const char *sender = g_dbus_method_invocation_get_sender (invocation);
if (g_strcmp0 (required_sender, sender) != 0)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
"Client not allowed to access object");
return FALSE;
}
}
keyfile = flatpak_invocation_lookup_app_info (invocation, NULL, &error);
if (keyfile == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
app_id = g_key_file_get_string (keyfile,
FLATPAK_METADATA_GROUP_APPLICATION,
FLATPAK_METADATA_KEY_NAME, &error);
if (app_id == NULL)
{
g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
"Authorization error: %s", error->message);
return FALSE;
}
g_object_set_data_full (G_OBJECT (invocation), "app-info", g_steal_pointer (&keyfile), (GDestroyNotify) g_key_file_unref);
return TRUE;
}
static void
register_update_monitor (PortalFlatpakUpdateMonitor *monitor,
const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_insert (update_monitors, g_strdup (obj_path), g_object_ref (monitor));
/* Trigger update timeout if needed */
if (update_monitors_timeout == 0 && !update_monitors_timeout_running_thread)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
static void
unregister_update_monitor (const char *obj_path)
{
G_LOCK (update_monitors);
g_hash_table_remove (update_monitors, obj_path);
G_UNLOCK (update_monitors);
}
static gboolean
has_update_monitors (void)
{
gboolean res;
G_LOCK (update_monitors);
res = g_hash_table_size (update_monitors) > 0;
G_UNLOCK (update_monitors);
return res;
}
static GList *
update_monitors_get_all (const char *optional_sender)
{
GList *list = NULL;
G_LOCK (update_monitors);
if (update_monitors)
{
GLNX_HASH_TABLE_FOREACH_V (update_monitors, PortalFlatpakUpdateMonitor *, monitor)
{
UpdateMonitorData *data = update_monitor_get_data (monitor);
if (optional_sender == NULL ||
strcmp (data->sender, optional_sender) == 0)
list = g_list_prepend (list, g_object_ref (monitor));
}
}
G_UNLOCK (update_monitors);
return list;
}
static void
update_monitor_data_free (gpointer data)
{
UpdateMonitorData *m = data;
g_mutex_clear (&m->lock);
g_free (m->sender);
g_free (m->obj_path);
g_object_unref (m->cancellable);
g_free (m->name);
g_free (m->arch);
g_free (m->branch);
g_free (m->commit);
g_free (m->app_path);
g_free (m->reported_local_commit);
g_free (m->reported_remote_commit);
g_free (m);
}
static UpdateMonitorData *
update_monitor_get_data (PortalFlatpakUpdateMonitor *monitor)
{
return (UpdateMonitorData *)g_object_get_data (G_OBJECT (monitor), "update-monitor-data");
}
static PortalFlatpakUpdateMonitor *
create_update_monitor (GDBusMethodInvocation *invocation,
const char *obj_path,
GError **error)
{
PortalFlatpakUpdateMonitor *monitor;
UpdateMonitorData *m;
g_autoptr(GKeyFile) app_info = NULL;
g_autofree char *name = NULL;
app_info = flatpak_invocation_lookup_app_info (invocation, NULL, error);
if (app_info == NULL)
return NULL;
name = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_APPLICATION,
"name", NULL);
if (name == NULL || *name == 0)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
"Updates only supported by flatpak apps");
return NULL;
}
m = g_new0 (UpdateMonitorData, 1);
g_mutex_init (&m->lock);
m->obj_path = g_strdup (obj_path);
m->sender = g_strdup (g_dbus_method_invocation_get_sender (invocation));
m->cancellable = g_cancellable_new ();
m->name = g_steal_pointer (&name);
m->arch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"arch", NULL);
m->branch = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"branch", NULL);
m->commit = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-commit", NULL);
m->app_path = g_key_file_get_string (app_info,
FLATPAK_METADATA_GROUP_INSTANCE,
"app-path", NULL);
m->reported_local_commit = g_strdup (m->commit);
m->reported_remote_commit = g_strdup (m->commit);
monitor = portal_flatpak_update_monitor_skeleton_new ();
g_object_set_data_full (G_OBJECT (monitor), "update-monitor-data", m, update_monitor_data_free);
g_object_set_data_full (G_OBJECT (monitor), "required-sender", g_strdup (m->sender), g_free);
g_debug ("created UpdateMonitor for %s/%s at %s", m->name, m->branch, obj_path);
return monitor;
}
static void
update_monitor_do_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_dbus_interface_skeleton_unexport (G_DBUS_INTERFACE_SKELETON (monitor));
unregister_update_monitor (m->obj_path);
}
/* Always called in worker thread */
static void
update_monitor_close (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean do_close;
g_mutex_lock (&m->lock);
/* Close at most once, but not if running, if running it will be closed when that is done */
do_close = !m->closed && !m->running;
m->closed = TRUE;
g_mutex_unlock (&m->lock);
/* Always cancel though, so we can exit any running code early */
g_cancellable_cancel (m->cancellable);
if (do_close)
update_monitor_do_close (monitor);
}
static GDBusConnection *
update_monitor_get_connection (PortalFlatpakUpdateMonitor *monitor)
{
return g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (monitor));
}
static GHashTable *installation_cache = NULL;
static void
clear_installation_cache (void)
{
if (installation_cache != NULL)
g_hash_table_remove_all (installation_cache);
}
/* Caching lookup of Installation for a path */
static FlatpakInstallation *
lookup_installation_for_path (GFile *path, GError **error)
{
FlatpakInstallation *installation;
if (installation_cache == NULL)
installation_cache = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal, g_object_unref, g_object_unref);
installation = g_hash_table_lookup (installation_cache, path);
if (installation == NULL)
{
g_autoptr(FlatpakDir) dir = NULL;
dir = flatpak_dir_get_by_path (path);
installation = flatpak_installation_new_for_dir (dir, NULL, error);
if (installation == NULL)
return NULL;
flatpak_installation_set_no_interaction (installation, TRUE);
g_hash_table_insert (installation_cache, g_object_ref (path), installation);
}
return g_object_ref (installation);
}
static GFile *
update_monitor_get_installation_path (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) app_path = NULL;
app_path = g_file_new_for_path (m->app_path);
/* The app path is always 6 level deep inside the installation dir,
* like $dir/app/org.the.app/x86_64/stable/$commit/files, so we find
* the installation by just going up 6 parents. */
return g_file_resolve_relative_path (app_path, "../../../../../..");
}
static void
check_for_updates (PortalFlatpakUpdateMonitor *monitor)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GFile) installation_path = NULL;
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakInstalledRef) installed_ref = NULL;
g_autoptr(FlatpakRemoteRef) remote_ref = NULL;
const char *origin = NULL;
const char *local_commit = NULL;
const char *remote_commit;
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
const char *ref;
installation_path = update_monitor_get_installation_path (monitor);
g_debug ("Checking for updates for %s/%s/%s in %s", m->name, m->arch, m->branch, flatpak_file_get_path_cached (installation_path));
installation = lookup_installation_for_path (installation_path, &error);
if (installation == NULL)
{
g_debug ("Unable to find installation for path %s: %s", flatpak_file_get_path_cached (installation_path), error->message);
return;
}
installed_ref = flatpak_installation_get_installed_ref (installation,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (installed_ref == NULL)
{
g_debug ("getting installed ref failed: %s", error->message);
return; /* Never report updates for uninstalled refs */
}
dir = flatpak_installation_get_dir (installation, NULL);
if (dir == NULL)
return;
ref = flatpak_ref_format_ref_cached (FLATPAK_REF (installed_ref));
if (flatpak_dir_ref_is_masked (dir, ref))
return; /* Never report updates for masked refs */
local_commit = flatpak_ref_get_commit (FLATPAK_REF (installed_ref));
origin = flatpak_installed_ref_get_origin (installed_ref);
remote_ref = flatpak_installation_fetch_remote_ref_sync (installation, origin,
FLATPAK_REF_KIND_APP,
m->name, m->arch, m->branch,
m->cancellable, &error);
if (remote_ref == NULL)
{
/* Probably some network issue.
* Fall back to the local_commit to at least be able to pick up already installed updates.
*/
g_debug ("getting remote ref failed: %s", error->message);
g_clear_error (&error);
remote_commit = local_commit;
}
else
{
remote_commit = flatpak_ref_get_commit (FLATPAK_REF (remote_ref));
if (remote_commit == NULL)
{
/* This can happen if we're offline and there is an update from an usb drive.
* Not much we can do in terms of reporting it, but at least handle the case
*/
g_debug ("Unknown remote commit, setting to local_commit");
remote_commit = local_commit;
}
}
if (g_strcmp0 (m->reported_local_commit, local_commit) != 0 ||
g_strcmp0 (m->reported_remote_commit, remote_commit) != 0)
{
GVariantBuilder builder;
gboolean is_closed;
g_free (m->reported_local_commit);
m->reported_local_commit = g_strdup (local_commit);
g_free (m->reported_remote_commit);
m->reported_remote_commit = g_strdup (remote_commit);
g_debug ("Found update for %s/%s/%s, local: %s, remote: %s", m->name, m->arch, m->branch, local_commit, remote_commit);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&builder, "{sv}", "running-commit", g_variant_new_string (m->commit));
g_variant_builder_add (&builder, "{sv}", "local-commit", g_variant_new_string (local_commit));
g_variant_builder_add (&builder, "{sv}", "remote-commit", g_variant_new_string (remote_commit));
/* Maybe someone closed the monitor while we were checking for updates, then drop the signal.
* There is still a minimal race between this check and the emit where a client could call close()
* and still see the signal though. */
g_mutex_lock (&m->lock);
is_closed = m->closed;
g_mutex_unlock (&m->lock);
if (!is_closed &&
!g_dbus_connection_emit_signal (update_monitor_get_connection (monitor),
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"UpdateAvailable",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit UpdateAvailable: %s", error->message);
g_clear_error (&error);
}
}
}
static void
check_all_for_updates_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *monitors, *l;
monitors = update_monitors_get_all (NULL);
for (l = monitors; l != NULL; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
gboolean was_closed = FALSE;
g_mutex_lock (&m->lock);
if (m->closed)
was_closed = TRUE;
else
m->running = TRUE;
g_mutex_unlock (&m->lock);
if (!was_closed)
{
check_for_updates (monitor);
g_mutex_lock (&m->lock);
m->running = FALSE;
if (m->closed) /* Was closed during running, do delayed close */
update_monitor_do_close (monitor);
g_mutex_unlock (&m->lock);
}
}
g_list_free_full (monitors, g_object_unref);
/* We want to cache stuff between multiple monitors
when a poll is scheduled, but there is no need to keep it
long term to the next poll, the in-memory is just
a waste of space then. */
clear_installation_cache ();
G_LOCK (update_monitors);
update_monitors_timeout_running_thread = FALSE;
if (g_hash_table_size (update_monitors) > 0)
update_monitors_timeout = g_timeout_add_seconds (opt_poll_timeout, check_all_for_updates_cb, NULL);
G_UNLOCK (update_monitors);
}
/* Runs on main thread */
static gboolean
check_all_for_updates_cb (void *data)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
if (!opt_poll_when_metered &&
g_network_monitor_get_network_metered (network_monitor))
{
g_debug ("Skipping update check on metered network");
return G_SOURCE_CONTINUE;
}
g_debug ("Checking all update monitors");
G_LOCK (update_monitors);
update_monitors_timeout = 0;
update_monitors_timeout_running_thread = TRUE;
G_UNLOCK (update_monitors);
g_task_run_in_thread (task, check_all_for_updates_in_thread_func);
return G_SOURCE_REMOVE; /* This will be re-added by the thread when done */
}
/* Runs in worker thread */
static gboolean
handle_create_update_monitor (PortalFlatpak *object,
GDBusMethodInvocation *invocation,
GVariant *options)
{
GDBusConnection *connection = g_dbus_method_invocation_get_connection (invocation);
g_autoptr(PortalFlatpakUpdateMonitorSkeleton) monitor = NULL;
const char *sender;
g_autofree char *sender_escaped = NULL;
g_autofree char *obj_path = NULL;
g_autofree char *token = NULL;
g_autoptr(GError) error = NULL;
int i;
if (!g_variant_lookup (options, "handle_token", "s", &token))
token = g_strdup_printf ("%d", g_random_int_range (0, 1000));
sender = g_dbus_method_invocation_get_sender (invocation);
g_debug ("handle CreateUpdateMonitor from %s", sender);
sender_escaped = g_strdup (sender + 1);
for (i = 0; sender_escaped[i]; i++)
{
if (sender_escaped[i] == '.')
sender_escaped[i] = '_';
}
obj_path = g_strdup_printf ("/org/freedesktop/portal/Flatpak/update_monitor/%s/%s",
sender_escaped,
token);
monitor = (PortalFlatpakUpdateMonitorSkeleton *) create_update_monitor (invocation, obj_path, &error);
if (monitor == NULL)
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
g_signal_connect (monitor, "handle-close", G_CALLBACK (handle_close), NULL);
g_signal_connect (monitor, "handle-update", G_CALLBACK (handle_update), NULL);
g_signal_connect (monitor, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (monitor),
connection,
obj_path,
&error))
{
g_dbus_method_invocation_return_gerror (invocation, error);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
register_update_monitor ((PortalFlatpakUpdateMonitor*)monitor, obj_path);
portal_flatpak_complete_create_update_monitor (portal, invocation, obj_path);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
/* Runs in worker thread */
static gboolean
handle_close (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation)
{
update_monitor_close (monitor);
g_debug ("handle UpdateMonitor.Close");
portal_flatpak_update_monitor_complete_close (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
deep_free_object_list (gpointer data)
{
g_list_free_full ((GList *)data, g_object_unref);
}
static void
close_update_monitors_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
GList *list = task_data;
GList *l;
for (l = list; l; l = l->next)
{
PortalFlatpakUpdateMonitor *monitor = l->data;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_debug ("closing monitor %s", m->obj_path);
update_monitor_close (monitor);
}
}
static void
close_update_monitors_for_sender (const char *sender)
{
GList *list = update_monitors_get_all (sender);
if (list)
{
g_autoptr(GTask) task = g_task_new (NULL, NULL, NULL, NULL);
g_task_set_task_data (task, list, deep_free_object_list);
g_debug ("%s dropped off the bus, closing monitors", sender);
g_task_run_in_thread (task, close_update_monitors_in_thread_func);
}
}
static guint32
get_update_permission (const char *app_id)
{
g_autoptr(GVariant) out_perms = NULL;
g_autoptr(GVariant) out_data = NULL;
g_autoptr(GError) error = NULL;
guint32 ret = UNSET;
if (permission_store == NULL)
{
g_debug ("No portals installed, assume no permissions");
return NO;
}
if (!xdp_dbus_permission_store_call_lookup_sync (permission_store,
PERMISSION_TABLE,
PERMISSION_ID,
&out_perms,
&out_data,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_debug ("No updates permissions found: %s", error->message);
g_clear_error (&error);
}
if (out_perms != NULL)
{
const char **perms;
if (g_variant_lookup (out_perms, app_id, "^a&s", &perms))
{
if (strcmp (perms[0], "ask") == 0)
ret = ASK;
else if (strcmp (perms[0], "yes") == 0)
ret = YES;
else
ret = NO;
}
}
g_debug ("Updates permissions for %s: %d", app_id, ret);
return ret;
}
static void
set_update_permission (const char *app_id,
Permission permission)
{
g_autoptr(GError) error = NULL;
const char *permissions[2];
if (permission == ASK)
permissions[0] = "ask";
else if (permission == YES)
permissions[0] = "yes";
else if (permission == NO)
permissions[0] = "no";
else
{
g_warning ("Wrong permission format, ignoring");
return;
}
permissions[1] = NULL;
if (!xdp_dbus_permission_store_call_set_permission_sync (permission_store,
PERMISSION_TABLE,
TRUE,
PERMISSION_ID,
app_id,
(const char * const*)permissions,
NULL,
&error))
{
g_dbus_error_strip_remote_error (error);
g_info ("Error updating permission store: %s", error->message);
}
}
static char *
get_app_display_name (const char *app_id)
{
g_autofree char *id = NULL;
g_autoptr(GDesktopAppInfo) info = NULL;
const char *name = NULL;
id = g_strconcat (app_id, ".desktop", NULL);
info = g_desktop_app_info_new (id);
if (info)
{
name = g_app_info_get_display_name (G_APP_INFO (info));
if (name)
return g_strdup (name);
}
return g_strdup (app_id);
}
static gboolean
request_update_permissions_sync (PortalFlatpakUpdateMonitor *monitor,
const char *app_id,
const char *window,
GError **error)
{
Permission permission;
permission = get_update_permission (app_id);
if (permission == UNSET || permission == ASK)
{
guint access_response = 2;
PortalImplementation *access_impl;
GVariantBuilder access_opt_builder;
g_autofree char *app_name = NULL;
g_autofree char *title = NULL;
g_autoptr(GVariant) ret = NULL;
access_impl = find_portal_implementation ("org.freedesktop.impl.portal.Access");
if (access_impl == NULL)
{
g_warning ("No Access portal implementation found");
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED, _("No portal support found"));
return FALSE;
}
g_variant_builder_init (&access_opt_builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&access_opt_builder, "{sv}",
"deny_label", g_variant_new_string (_("Deny")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"grant_label", g_variant_new_string (_("Update")));
g_variant_builder_add (&access_opt_builder, "{sv}",
"icon", g_variant_new_string ("package-x-generic-symbolic"));
app_name = get_app_display_name (app_id);
title = g_strdup_printf (_("Update %s?"), app_name);
ret = g_dbus_connection_call_sync (update_monitor_get_connection (monitor),
access_impl->dbus_name,
"/org/freedesktop/portal/desktop",
"org.freedesktop.impl.portal.Access",
"AccessDialog",
g_variant_new ("(osssssa{sv})",
"/request/path",
app_id,
window,
title,
_("The application wants to update itself."),
_("Update access can be changed any time from the privacy settings."),
&access_opt_builder),
G_VARIANT_TYPE ("(ua{sv})"),
G_DBUS_CALL_FLAGS_NONE,
G_MAXINT,
NULL,
error);
if (ret == NULL)
{
g_dbus_error_strip_remote_error (*error);
g_warning ("Failed to show access dialog: %s", (*error)->message);
return FALSE;
}
g_variant_get (ret, "(ua{sv})", &access_response, NULL);
if (permission == UNSET)
set_update_permission (app_id, (access_response == 0) ? YES : NO);
permission = (access_response == 0) ? YES : NO;
}
if (permission == NO)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_ACCESS_DENIED,
_("Application update not allowed"));
return FALSE;
}
return TRUE;
}
static void
emit_progress (PortalFlatpakUpdateMonitor *monitor,
int op,
int n_ops,
int progress,
int status,
const char *error_name,
const char *error_message)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
GDBusConnection *connection;
GVariantBuilder builder;
g_autoptr(GError) error = NULL;
g_debug ("%d/%d ops, progress %d, status: %d", op, n_ops, progress, status);
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
if (n_ops > 0)
{
g_variant_builder_add (&builder, "{sv}", "op", g_variant_new_uint32 (op));
g_variant_builder_add (&builder, "{sv}", "n_ops", g_variant_new_uint32 (n_ops));
g_variant_builder_add (&builder, "{sv}", "progress", g_variant_new_uint32 (progress));
}
g_variant_builder_add (&builder, "{sv}", "status", g_variant_new_uint32 (status));
if (error_name)
{
g_variant_builder_add (&builder, "{sv}", "error", g_variant_new_string (error_name));
g_variant_builder_add (&builder, "{sv}", "error_message", g_variant_new_string (error_message));
}
connection = update_monitor_get_connection (monitor);
if (!g_dbus_connection_emit_signal (connection,
m->sender,
m->obj_path,
"org.freedesktop.portal.Flatpak.UpdateMonitor",
"Progress",
g_variant_new ("(a{sv})", &builder),
&error))
{
g_warning ("Failed to emit ::progress: %s", error->message);
}
}
static char *
get_progress_error (const GError *update_error)
{
g_autofree gchar *name = NULL;
name = g_dbus_error_encode_gerror (update_error);
/* Don't return weird dbus wrapped things from the portal */
if (g_str_has_prefix (name, "org.gtk.GDBus.UnmappedGError.Quark"))
return g_strdup ("org.freedesktop.DBus.Error.Failed");
return g_steal_pointer (&name);
}
static void
emit_progress_error (PortalFlatpakUpdateMonitor *monitor,
GError *update_error)
{
g_autofree gchar *error_name = get_progress_error (update_error);
emit_progress (monitor, 0, 0, 0,
PROGRESS_STATUS_ERROR,
error_name, update_error->message);
}
static void
send_variant (GVariant *v, GOutputStream *out)
{
g_autoptr(GError) error = NULL;
const guchar *data;
gsize size;
guint32 size32;
data = g_variant_get_data (v);
size = g_variant_get_size (v);
size32 = size;
if (!g_output_stream_write_all (out, &size32, 4, NULL, NULL, &error) ||
!g_output_stream_write_all (out, data, size, NULL, NULL, &error))
{
g_warning ("sending to parent failed: %s", error->message);
exit (1); // This will exit the child process and cause the parent to report an error
}
}
static void
send_progress (GOutputStream *out,
int op,
int n_ops,
int progress,
int status,
const GError *update_error)
{
g_autoptr(GVariant) v = NULL;
g_autofree gchar *error_name = NULL;
if (update_error)
error_name = get_progress_error (update_error);
v = g_variant_ref_sink (g_variant_new ("(uuuuss)",
op, n_ops, progress, status,
error_name ? error_name : "",
update_error ? update_error->message : ""));
send_variant (v, out);
}
typedef struct {
GOutputStream *out;
int n_ops;
int op;
int progress;
gboolean saw_first_operation;
} TransactionData;
static gboolean
transaction_ready (FlatpakTransaction *transaction,
TransactionData *d)
{
GList *ops = flatpak_transaction_get_operations (transaction);
int status;
GList *l;
d->n_ops = g_list_length (ops);
d->op = 0;
d->progress = 0;
for (l = ops; l != NULL; l = l->next)
{
FlatpakTransactionOperation *op = l->data;
const char *ref = flatpak_transaction_operation_get_ref (op);
FlatpakTransactionOperationType type = flatpak_transaction_operation_get_operation_type (op);
/* Actual app updates need to not increase premission requirements */
if (type == FLATPAK_TRANSACTION_OPERATION_UPDATE && g_str_has_prefix (ref, "app/"))
{
GKeyFile *new_metadata = flatpak_transaction_operation_get_metadata (op);
GKeyFile *old_metadata = flatpak_transaction_operation_get_old_metadata (op);
g_autoptr(FlatpakContext) new_context = flatpak_context_new ();
g_autoptr(FlatpakContext) old_context = flatpak_context_new ();
if (!flatpak_context_load_metadata (new_context, new_metadata, NULL) ||
!flatpak_context_load_metadata (old_context, old_metadata, NULL) ||
flatpak_context_adds_permissions (old_context, new_context))
{
g_autoptr(GError) error = NULL;
g_set_error (&error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
_("Self update not supported, new version requires new permissions"));
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE;
}
}
}
if (flatpak_transaction_is_empty (transaction))
status = PROGRESS_STATUS_EMPTY;
else
status = PROGRESS_STATUS_RUNNING;
send_progress (d->out,
d->op, d->n_ops,
d->progress, status,
NULL);
if (status == PROGRESS_STATUS_EMPTY)
return FALSE; /* This will cause us to return an ABORTED error */
return TRUE;
}
static void
transaction_progress_changed (FlatpakTransactionProgress *progress,
TransactionData *d)
{
/* Only report 100 when really done */
d->progress = MIN (flatpak_transaction_progress_get_progress (progress), 99);
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
transaction_new_operation (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
FlatpakTransactionProgress *progress,
TransactionData *d)
{
d->progress = 0;
if (d->saw_first_operation)
d->op++;
else
d->saw_first_operation = TRUE;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
g_signal_connect (progress, "changed", G_CALLBACK (transaction_progress_changed), d);
}
static gboolean
transaction_operation_error (FlatpakTransaction *transaction,
FlatpakTransactionOperation *operation,
const GError *error,
FlatpakTransactionErrorDetails detail,
TransactionData *d)
{
gboolean non_fatal = (detail & FLATPAK_TRANSACTION_ERROR_DETAILS_NON_FATAL) != 0;
if (non_fatal)
return TRUE; /* Continue */
send_progress (d->out,
d->op, d->n_ops, d->progress,
PROGRESS_STATUS_ERROR,
error);
return FALSE; /* This will cause us to return an ABORTED error */
}
static void
transaction_operation_done (FlatpakTransaction *transaction,
FlatpakTransactionOperation *op,
const char *commit,
FlatpakTransactionResult result,
TransactionData *d)
{
d->progress = 100;
send_progress (d->out,
d->op, d->n_ops,
d->progress, PROGRESS_STATUS_RUNNING,
NULL);
}
static void
update_child_setup_func (gpointer user_data)
{
int *socket = user_data;
dup2 (*socket, 3);
flatpak_close_fds_workaround (4);
}
/* This is the meat of the update process, its run out of process (via
spawn) to avoid running lots of complicated code in the portal
process and possibly long-term leaks in a long-running process. */
static int
do_update_child_process (const char *installation_path, const char *ref, int socket_fd)
{
g_autoptr(GOutputStream) out = g_unix_output_stream_new (socket_fd, TRUE);
g_autoptr(FlatpakInstallation) installation = NULL;
g_autoptr(FlatpakTransaction) transaction = NULL;
g_autoptr(GFile) f = g_file_new_for_path (installation_path);
g_autoptr(GError) error = NULL;
g_autoptr(FlatpakDir) dir = NULL;
TransactionData transaction_data = { NULL };
dir = flatpak_dir_get_by_path (f);
if (!flatpak_dir_maybe_ensure_repo (dir, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
installation = flatpak_installation_new_for_dir (dir, NULL, &error);
if (installation)
transaction = flatpak_transaction_new_for_installation (installation, NULL, &error);
if (transaction == NULL)
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
flatpak_transaction_add_default_dependency_sources (transaction);
if (!flatpak_transaction_add_update (transaction, ref, NULL, NULL, &error))
{
send_progress (out, 0, 0, 0,
PROGRESS_STATUS_ERROR, error);
return 0;
}
transaction_data.out = out;
g_signal_connect (transaction, "ready", G_CALLBACK (transaction_ready), &transaction_data);
g_signal_connect (transaction, "new-operation", G_CALLBACK (transaction_new_operation), &transaction_data);
g_signal_connect (transaction, "operation-done", G_CALLBACK (transaction_operation_done), &transaction_data);
g_signal_connect (transaction, "operation-error", G_CALLBACK (transaction_operation_error), &transaction_data);
if (!flatpak_transaction_run (transaction, NULL, &error))
{
if (!g_error_matches (error, FLATPAK_ERROR, FLATPAK_ERROR_ABORTED)) /* If aborted we already sent error */
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_ERROR, error);
return 0;
}
send_progress (out, transaction_data.op, transaction_data.n_ops, transaction_data.progress,
PROGRESS_STATUS_DONE, error);
return 0;
}
static GVariant *
read_variant (GInputStream *in,
GCancellable *cancellable,
GError **error)
{
guint32 size;
guchar *data;
gsize bytes_read;
if (!g_input_stream_read_all (in, &size, 4, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != 4)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
data = g_try_malloc (size);
if (data == NULL)
{
flatpak_fail (error, "Out of memory");
return NULL;
}
if (!g_input_stream_read_all (in, data, size, &bytes_read, cancellable, error))
return NULL;
if (bytes_read != size)
{
g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
_("Update ended unexpectedly"));
return NULL;
}
return g_variant_ref_sink (g_variant_new_from_data (G_VARIANT_TYPE("(uuuuss)"),
data, size, FALSE, g_free, data));
}
/* We do the actual update out of process (in do_update_child_process,
via spawn) and just proxy the feedback here */
static gboolean
handle_update_responses (PortalFlatpakUpdateMonitor *monitor,
int socket_fd,
GError **error)
{
g_autoptr(GInputStream) in = g_unix_input_stream_new (socket_fd, FALSE); /* Closed by parent */
UpdateMonitorData *m = update_monitor_get_data (monitor);
guint32 status;
do
{
g_autoptr(GVariant) v = NULL;
guint32 op;
guint32 n_ops;
guint32 progress;
const char *error_name;
const char *error_message;
v = read_variant (in, m->cancellable, error);
if (v == NULL)
{
g_debug ("Reading message from child update process failed %s", (*error)->message);
return FALSE;
}
g_variant_get (v, "(uuuu&s&s)",
&op, &n_ops, &progress, &status, &error_name, &error_message);
emit_progress (monitor, op, n_ops, progress, status,
*error_name != 0 ? error_name : NULL,
*error_message != 0 ? error_message : NULL);
}
while (status == PROGRESS_STATUS_RUNNING);
/* Don't return an received error as we emited it already, that would cause it to be emitted twice */
return TRUE;
}
static void
handle_update_in_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
PortalFlatpakUpdateMonitor *monitor = source_object;
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GError) error = NULL;
const char *window;
window = (const char *)g_object_get_data (G_OBJECT (task), "window");
if (request_update_permissions_sync (monitor, m->name, window, &error))
{
g_autoptr(GFile) installation_path = update_monitor_get_installation_path (monitor);
g_autofree char *ref = flatpak_build_app_ref (m->name, m->branch, m->arch);
const char *argv[] = { "/proc/self/exe", "flatpak-portal", "--update", flatpak_file_get_path_cached (installation_path), ref, NULL };
int sockets[2];
GPid pid;
if (socketpair (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sockets) != 0)
{
glnx_throw_errno (&error);
}
else
{
gboolean spawn_ok;
spawn_ok = g_spawn_async (NULL, (char **)argv, NULL,
G_SPAWN_FILE_AND_ARGV_ZERO |
G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
update_child_setup_func, &sockets[1],
&pid, &error);
close (sockets[1]); // Close remote side
if (spawn_ok)
{
if (!handle_update_responses (monitor, sockets[0], &error))
{
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
kill (pid, SIGINT);
}
}
close (sockets[0]); // Close local side
}
}
if (error)
emit_progress_error (monitor, error);
g_mutex_lock (&m->lock);
m->installing = FALSE;
g_mutex_unlock (&m->lock);
}
static gboolean
handle_update (PortalFlatpakUpdateMonitor *monitor,
GDBusMethodInvocation *invocation,
const char *arg_window,
GVariant *arg_options)
{
UpdateMonitorData *m = update_monitor_get_data (monitor);
g_autoptr(GTask) task = NULL;
gboolean already_installing = FALSE;
g_debug ("handle UpdateMonitor.Update");
g_mutex_lock (&m->lock);
if (m->installing)
already_installing = TRUE;
else
m->installing = TRUE;
g_mutex_unlock (&m->lock);
if (already_installing)
{
g_dbus_method_invocation_return_error (invocation,
G_DBUS_ERROR,
G_DBUS_ERROR_FAILED,
"Already installing");
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
task = g_task_new (monitor, NULL, NULL, NULL);
g_object_set_data_full (G_OBJECT (task), "window", g_strdup (arg_window), g_free);
g_task_run_in_thread (task, handle_update_in_thread_func);
portal_flatpak_update_monitor_complete_update (monitor, invocation);
return G_DBUS_METHOD_INVOCATION_HANDLED;
}
static void
name_owner_changed (GDBusConnection *connection,
const gchar *sender_name,
const gchar *object_path,
const gchar *interface_name,
const gchar *signal_name,
GVariant *parameters,
gpointer user_data)
{
const char *name, *from, *to;
g_variant_get (parameters, "(&s&s&s)", &name, &from, &to);
if (name[0] == ':' &&
strcmp (name, from) == 0 &&
strcmp (to, "") == 0)
{
GHashTableIter iter;
PidData *pid_data = NULL;
gpointer value = NULL;
GList *list = NULL, *l;
g_hash_table_iter_init (&iter, client_pid_data_hash);
while (g_hash_table_iter_next (&iter, NULL, &value))
{
pid_data = value;
if (pid_data->watch_bus && g_str_equal (pid_data->client, name))
list = g_list_prepend (list, pid_data);
}
for (l = list; l; l = l->next)
{
pid_data = l->data;
g_debug ("%s dropped off the bus, killing %d", pid_data->client, pid_data->pid);
killpg (pid_data->pid, SIGINT);
}
g_list_free (list);
close_update_monitors_for_sender (name);
}
}
#define DBUS_NAME_DBUS "org.freedesktop.DBus"
#define DBUS_INTERFACE_DBUS DBUS_NAME_DBUS
#define DBUS_PATH_DBUS "/org/freedesktop/DBus"
static gboolean
supports_expose_pids (void)
{
const char *path = g_find_program_in_path (flatpak_get_bwrap ());
struct stat st;
/* This is supported only if bwrap exists and is not setuid */
return
path != NULL &&
stat (path, &st) == 0 &&
(st.st_mode & S_ISUID) == 0;
}
static void
on_bus_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
GError *error = NULL;
g_debug ("Bus acquired, creating skeleton");
g_dbus_connection_set_exit_on_close (connection, FALSE);
update_monitors = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
permission_store = xdp_dbus_permission_store_proxy_new_sync (connection,
G_DBUS_PROXY_FLAGS_NONE,
"org.freedesktop.impl.portal.PermissionStore",
"/org/freedesktop/impl/portal/PermissionStore",
NULL, NULL);
portal = portal_flatpak_skeleton_new ();
g_dbus_connection_signal_subscribe (connection,
DBUS_NAME_DBUS,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged",
DBUS_PATH_DBUS,
NULL,
G_DBUS_SIGNAL_FLAGS_NONE,
name_owner_changed,
NULL, NULL);
g_object_set_data_full (G_OBJECT (portal), "track-alive", GINT_TO_POINTER (42), skeleton_died_cb);
g_dbus_interface_skeleton_set_flags (G_DBUS_INTERFACE_SKELETON (portal),
G_DBUS_INTERFACE_SKELETON_FLAGS_HANDLE_METHOD_INVOCATIONS_IN_THREAD);
portal_flatpak_set_version (PORTAL_FLATPAK (portal), 5);
portal_flatpak_set_supports (PORTAL_FLATPAK (portal), supports);
g_signal_connect (portal, "handle-spawn", G_CALLBACK (handle_spawn), NULL);
g_signal_connect (portal, "handle-spawn-signal", G_CALLBACK (handle_spawn_signal), NULL);
g_signal_connect (portal, "handle-create-update-monitor", G_CALLBACK (handle_create_update_monitor), NULL);
g_signal_connect (portal, "g-authorize-method", G_CALLBACK (authorize_method_handler), NULL);
if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (portal),
connection,
"/org/freedesktop/portal/Flatpak",
&error))
{
g_warning ("error: %s", error->message);
g_error_free (error);
}
}
static void
on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name acquired");
}
static void
on_name_lost (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_debug ("Name lost");
unref_skeleton_in_timeout ();
}
static void
binary_file_changed_cb (GFileMonitor *file_monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
gpointer data)
{
static gboolean got_it = FALSE;
if (!got_it)
{
g_debug ("binary file changed");
unref_skeleton_in_timeout ();
}
got_it = TRUE;
}
static void
message_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data)
{
/* Make this look like normal console output */
if (log_level & G_LOG_LEVEL_DEBUG)
g_printerr ("F: %s\n", message);
else
g_printerr ("%s: %s\n", g_get_prgname (), message);
}
int
main (int argc,
char **argv)
{
gchar exe_path[PATH_MAX + 1];
ssize_t exe_path_len;
gboolean replace;
gboolean show_version;
GOptionContext *context;
GBusNameOwnerFlags flags;
g_autoptr(GError) error = NULL;
const GOptionEntry options[] = {
{ "replace", 'r', 0, G_OPTION_ARG_NONE, &replace, "Replace old daemon.", NULL },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &opt_verbose, "Enable debug output.", NULL },
{ "version", 0, 0, G_OPTION_ARG_NONE, &show_version, "Show program version.", NULL},
{ "no-idle-exit", 0, 0, G_OPTION_ARG_NONE, &no_idle_exit, "Don't exit when idle.", NULL },
{ "poll-timeout", 0, 0, G_OPTION_ARG_INT, &opt_poll_timeout, "Delay in seconds between polls for updates.", NULL },
{ "poll-when-metered", 0, 0, G_OPTION_ARG_NONE, &opt_poll_when_metered, "Whether to check for updates on metered networks", NULL },
{ NULL }
};
setlocale (LC_ALL, "");
g_setenv ("GIO_USE_VFS", "local", TRUE);
g_set_prgname (argv[0]);
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, message_handler, NULL);
if (argc >= 4 && strcmp (argv[1], "--update") == 0)
{
return do_update_child_process (argv[2], argv[3], 3);
}
context = g_option_context_new ("");
replace = FALSE;
opt_verbose = FALSE;
show_version = FALSE;
g_option_context_set_summary (context, "Flatpak portal");
g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
if (!g_option_context_parse (context, &argc, &argv, &error))
{
g_printerr ("%s: %s", g_get_application_name (), error->message);
g_printerr ("\n");
g_printerr ("Try \"%s --help\" for more information.",
g_get_prgname ());
g_printerr ("\n");
g_option_context_free (context);
return 1;
}
if (opt_poll_timeout == 0)
opt_poll_timeout = DEFAULT_UPDATE_POLL_TIMEOUT_SEC;
if (show_version)
{
g_print (PACKAGE_STRING "\n");
return 0;
}
if (opt_verbose)
g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, message_handler, NULL);
client_pid_data_hash = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) pid_data_free);
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
if (session_bus == NULL)
{
g_printerr ("Can't find bus: %s\n", error->message);
return 1;
}
exe_path_len = readlink ("/proc/self/exe", exe_path, sizeof (exe_path) - 1);
if (exe_path_len > 0 && (size_t) exe_path_len < sizeof (exe_path))
{
exe_path[exe_path_len] = 0;
GFileMonitor *monitor;
g_autoptr(GFile) exe = NULL;
g_autoptr(GError) local_error = NULL;
exe = g_file_new_for_path (exe_path);
monitor = g_file_monitor_file (exe,
G_FILE_MONITOR_NONE,
NULL,
&local_error);
if (monitor == NULL)
g_warning ("Failed to set watch on %s: %s", exe_path, error->message);
else
g_signal_connect (monitor, "changed",
G_CALLBACK (binary_file_changed_cb), NULL);
}
flatpak_connection_track_name_owners (session_bus);
if (supports_expose_pids ())
supports |= FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS;
flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
if (replace)
flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
"org.freedesktop.portal.Flatpak",
flags,
on_bus_acquired,
on_name_acquired,
on_name_lost,
NULL,
NULL);
load_installed_portals (opt_verbose);
/* Ensure we don't idle exit */
schedule_idle_callback ();
network_monitor = g_network_monitor_get_default ();
main_loop = g_main_loop_new (NULL, FALSE);
g_main_loop_run (main_loop);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1909_0 |
crossvul-cpp_data_good_4069_7 | /**
* @file
* Send email to an SMTP server
*
* @authors
* Copyright (C) 2002 Michael R. Elkins <me@mutt.org>
* Copyright (C) 2005-2009 Brendan Cully <brendan@kublai.com>
* Copyright (C) 2019 Pietro Cerutti <gahr@gahr.ch>
*
* @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 smtp Send email to an SMTP server
*
* Send email to an SMTP server
*/
/* This file contains code for direct SMTP delivery of email messages. */
#include "config.h"
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "mutt/lib.h"
#include "address/lib.h"
#include "email/lib.h"
#include "conn/lib.h"
#include "smtp.h"
#include "globals.h"
#include "init.h"
#include "mutt_account.h"
#include "mutt_socket.h"
#include "progress.h"
#include "sendlib.h"
#ifdef USE_SSL
#include "config/lib.h"
#endif
#ifdef USE_SASL
#include <sasl/sasl.h>
#include <sasl/saslutil.h>
#include "options.h"
#endif
/* These Config Variables are only used in smtp.c */
struct Slist *C_SmtpAuthenticators; ///< Config: (smtp) List of allowed authentication methods
char *C_SmtpOauthRefreshCommand; ///< Config: (smtp) External command to generate OAUTH refresh token
char *C_SmtpPass; ///< Config: (smtp) Password for the SMTP server
char *C_SmtpUser; ///< Config: (smtp) Username for the SMTP server
#define smtp_success(x) ((x) / 100 == 2)
#define SMTP_READY 334
#define SMTP_CONTINUE 354
#define SMTP_ERR_READ -2
#define SMTP_ERR_WRITE -3
#define SMTP_ERR_CODE -4
#define SMTP_PORT 25
#define SMTPS_PORT 465
#define SMTP_AUTH_SUCCESS 0
#define SMTP_AUTH_UNAVAIL 1
#define SMTP_AUTH_FAIL -1
// clang-format off
/**
* typedef SmtpCapFlags - SMTP server capabilities
*/
typedef uint8_t SmtpCapFlags; ///< Flags, e.g. #SMTP_CAP_STARTTLS
#define SMTP_CAP_NO_FLAGS 0 ///< No flags are set
#define SMTP_CAP_STARTTLS (1 << 0) ///< Server supports STARTTLS command
#define SMTP_CAP_AUTH (1 << 1) ///< Server supports AUTH command
#define SMTP_CAP_DSN (1 << 2) ///< Server supports Delivery Status Notification
#define SMTP_CAP_EIGHTBITMIME (1 << 3) ///< Server supports 8-bit MIME content
#define SMTP_CAP_SMTPUTF8 (1 << 4) ///< Server accepts UTF-8 strings
#define SMTP_CAP_ALL ((1 << 5) - 1)
// clang-format on
static char *AuthMechs = NULL;
static SmtpCapFlags Capabilities;
/**
* valid_smtp_code - Is the is a valid SMTP return code?
* @param[in] buf String to check
* @param[in] buflen Length of string
* @param[out] n Numeric value of code
* @retval true Valid number
*/
static bool valid_smtp_code(char *buf, size_t buflen, int *n)
{
char code[4];
if (buflen < 4)
return false;
code[0] = buf[0];
code[1] = buf[1];
code[2] = buf[2];
code[3] = '\0';
if (mutt_str_atoi(code, n) < 0)
return false;
return true;
}
/**
* smtp_get_resp - Read a command response from the SMTP server
* @param conn SMTP connection
* @retval 0 Success (2xx code) or continue (354 code)
* @retval -1 Write error, or any other response code
*/
static int smtp_get_resp(struct Connection *conn)
{
int n;
char buf[1024];
do
{
n = mutt_socket_readln(buf, sizeof(buf), conn);
if (n < 4)
{
/* read error, or no response code */
return SMTP_ERR_READ;
}
const char *s = buf + 4; /* Skip the response code and the space/dash */
size_t plen;
if (mutt_str_startswith(s, "8BITMIME", CASE_IGNORE))
Capabilities |= SMTP_CAP_EIGHTBITMIME;
else if ((plen = mutt_str_startswith(s, "AUTH ", CASE_IGNORE)))
{
Capabilities |= SMTP_CAP_AUTH;
FREE(&AuthMechs);
AuthMechs = mutt_str_strdup(s + plen);
}
else if (mutt_str_startswith(s, "DSN", CASE_IGNORE))
Capabilities |= SMTP_CAP_DSN;
else if (mutt_str_startswith(s, "STARTTLS", CASE_IGNORE))
Capabilities |= SMTP_CAP_STARTTLS;
else if (mutt_str_startswith(s, "SMTPUTF8", CASE_IGNORE))
Capabilities |= SMTP_CAP_SMTPUTF8;
if (!valid_smtp_code(buf, n, &n))
return SMTP_ERR_CODE;
} while (buf[3] == '-');
if (smtp_success(n) || (n == SMTP_CONTINUE))
return 0;
mutt_error(_("SMTP session failed: %s"), buf);
return -1;
}
/**
* smtp_rcpt_to - Set the recipient to an Address
* @param conn Server Connection
* @param al AddressList to use
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_ERR_WRITE
*/
static int smtp_rcpt_to(struct Connection *conn, const struct AddressList *al)
{
if (!al)
return 0;
struct Address *a = NULL;
TAILQ_FOREACH(a, al, entries)
{
/* weed out group mailboxes, since those are for display only */
if (!a->mailbox || a->group)
{
continue;
}
char buf[1024];
if ((Capabilities & SMTP_CAP_DSN) && C_DsnNotify)
snprintf(buf, sizeof(buf), "RCPT TO:<%s> NOTIFY=%s\r\n", a->mailbox, C_DsnNotify);
else
snprintf(buf, sizeof(buf), "RCPT TO:<%s>\r\n", a->mailbox);
if (mutt_socket_send(conn, buf) == -1)
return SMTP_ERR_WRITE;
int rc = smtp_get_resp(conn);
if (rc != 0)
return rc;
}
return 0;
}
/**
* smtp_data - Send data to an SMTP server
* @param conn SMTP Connection
* @param msgfile Filename containing data
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_ERR_WRITE
*/
static int smtp_data(struct Connection *conn, const char *msgfile)
{
char buf[1024];
struct Progress progress;
struct stat st;
int rc, term = 0;
size_t buflen = 0;
FILE *fp = fopen(msgfile, "r");
if (!fp)
{
mutt_error(_("SMTP session failed: unable to open %s"), msgfile);
return -1;
}
stat(msgfile, &st);
unlink(msgfile);
mutt_progress_init(&progress, _("Sending message..."), MUTT_PROGRESS_NET, st.st_size);
snprintf(buf, sizeof(buf), "DATA\r\n");
if (mutt_socket_send(conn, buf) == -1)
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
rc = smtp_get_resp(conn);
if (rc != 0)
{
mutt_file_fclose(&fp);
return rc;
}
while (fgets(buf, sizeof(buf) - 1, fp))
{
buflen = mutt_str_strlen(buf);
term = buflen && buf[buflen - 1] == '\n';
if (term && ((buflen == 1) || (buf[buflen - 2] != '\r')))
snprintf(buf + buflen - 1, sizeof(buf) - buflen + 1, "\r\n");
if (buf[0] == '.')
{
if (mutt_socket_send_d(conn, ".", MUTT_SOCK_LOG_FULL) == -1)
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
}
if (mutt_socket_send_d(conn, buf, MUTT_SOCK_LOG_FULL) == -1)
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
mutt_progress_update(&progress, ftell(fp), -1);
}
if (!term && buflen && (mutt_socket_send_d(conn, "\r\n", MUTT_SOCK_LOG_FULL) == -1))
{
mutt_file_fclose(&fp);
return SMTP_ERR_WRITE;
}
mutt_file_fclose(&fp);
/* terminate the message body */
if (mutt_socket_send(conn, ".\r\n") == -1)
return SMTP_ERR_WRITE;
rc = smtp_get_resp(conn);
if (rc != 0)
return rc;
return 0;
}
/**
* address_uses_unicode - Do any addresses use Unicode
* @param a Address list to check
* @retval true if any of the string of addresses use 8-bit characters
*/
static bool address_uses_unicode(const char *a)
{
if (!a)
return false;
while (*a)
{
if ((unsigned char) *a & (1 << 7))
return true;
a++;
}
return false;
}
/**
* addresses_use_unicode - Do any of a list of addresses use Unicode
* @param al Address list to check
* @retval true if any use 8-bit characters
*/
static bool addresses_use_unicode(const struct AddressList *al)
{
if (!al)
{
return false;
}
struct Address *a = NULL;
TAILQ_FOREACH(a, al, entries)
{
if (a->mailbox && !a->group && address_uses_unicode(a->mailbox))
return true;
}
return false;
}
/**
* smtp_get_field - Get connection login credentials - Implements ConnAccount::get_field()
*/
static const char *smtp_get_field(enum ConnAccountField field)
{
switch (field)
{
case MUTT_CA_LOGIN:
case MUTT_CA_USER:
return C_SmtpUser;
case MUTT_CA_PASS:
return C_SmtpPass;
case MUTT_CA_OAUTH_CMD:
return C_SmtpOauthRefreshCommand;
case MUTT_CA_HOST:
default:
return NULL;
}
}
/**
* smtp_fill_account - Create ConnAccount object from SMTP Url
* @param cac ConnAccount to populate
* @retval 0 Success
* @retval -1 Error
*/
static int smtp_fill_account(struct ConnAccount *cac)
{
cac->flags = 0;
cac->port = 0;
cac->type = MUTT_ACCT_TYPE_SMTP;
cac->service = "smtp";
cac->get_field = smtp_get_field;
struct Url *url = url_parse(C_SmtpUrl);
if (!url || ((url->scheme != U_SMTP) && (url->scheme != U_SMTPS)) ||
!url->host || (mutt_account_fromurl(cac, url) < 0))
{
url_free(&url);
mutt_error(_("Invalid SMTP URL: %s"), C_SmtpUrl);
return -1;
}
if (url->scheme == U_SMTPS)
cac->flags |= MUTT_ACCT_SSL;
if (cac->port == 0)
{
if (cac->flags & MUTT_ACCT_SSL)
cac->port = SMTPS_PORT;
else
{
static unsigned short SmtpPort = 0;
if (SmtpPort == 0)
{
struct servent *service = getservbyname("smtp", "tcp");
if (service)
SmtpPort = ntohs(service->s_port);
else
SmtpPort = SMTP_PORT;
mutt_debug(LL_DEBUG3, "Using default SMTP port %d\n", SmtpPort);
}
cac->port = SmtpPort;
}
}
url_free(&url);
return 0;
}
/**
* smtp_helo - Say hello to an SMTP Server
* @param conn SMTP Connection
* @param esmtp If true, use ESMTP
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_ERR_WRITE
*/
static int smtp_helo(struct Connection *conn, bool esmtp)
{
Capabilities = 0;
if (!esmtp)
{
/* if TLS or AUTH are requested, use EHLO */
if (conn->account.flags & MUTT_ACCT_USER)
esmtp = true;
#ifdef USE_SSL
if (C_SslForceTls || (C_SslStarttls != MUTT_NO))
esmtp = true;
#endif
}
const char *fqdn = mutt_fqdn(false);
if (!fqdn)
fqdn = NONULL(ShortHostname);
char buf[1024];
snprintf(buf, sizeof(buf), "%s %s\r\n", esmtp ? "EHLO" : "HELO", fqdn);
/* XXX there should probably be a wrapper in mutt_socket.c that
* repeatedly calls conn->write until all data is sent. This
* currently doesn't check for a short write. */
if (mutt_socket_send(conn, buf) == -1)
return SMTP_ERR_WRITE;
return smtp_get_resp(conn);
}
#ifdef USE_SASL
/**
* smtp_auth_sasl - Authenticate using SASL
* @param conn SMTP Connection
* @param mechlist List of mechanisms to use
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_AUTH_FAIL
*/
static int smtp_auth_sasl(struct Connection *conn, const char *mechlist)
{
sasl_conn_t *saslconn = NULL;
sasl_interact_t *interaction = NULL;
const char *mech = NULL;
const char *data = NULL;
unsigned int len;
char *buf = NULL;
size_t bufsize = 0;
int rc, saslrc;
if (mutt_sasl_client_new(conn, &saslconn) < 0)
return SMTP_AUTH_FAIL;
do
{
rc = sasl_client_start(saslconn, mechlist, &interaction, &data, &len, &mech);
if (rc == SASL_INTERACT)
mutt_sasl_interact(interaction);
} while (rc == SASL_INTERACT);
if ((rc != SASL_OK) && (rc != SASL_CONTINUE))
{
mutt_debug(LL_DEBUG2, "%s unavailable\n", mech);
sasl_dispose(&saslconn);
return SMTP_AUTH_UNAVAIL;
}
if (!OptNoCurses)
mutt_message(_("Authenticating (%s)..."), mech);
bufsize = MAX((len * 2), 1024);
buf = mutt_mem_malloc(bufsize);
snprintf(buf, bufsize, "AUTH %s", mech);
if (len)
{
mutt_str_strcat(buf, bufsize, " ");
if (sasl_encode64(data, len, buf + mutt_str_strlen(buf),
bufsize - mutt_str_strlen(buf), &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "#1 error base64-encoding client response\n");
goto fail;
}
}
mutt_str_strcat(buf, bufsize, "\r\n");
do
{
if (mutt_socket_send(conn, buf) < 0)
goto fail;
rc = mutt_socket_readln_d(buf, bufsize, conn, MUTT_SOCK_LOG_FULL);
if (rc < 0)
goto fail;
if (!valid_smtp_code(buf, rc, &rc))
goto fail;
if (rc != SMTP_READY)
break;
if (sasl_decode64(buf + 4, strlen(buf + 4), buf, bufsize - 1, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "error base64-decoding server response\n");
goto fail;
}
do
{
saslrc = sasl_client_step(saslconn, buf, len, &interaction, &data, &len);
if (saslrc == SASL_INTERACT)
mutt_sasl_interact(interaction);
} while (saslrc == SASL_INTERACT);
if (len)
{
if ((len * 2) > bufsize)
{
bufsize = len * 2;
mutt_mem_realloc(&buf, bufsize);
}
if (sasl_encode64(data, len, buf, bufsize, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "#2 error base64-encoding client response\n");
goto fail;
}
}
mutt_str_strfcpy(buf + len, "\r\n", bufsize - len);
} while (rc == SMTP_READY && saslrc != SASL_FAIL);
if (smtp_success(rc))
{
mutt_sasl_setup_conn(conn, saslconn);
FREE(&buf);
return SMTP_AUTH_SUCCESS;
}
fail:
sasl_dispose(&saslconn);
FREE(&buf);
return SMTP_AUTH_FAIL;
}
#endif
/**
* smtp_auth_oauth - Authenticate an SMTP connection using OAUTHBEARER
* @param conn Connection info
* @retval num Result, e.g. #SMTP_AUTH_SUCCESS
*/
static int smtp_auth_oauth(struct Connection *conn)
{
mutt_message(_("Authenticating (OAUTHBEARER)..."));
/* We get the access token from the smtp_oauth_refresh_command */
char *oauthbearer = mutt_account_getoauthbearer(&conn->account);
if (!oauthbearer)
return SMTP_AUTH_FAIL;
size_t ilen = strlen(oauthbearer) + 30;
char *ibuf = mutt_mem_malloc(ilen);
snprintf(ibuf, ilen, "AUTH OAUTHBEARER %s\r\n", oauthbearer);
int rc = mutt_socket_send(conn, ibuf);
FREE(&oauthbearer);
FREE(&ibuf);
if (rc == -1)
return SMTP_AUTH_FAIL;
if (smtp_get_resp(conn) != 0)
return SMTP_AUTH_FAIL;
return SMTP_AUTH_SUCCESS;
}
/**
* smtp_auth_plain - Authenticate using plain text
* @param conn SMTP Connection
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_AUTH_FAIL
*/
static int smtp_auth_plain(struct Connection *conn)
{
char buf[1024];
/* Get username and password. Bail out of any can't be retrieved. */
if ((mutt_account_getuser(&conn->account) < 0) ||
(mutt_account_getpass(&conn->account) < 0))
{
goto error;
}
/* Build the initial client response. */
size_t len = mutt_sasl_plain_msg(buf, sizeof(buf), "AUTH PLAIN", conn->account.user,
conn->account.user, conn->account.pass);
/* Terminate as per SMTP protocol. Bail out if there's no room left. */
if (snprintf(buf + len, sizeof(buf) - len, "\r\n") != 2)
{
goto error;
}
/* Send request, receive response (with a check for OK code). */
if ((mutt_socket_send(conn, buf) < 0) || smtp_get_resp(conn))
{
goto error;
}
/* If we got here, auth was successful. */
return 0;
error:
mutt_error(_("SASL authentication failed"));
return -1;
}
/**
* smtp_auth - Authenticate to an SMTP server
* @param conn SMTP Connection
* @retval 0 Success
* @retval <0 Error, e.g. #SMTP_AUTH_FAIL
*/
static int smtp_auth(struct Connection *conn)
{
int r = SMTP_AUTH_UNAVAIL;
if (C_SmtpAuthenticators)
{
struct ListNode *np = NULL;
STAILQ_FOREACH(np, &C_SmtpAuthenticators->head, entries)
{
mutt_debug(LL_DEBUG2, "Trying method %s\n", np->data);
if (strcmp(np->data, "oauthbearer") == 0)
{
r = smtp_auth_oauth(conn);
}
else if (strcmp(np->data, "plain") == 0)
{
r = smtp_auth_plain(conn);
}
else
{
#ifdef USE_SASL
r = smtp_auth_sasl(conn, np->data);
#else
mutt_error(_("SMTP authentication method %s requires SASL"), np->data);
continue;
#endif
}
if ((r == SMTP_AUTH_FAIL) && (C_SmtpAuthenticators->count > 1))
{
mutt_error(_("%s authentication failed, trying next method"), np->data);
}
else if (r != SMTP_AUTH_UNAVAIL)
break;
}
}
else
{
#ifdef USE_SASL
r = smtp_auth_sasl(conn, AuthMechs);
#else
mutt_error(_("SMTP authentication requires SASL"));
r = SMTP_AUTH_UNAVAIL;
#endif
}
if (r != SMTP_AUTH_SUCCESS)
mutt_account_unsetpass(&conn->account);
if (r == SMTP_AUTH_FAIL)
{
mutt_error(_("SASL authentication failed"));
}
else if (r == SMTP_AUTH_UNAVAIL)
{
mutt_error(_("No authenticators available"));
}
return (r == SMTP_AUTH_SUCCESS) ? 0 : -1;
}
/**
* smtp_open - Open an SMTP Connection
* @param conn SMTP Connection
* @param esmtp If true, use ESMTP
* @retval 0 Success
* @retval -1 Error
*/
static int smtp_open(struct Connection *conn, bool esmtp)
{
int rc;
if (mutt_socket_open(conn))
return -1;
/* get greeting string */
rc = smtp_get_resp(conn);
if (rc != 0)
return rc;
rc = smtp_helo(conn, esmtp);
if (rc != 0)
return rc;
#ifdef USE_SSL
enum QuadOption ans = MUTT_NO;
if (conn->ssf)
ans = MUTT_NO;
else if (C_SslForceTls)
ans = MUTT_YES;
else if ((Capabilities & SMTP_CAP_STARTTLS) &&
((ans = query_quadoption(C_SslStarttls,
_("Secure connection with TLS?"))) == MUTT_ABORT))
{
return -1;
}
if (ans == MUTT_YES)
{
if (mutt_socket_send(conn, "STARTTLS\r\n") < 0)
return SMTP_ERR_WRITE;
rc = smtp_get_resp(conn);
// Clear any data after the STARTTLS acknowledgement
mutt_socket_empty(conn);
if (rc != 0)
return rc;
if (mutt_ssl_starttls(conn))
{
mutt_error(_("Could not negotiate TLS connection"));
return -1;
}
/* re-EHLO to get authentication mechanisms */
rc = smtp_helo(conn, esmtp);
if (rc != 0)
return rc;
}
#endif
if (conn->account.flags & MUTT_ACCT_USER)
{
if (!(Capabilities & SMTP_CAP_AUTH))
{
mutt_error(_("SMTP server does not support authentication"));
return -1;
}
return smtp_auth(conn);
}
return 0;
}
/**
* mutt_smtp_send - Send a message using SMTP
* @param from From Address
* @param to To Address
* @param cc Cc Address
* @param bcc Bcc Address
* @param msgfile Message to send to the server
* @param eightbit If true, try for an 8-bit friendly connection
* @retval 0 Success
* @retval -1 Error
*/
int mutt_smtp_send(const struct AddressList *from, const struct AddressList *to,
const struct AddressList *cc, const struct AddressList *bcc,
const char *msgfile, bool eightbit)
{
struct Connection *conn = NULL;
struct ConnAccount cac = { { 0 } };
const char *envfrom = NULL;
char buf[1024];
int rc = -1;
/* it might be better to synthesize an envelope from from user and host
* but this condition is most likely arrived at accidentally */
if (C_EnvelopeFromAddress)
envfrom = C_EnvelopeFromAddress->mailbox;
else if (from && !TAILQ_EMPTY(from))
envfrom = TAILQ_FIRST(from)->mailbox;
else
{
mutt_error(_("No from address given"));
return -1;
}
if (smtp_fill_account(&cac) < 0)
return rc;
conn = mutt_conn_find(&cac);
if (!conn)
return -1;
do
{
/* send our greeting */
rc = smtp_open(conn, eightbit);
if (rc != 0)
break;
FREE(&AuthMechs);
/* send the sender's address */
int len = snprintf(buf, sizeof(buf), "MAIL FROM:<%s>", envfrom);
if (eightbit && (Capabilities & SMTP_CAP_EIGHTBITMIME))
{
mutt_str_strncat(buf, sizeof(buf), " BODY=8BITMIME", 15);
len += 14;
}
if (C_DsnReturn && (Capabilities & SMTP_CAP_DSN))
len += snprintf(buf + len, sizeof(buf) - len, " RET=%s", C_DsnReturn);
if ((Capabilities & SMTP_CAP_SMTPUTF8) &&
(address_uses_unicode(envfrom) || addresses_use_unicode(to) ||
addresses_use_unicode(cc) || addresses_use_unicode(bcc)))
{
snprintf(buf + len, sizeof(buf) - len, " SMTPUTF8");
}
mutt_str_strncat(buf, sizeof(buf), "\r\n", 3);
if (mutt_socket_send(conn, buf) == -1)
{
rc = SMTP_ERR_WRITE;
break;
}
rc = smtp_get_resp(conn);
if (rc != 0)
break;
/* send the recipient list */
if ((rc = smtp_rcpt_to(conn, to)) || (rc = smtp_rcpt_to(conn, cc)) ||
(rc = smtp_rcpt_to(conn, bcc)))
{
break;
}
/* send the message data */
rc = smtp_data(conn, msgfile);
if (rc != 0)
break;
mutt_socket_send(conn, "QUIT\r\n");
rc = 0;
} while (false);
mutt_socket_close(conn);
FREE(&conn);
if (rc == SMTP_ERR_READ)
mutt_error(_("SMTP session failed: read error"));
else if (rc == SMTP_ERR_WRITE)
mutt_error(_("SMTP session failed: write error"));
else if (rc == SMTP_ERR_CODE)
mutt_error(_("Invalid server response"));
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_4069_7 |
crossvul-cpp_data_bad_5255_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
| Andrei Zmievski <andrei@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef PHP_WIN32
# include "win32/winutil.h"
# include "win32/time.h"
#else
# include <sys/time.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include "php_ini.h"
#include "SAPI.h"
#include "rfc1867.h"
#include "php_variables.h"
#include "php_session.h"
#include "ext/standard/md5.h"
#include "ext/standard/sha1.h"
#include "ext/standard/php_var.h"
#include "ext/date/php_date.h"
#include "ext/standard/php_lcg.h"
#include "ext/standard/url_scanner_ex.h"
#include "ext/standard/php_rand.h" /* for RAND_MAX */
#include "ext/standard/info.h"
#include "ext/standard/php_smart_str.h"
#include "ext/standard/url.h"
#include "ext/standard/basic_functions.h"
#include "mod_files.h"
#include "mod_user.h"
#ifdef HAVE_LIBMM
#include "mod_mm.h"
#endif
PHPAPI ZEND_DECLARE_MODULE_GLOBALS(ps)
static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra TSRMLS_DC);
static int (*php_session_rfc1867_orig_callback)(unsigned int event, void *event_data, void **extra TSRMLS_DC);
/* SessionHandler class */
zend_class_entry *php_session_class_entry;
/* SessionHandlerInterface */
zend_class_entry *php_session_iface_entry;
/* SessionIdInterface */
zend_class_entry *php_session_id_iface_entry;
/* ***********
* Helpers *
*********** */
#define IF_SESSION_VARS() \
if (PS(http_session_vars) && PS(http_session_vars)->type == IS_ARRAY)
#define SESSION_CHECK_ACTIVE_STATE \
if (PS(session_status) == php_session_active) { \
php_error_docref(NULL TSRMLS_CC, E_WARNING, "A session is active. You cannot change the session module's ini settings at this time"); \
return FAILURE; \
}
static void php_session_send_cookie(TSRMLS_D);
/* Dispatched by RINIT and by php_session_destroy */
static inline void php_rinit_session_globals(TSRMLS_D) /* {{{ */
{
PS(id) = NULL;
PS(session_status) = php_session_none;
PS(mod_data) = NULL;
PS(mod_user_is_open) = 0;
/* Do NOT init PS(mod_user_names) here! */
PS(http_session_vars) = NULL;
}
/* }}} */
/* Dispatched by RSHUTDOWN and by php_session_destroy */
static inline void php_rshutdown_session_globals(TSRMLS_D) /* {{{ */
{
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
PS(http_session_vars) = NULL;
}
/* Do NOT destroy PS(mod_user_names) here! */
if (PS(mod_data) || PS(mod_user_implemented)) {
zend_try {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
} zend_end_try();
}
if (PS(id)) {
efree(PS(id));
PS(id) = NULL;
}
}
/* }}} */
static int php_session_destroy(TSRMLS_D) /* {{{ */
{
int retval = SUCCESS;
if (PS(session_status) != php_session_active) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to destroy uninitialized session");
return FAILURE;
}
if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
retval = FAILURE;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
}
php_rshutdown_session_globals(TSRMLS_C);
php_rinit_session_globals(TSRMLS_C);
return retval;
}
/* }}} */
PHPAPI void php_add_session_var(char *name, size_t namelen TSRMLS_DC) /* {{{ */
{
zval **sym_track = NULL;
IF_SESSION_VARS() {
zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void *) &sym_track);
} else {
return;
}
if (sym_track == NULL) {
zval *empty_var;
ALLOC_INIT_ZVAL(empty_var);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), name, namelen+1, empty_var, 1, 0);
}
}
/* }}} */
PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */
{
IF_SESSION_VARS() {
zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars)));
}
}
/* }}} */
PHPAPI int php_get_session_var(char *name, size_t namelen, zval ***state_var TSRMLS_DC) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
ret = zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void **) state_var);
}
return ret;
}
/* }}} */
static void php_session_track_init(TSRMLS_D) /* {{{ */
{
zval *session_vars = NULL;
/* Unconditionally destroy existing array -- possible dirty data */
zend_delete_global_variable("_SESSION", sizeof("_SESSION")-1 TSRMLS_CC);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
MAKE_STD_ZVAL(session_vars);
array_init(session_vars);
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), 2, 1);
}
/* }}} */
static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */
{
char *ret = NULL;
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
ret = NULL;
} else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) {
ret = NULL;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session");
}
return ret;
}
/* }}} */
static int php_session_decode(const char *val, int vallen TSRMLS_DC) /* {{{ */
{
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
return FAILURE;
}
if (PS(serializer)->decode(val, vallen TSRMLS_CC) == FAILURE) {
php_session_destroy(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to decode session object. Session has been destroyed");
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/*
* Note that we cannot use the BASE64 alphabet here, because
* it contains "/" and "+": both are unacceptable for simple inclusion
* into URLs.
*/
static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
enum {
PS_HASH_FUNC_MD5,
PS_HASH_FUNC_SHA1,
PS_HASH_FUNC_OTHER
};
/* returns a pointer to the byte after the last valid character in out */
static char *bin_to_readable(char *in, size_t inlen, char *out, char nbits) /* {{{ */
{
unsigned char *p, *q;
unsigned short w;
int mask;
int have;
p = (unsigned char *) in;
q = (unsigned char *)in + inlen;
w = 0;
have = 0;
mask = (1 << nbits) - 1;
while (1) {
if (have < nbits) {
if (p < q) {
w |= *p++ << have;
have += 8;
} else {
/* consumed everything? */
if (have == 0) break;
/* No? We need a final round */
have = nbits;
}
}
/* consume nbits */
*out++ = hexconvtab[w & mask];
w >>= nbits;
have -= nbits;
}
*out = '\0';
return out;
}
/* }}} */
PHPAPI char *php_session_create_id(PS_CREATE_SID_ARGS) /* {{{ */
{
PHP_MD5_CTX md5_context;
PHP_SHA1_CTX sha1_context;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
void *hash_context = NULL;
#endif
unsigned char *digest;
int digest_len;
int j;
char *buf, *outid;
struct timeval tv;
zval **array;
zval **token;
char *remote_addr = NULL;
gettimeofday(&tv, NULL);
if (zend_hash_find(&EG(symbol_table), "_SERVER", sizeof("_SERVER"), (void **) &array) == SUCCESS &&
Z_TYPE_PP(array) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(array), "REMOTE_ADDR", sizeof("REMOTE_ADDR"), (void **) &token) == SUCCESS &&
Z_TYPE_PP(token) == IS_STRING
) {
remote_addr = Z_STRVAL_PP(token);
}
/* maximum 15+19+19+10 bytes */
spprintf(&buf, 0, "%.15s%ld%ld%0.8F", remote_addr ? remote_addr : "", tv.tv_sec, (long int)tv.tv_usec, php_combined_lcg(TSRMLS_C) * 10);
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Init(&md5_context);
PHP_MD5Update(&md5_context, (unsigned char *) buf, strlen(buf));
digest_len = 16;
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Init(&sha1_context);
PHP_SHA1Update(&sha1_context, (unsigned char *) buf, strlen(buf));
digest_len = 20;
break;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
if (!PS(hash_ops)) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Invalid session hash function");
efree(buf);
return NULL;
}
hash_context = emalloc(PS(hash_ops)->context_size);
PS(hash_ops)->hash_init(hash_context);
PS(hash_ops)->hash_update(hash_context, (unsigned char *) buf, strlen(buf));
digest_len = PS(hash_ops)->digest_size;
break;
#endif /* HAVE_HASH_EXT */
default:
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Invalid session hash function");
efree(buf);
return NULL;
}
efree(buf);
if (PS(entropy_length) > 0) {
#ifdef PHP_WIN32
unsigned char rbuf[2048];
size_t toread = PS(entropy_length);
if (php_win32_get_random_bytes(rbuf, MIN(toread, sizeof(rbuf))) == SUCCESS){
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Update(&md5_context, rbuf, toread);
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Update(&sha1_context, rbuf, toread);
break;
# if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
PS(hash_ops)->hash_update(hash_context, rbuf, toread);
break;
# endif /* HAVE_HASH_EXT */
}
}
#else
int fd;
fd = VCWD_OPEN(PS(entropy_file), O_RDONLY);
if (fd >= 0) {
unsigned char rbuf[2048];
int n;
int to_read = PS(entropy_length);
while (to_read > 0) {
n = read(fd, rbuf, MIN(to_read, sizeof(rbuf)));
if (n <= 0) break;
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Update(&md5_context, rbuf, n);
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Update(&sha1_context, rbuf, n);
break;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
PS(hash_ops)->hash_update(hash_context, rbuf, n);
break;
#endif /* HAVE_HASH_EXT */
}
to_read -= n;
}
close(fd);
}
#endif
}
digest = emalloc(digest_len + 1);
switch (PS(hash_func)) {
case PS_HASH_FUNC_MD5:
PHP_MD5Final(digest, &md5_context);
break;
case PS_HASH_FUNC_SHA1:
PHP_SHA1Final(digest, &sha1_context);
break;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
case PS_HASH_FUNC_OTHER:
PS(hash_ops)->hash_final(digest, hash_context);
efree(hash_context);
break;
#endif /* HAVE_HASH_EXT */
}
if (PS(hash_bits_per_character) < 4
|| PS(hash_bits_per_character) > 6) {
PS(hash_bits_per_character) = 4;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ini setting hash_bits_per_character is out of range (should be 4, 5, or 6) - using 4 for now");
}
outid = emalloc((size_t)((digest_len + 2) * ((8.0f / PS(hash_bits_per_character)) + 0.5)));
j = (int) (bin_to_readable((char *)digest, digest_len, outid, (char)PS(hash_bits_per_character)) - outid);
efree(digest);
if (newlen) {
*newlen = j;
}
return outid;
}
/* }}} */
/* Default session id char validation function allowed by ps_modules.
* If you change the logic here, please also update the error message in
* ps_modules appropriately */
PHPAPI int php_session_valid_key(const char *key) /* {{{ */
{
size_t len;
const char *p;
char c;
int ret = SUCCESS;
for (p = key; (c = *p); p++) {
/* valid characters are a..z,A..Z,0..9 */
if (!((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == ','
|| c == '-')) {
ret = FAILURE;
break;
}
}
len = p - key;
/* Somewhat arbitrary length limit here, but should be way more than
anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
if (len == 0 || len > 128) {
ret = FAILURE;
}
return ret;
}
/* }}} */
static void php_session_initialize(TSRMLS_D) /* {{{ */
{
char *val = NULL;
int vallen;
if (!PS(mod)) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "No storage module chosen - failed to initialize session");
return;
}
/* Open session handler first */
if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name) TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Failed to initialize storage module: %s (path: %s)", PS(mod)->s_name, PS(save_path));
return;
}
/* If there is no ID, use session module to create one */
if (!PS(id)) {
PS(id) = PS(mod)->s_create_sid(&PS(mod_data), NULL TSRMLS_CC);
if (!PS(id)) {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Failed to create session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
return;
}
if (PS(use_cookies)) {
PS(send_cookie) = 1;
}
}
/* Set session ID for compatibility for older/3rd party save handlers */
if (!PS(use_strict_mode)) {
php_session_reset_id(TSRMLS_C);
PS(session_status) = php_session_active;
}
/* Read data */
php_session_track_init(TSRMLS_C);
if (PS(mod)->s_read(&PS(mod_data), PS(id), &val, &vallen TSRMLS_CC) == FAILURE) {
/* Some broken save handler implementation returns FAILURE for non-existent session ID */
/* It's better to raise error for this, but disabled error for better compatibility */
/*
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to read session data: %s (path: %s)", PS(mod)->s_name, PS(save_path));
*/
}
/* Set session ID if session read didn't activated session */
if (PS(use_strict_mode) && PS(session_status) != php_session_active) {
php_session_reset_id(TSRMLS_C);
PS(session_status) = php_session_active;
}
if (val) {
php_session_decode(val, vallen TSRMLS_CC);
str_efree(val);
}
if (!PS(use_cookies) && PS(send_cookie)) {
if (PS(use_trans_sid) && !PS(use_only_cookies)) {
PS(apply_trans_sid) = 1;
}
PS(send_cookie) = 0;
}
}
/* }}} */
static void php_session_save_current_state(TSRMLS_D) /* {{{ */
{
int ret = FAILURE;
IF_SESSION_VARS() {
if (PS(mod_data) || PS(mod_user_implemented)) {
char *val;
int vallen;
val = php_session_encode(&vallen TSRMLS_CC);
if (val) {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), val, vallen TSRMLS_CC);
efree(val);
} else {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), "", 0 TSRMLS_CC);
}
}
if (ret == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to write session data (%s). Please "
"verify that the current setting of session.save_path "
"is correct (%s)",
PS(mod)->s_name,
PS(save_path));
}
}
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
}
}
/* }}} */
/* *************************
* INI Settings/Handlers *
************************* */
static PHP_INI_MH(OnUpdateSaveHandler) /* {{{ */
{
ps_module *tmp;
SESSION_CHECK_ACTIVE_STATE;
tmp = _php_find_ps_module(new_value TSRMLS_CC);
if (PG(modules_activated) && !tmp) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL TSRMLS_CC, err_type, "Cannot find save handler '%s'", new_value);
}
return FAILURE;
}
PS(default_mod) = PS(mod);
PS(mod) = tmp;
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateSerializer) /* {{{ */
{
const ps_serializer *tmp;
SESSION_CHECK_ACTIVE_STATE;
tmp = _php_find_ps_serializer(new_value TSRMLS_CC);
if (PG(modules_activated) && !tmp) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL TSRMLS_CC, err_type, "Cannot find serialization handler '%s'", new_value);
}
return FAILURE;
}
PS(serializer) = tmp;
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateTransSid) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
if (!strncasecmp(new_value, "on", sizeof("on"))) {
PS(use_trans_sid) = (zend_bool) 1;
} else {
PS(use_trans_sid) = (zend_bool) atoi(new_value);
}
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateSaveDir) /* {{{ */
{
/* Only do the safemode/open_basedir check at runtime */
if (stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) {
char *p;
if (memchr(new_value, '\0', new_value_length) != NULL) {
return FAILURE;
}
/* we do not use zend_memrchr() since path can contain ; itself */
if ((p = strchr(new_value, ';'))) {
char *p2;
p++;
if ((p2 = strchr(p, ';'))) {
p = p2 + 1;
}
} else {
p = new_value;
}
if (PG(open_basedir) && *p && php_check_open_basedir(p TSRMLS_CC)) {
return FAILURE;
}
}
OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateName) /* {{{ */
{
/* Numeric session.name won't work at all */
if ((!new_value_length || is_numeric_string(new_value, new_value_length, NULL, NULL, 0))) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME || stage == ZEND_INI_STAGE_ACTIVATE || stage == ZEND_INI_STAGE_STARTUP) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL TSRMLS_CC, err_type, "session.name cannot be a numeric or empty '%s'", new_value);
}
return FAILURE;
}
OnUpdateStringUnempty(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateHashFunc) /* {{{ */
{
long val;
char *endptr = NULL;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
PS(hash_ops) = NULL;
#endif
val = strtol(new_value, &endptr, 10);
if (endptr && (*endptr == '\0')) {
/* Numeric value */
PS(hash_func) = val ? 1 : 0;
return SUCCESS;
}
if (new_value_length == (sizeof("md5") - 1) &&
strncasecmp(new_value, "md5", sizeof("md5") - 1) == 0) {
PS(hash_func) = PS_HASH_FUNC_MD5;
return SUCCESS;
}
if (new_value_length == (sizeof("sha1") - 1) &&
strncasecmp(new_value, "sha1", sizeof("sha1") - 1) == 0) {
PS(hash_func) = PS_HASH_FUNC_SHA1;
return SUCCESS;
}
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH) /* {{{ */
{
php_hash_ops *ops = (php_hash_ops*)php_hash_fetch_ops(new_value, new_value_length);
if (ops) {
PS(hash_func) = PS_HASH_FUNC_OTHER;
PS(hash_ops) = ops;
return SUCCESS;
}
}
#endif /* HAVE_HASH_EXT }}} */
php_error_docref(NULL TSRMLS_CC, E_WARNING, "session.configuration 'session.hash_function' must be existing hash function. %s does not exist.", new_value);
return FAILURE;
}
/* }}} */
static PHP_INI_MH(OnUpdateRfc1867Freq) /* {{{ */
{
int tmp;
tmp = zend_atoi(new_value, new_value_length);
if(tmp < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "session.upload_progress.freq must be greater than or equal to zero");
return FAILURE;
}
if(new_value_length > 0 && new_value[new_value_length-1] == '%') {
if(tmp > 100) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "session.upload_progress.freq cannot be over 100%%");
return FAILURE;
}
PS(rfc1867_freq) = -tmp;
} else {
PS(rfc1867_freq) = tmp;
}
return SUCCESS;
} /* }}} */
static ZEND_INI_MH(OnUpdateSmartStr) /* {{{ */
{
smart_str *p;
#ifndef ZTS
char *base = (char *) mh_arg2;
#else
char *base;
base = (char *) ts_resource(*((int *) mh_arg2));
#endif
p = (smart_str *) (base+(size_t) mh_arg1);
smart_str_sets(p, new_value);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("session.save_path", "", PHP_INI_ALL, OnUpdateSaveDir,save_path, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.name", "PHPSESSID", PHP_INI_ALL, OnUpdateName, session_name, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.save_handler", "files", PHP_INI_ALL, OnUpdateSaveHandler)
STD_PHP_INI_BOOLEAN("session.auto_start", "0", PHP_INI_PERDIR, OnUpdateBool, auto_start, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_probability", "1", PHP_INI_ALL, OnUpdateLong, gc_probability, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_divisor", "100", PHP_INI_ALL, OnUpdateLong, gc_divisor, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_maxlifetime", "1440", PHP_INI_ALL, OnUpdateLong, gc_maxlifetime, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.serialize_handler", "php", PHP_INI_ALL, OnUpdateSerializer)
STD_PHP_INI_ENTRY("session.cookie_lifetime", "0", PHP_INI_ALL, OnUpdateLong, cookie_lifetime, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_path", "/", PHP_INI_ALL, OnUpdateString, cookie_path, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_domain", "", PHP_INI_ALL, OnUpdateString, cookie_domain, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.cookie_secure", "", PHP_INI_ALL, OnUpdateBool, cookie_secure, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.cookie_httponly", "", PHP_INI_ALL, OnUpdateBool, cookie_httponly, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.use_cookies", "1", PHP_INI_ALL, OnUpdateBool, use_cookies, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.use_only_cookies", "1", PHP_INI_ALL, OnUpdateBool, use_only_cookies, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.use_strict_mode", "0", PHP_INI_ALL, OnUpdateBool, use_strict_mode, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.referer_check", "", PHP_INI_ALL, OnUpdateString, extern_referer_chk, php_ps_globals, ps_globals)
#if HAVE_DEV_URANDOM
STD_PHP_INI_ENTRY("session.entropy_file", "/dev/urandom", PHP_INI_ALL, OnUpdateString, entropy_file, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.entropy_length", "32", PHP_INI_ALL, OnUpdateLong, entropy_length, php_ps_globals, ps_globals)
#elif HAVE_DEV_ARANDOM
STD_PHP_INI_ENTRY("session.entropy_file", "/dev/arandom", PHP_INI_ALL, OnUpdateString, entropy_file, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.entropy_length", "32", PHP_INI_ALL, OnUpdateLong, entropy_length, php_ps_globals, ps_globals)
#else
STD_PHP_INI_ENTRY("session.entropy_file", "", PHP_INI_ALL, OnUpdateString, entropy_file, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.entropy_length", "0", PHP_INI_ALL, OnUpdateLong, entropy_length, php_ps_globals, ps_globals)
#endif
STD_PHP_INI_ENTRY("session.cache_limiter", "nocache", PHP_INI_ALL, OnUpdateString, cache_limiter, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cache_expire", "180", PHP_INI_ALL, OnUpdateLong, cache_expire, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.use_trans_sid", "0", PHP_INI_ALL, OnUpdateTransSid)
PHP_INI_ENTRY("session.hash_function", "0", PHP_INI_ALL, OnUpdateHashFunc)
STD_PHP_INI_ENTRY("session.hash_bits_per_character", "4", PHP_INI_ALL, OnUpdateLong, hash_bits_per_character, php_ps_globals, ps_globals)
/* Upload progress */
STD_PHP_INI_BOOLEAN("session.upload_progress.enabled",
"1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_enabled, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.upload_progress.cleanup",
"1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_cleanup, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.prefix",
"upload_progress_", ZEND_INI_PERDIR, OnUpdateSmartStr, rfc1867_prefix, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.name",
"PHP_SESSION_UPLOAD_PROGRESS", ZEND_INI_PERDIR, OnUpdateSmartStr, rfc1867_name, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.freq", "1%", ZEND_INI_PERDIR, OnUpdateRfc1867Freq, rfc1867_freq, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.min_freq",
"1", ZEND_INI_PERDIR, OnUpdateReal, rfc1867_min_freq,php_ps_globals, ps_globals)
/* Commented out until future discussion */
/* PHP_INI_ENTRY("session.encode_sources", "globals,track", PHP_INI_ALL, NULL) */
PHP_INI_END()
/* }}} */
/* ***************
* Serializers *
*************** */
PS_SERIALIZER_ENCODE_FUNC(php_serialize) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &PS(http_session_vars), &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
if (newlen) {
*newlen = buf.len;
}
smart_str_0(&buf);
*newstr = buf.c;
return SUCCESS;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */
{
const char *endptr = val + vallen;
zval *session_vars;
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
ALLOC_INIT_ZVAL(session_vars);
if (php_var_unserialize(&session_vars, &val, endptr, &var_hash TSRMLS_CC)) {
var_push_dtor(&var_hash, &session_vars);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (PS(http_session_vars)) {
zval_ptr_dtor(&PS(http_session_vars));
}
if (Z_TYPE_P(session_vars) == IS_NULL) {
array_init(session_vars);
}
PS(http_session_vars) = session_vars;
ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), Z_REFCOUNT_P(PS(http_session_vars)) + 1, 1);
return SUCCESS;
}
/* }}} */
#define PS_BIN_NR_OF_BITS 8
#define PS_BIN_UNDEF (1<<(PS_BIN_NR_OF_BITS-1))
#define PS_BIN_MAX (PS_BIN_UNDEF-1)
PS_SERIALIZER_ENCODE_FUNC(php_binary) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PS_ENCODE_VARS;
PHP_VAR_SERIALIZE_INIT(var_hash);
PS_ENCODE_LOOP(
if (key_length > PS_BIN_MAX) continue;
smart_str_appendc(&buf, (unsigned char) key_length);
smart_str_appendl(&buf, key, key_length);
php_var_serialize(&buf, struc, &var_hash TSRMLS_CC);
} else {
if (key_length > PS_BIN_MAX) continue;
smart_str_appendc(&buf, (unsigned char) (key_length & PS_BIN_UNDEF));
smart_str_appendl(&buf, key, key_length);
);
if (newlen) {
*newlen = buf.len;
}
smart_str_0(&buf);
*newstr = buf.c;
PHP_VAR_SERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */
{
const char *p;
char *name;
const char *endptr = val + vallen;
zval *current;
int namelen;
int has_value;
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
for (p = val; p < endptr; ) {
zval **tmp;
namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF);
if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
has_value = *p & PS_BIN_UNDEF ? 0 : 1;
name = estrndup(p + 1, namelen);
p += namelen + 1;
if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) {
if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) {
efree(name);
continue;
}
}
if (has_value) {
ALLOC_INIT_ZVAL(current);
if (php_var_unserialize(¤t, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) {
php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC);
} else {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
var_push_dtor_no_addref(&var_hash, ¤t);
}
PS_ADD_VARL(name, namelen);
efree(name);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
#define PS_DELIMITER '|'
#define PS_UNDEF_MARKER '!'
PS_SERIALIZER_ENCODE_FUNC(php) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PS_ENCODE_VARS;
PHP_VAR_SERIALIZE_INIT(var_hash);
PS_ENCODE_LOOP(
smart_str_appendl(&buf, key, key_length);
if (memchr(key, PS_DELIMITER, key_length) || memchr(key, PS_UNDEF_MARKER, key_length)) {
PHP_VAR_SERIALIZE_DESTROY(var_hash);
smart_str_free(&buf);
return FAILURE;
}
smart_str_appendc(&buf, PS_DELIMITER);
php_var_serialize(&buf, struc, &var_hash TSRMLS_CC);
} else {
smart_str_appendc(&buf, PS_UNDEF_MARKER);
smart_str_appendl(&buf, key, key_length);
smart_str_appendc(&buf, PS_DELIMITER);
);
if (newlen) {
*newlen = buf.len;
}
smart_str_0(&buf);
*newstr = buf.c;
PHP_VAR_SERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */
{
const char *p, *q;
char *name;
const char *endptr = val + vallen;
zval *current;
int namelen;
int has_value;
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
p = val;
while (p < endptr) {
zval **tmp;
q = p;
while (*q != PS_DELIMITER) {
if (++q >= endptr) goto break_outer_loop;
}
if (p[0] == PS_UNDEF_MARKER) {
p++;
has_value = 0;
} else {
has_value = 1;
}
namelen = q - p;
name = estrndup(p, namelen);
q++;
if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) {
if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) {
goto skip;
}
}
if (has_value) {
ALLOC_INIT_ZVAL(current);
if (php_var_unserialize(¤t, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) {
php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC);
} else {
var_push_dtor_no_addref(&var_hash, ¤t);
efree(name);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
var_push_dtor_no_addref(&var_hash, ¤t);
}
PS_ADD_VARL(name, namelen);
skip:
efree(name);
p = q;
}
break_outer_loop:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
#define MAX_SERIALIZERS 32
#define PREDEFINED_SERIALIZERS 3
static ps_serializer ps_serializers[MAX_SERIALIZERS + 1] = {
PS_SERIALIZER_ENTRY(php_serialize),
PS_SERIALIZER_ENTRY(php),
PS_SERIALIZER_ENTRY(php_binary)
};
PHPAPI int php_session_register_serializer(const char *name, int (*encode)(PS_SERIALIZER_ENCODE_ARGS), int (*decode)(PS_SERIALIZER_DECODE_ARGS)) /* {{{ */
{
int ret = -1;
int i;
for (i = 0; i < MAX_SERIALIZERS; i++) {
if (ps_serializers[i].name == NULL) {
ps_serializers[i].name = name;
ps_serializers[i].encode = encode;
ps_serializers[i].decode = decode;
ps_serializers[i + 1].name = NULL;
ret = 0;
break;
}
}
return ret;
}
/* }}} */
/* *******************
* Storage Modules *
******************* */
#define MAX_MODULES 10
#define PREDEFINED_MODULES 2
static ps_module *ps_modules[MAX_MODULES + 1] = {
ps_files_ptr,
ps_user_ptr
};
PHPAPI int php_session_register_module(ps_module *ptr) /* {{{ */
{
int ret = -1;
int i;
for (i = 0; i < MAX_MODULES; i++) {
if (!ps_modules[i]) {
ps_modules[i] = ptr;
ret = 0;
break;
}
}
return ret;
}
/* }}} */
/* ******************
* Cache Limiters *
****************** */
typedef struct {
char *name;
void (*func)(TSRMLS_D);
} php_session_cache_limiter_t;
#define CACHE_LIMITER(name) _php_cache_limiter_##name
#define CACHE_LIMITER_FUNC(name) static void CACHE_LIMITER(name)(TSRMLS_D)
#define CACHE_LIMITER_ENTRY(name) { #name, CACHE_LIMITER(name) },
#define ADD_HEADER(a) sapi_add_header(a, strlen(a), 1);
#define MAX_STR 512
static char *month_names[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char *week_days[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
};
static inline void strcpy_gmt(char *ubuf, time_t *when) /* {{{ */
{
char buf[MAX_STR];
struct tm tm, *res;
int n;
res = php_gmtime_r(when, &tm);
if (!res) {
ubuf[0] = '\0';
return;
}
n = slprintf(buf, sizeof(buf), "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */
week_days[tm.tm_wday], tm.tm_mday,
month_names[tm.tm_mon], tm.tm_year + 1900,
tm.tm_hour, tm.tm_min,
tm.tm_sec);
memcpy(ubuf, buf, n);
ubuf[n] = '\0';
}
/* }}} */
static inline void last_modified(TSRMLS_D) /* {{{ */
{
const char *path;
struct stat sb;
char buf[MAX_STR + 1];
path = SG(request_info).path_translated;
if (path) {
if (VCWD_STAT(path, &sb) == -1) {
return;
}
#define LAST_MODIFIED "Last-Modified: "
memcpy(buf, LAST_MODIFIED, sizeof(LAST_MODIFIED) - 1);
strcpy_gmt(buf + sizeof(LAST_MODIFIED) - 1, &sb.st_mtime);
ADD_HEADER(buf);
}
}
/* }}} */
#define EXPIRES "Expires: "
CACHE_LIMITER_FUNC(public) /* {{{ */
{
char buf[MAX_STR + 1];
struct timeval tv;
time_t now;
gettimeofday(&tv, NULL);
now = tv.tv_sec + PS(cache_expire) * 60;
memcpy(buf, EXPIRES, sizeof(EXPIRES) - 1);
strcpy_gmt(buf + sizeof(EXPIRES) - 1, &now);
ADD_HEADER(buf);
snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=%ld", PS(cache_expire) * 60); /* SAFE */
ADD_HEADER(buf);
last_modified(TSRMLS_C);
}
/* }}} */
CACHE_LIMITER_FUNC(private_no_expire) /* {{{ */
{
char buf[MAX_STR + 1];
snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=%ld, pre-check=%ld", PS(cache_expire) * 60, PS(cache_expire) * 60); /* SAFE */
ADD_HEADER(buf);
last_modified(TSRMLS_C);
}
/* }}} */
CACHE_LIMITER_FUNC(private) /* {{{ */
{
ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
CACHE_LIMITER(private_no_expire)(TSRMLS_C);
}
/* }}} */
CACHE_LIMITER_FUNC(nocache) /* {{{ */
{
ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
/* For HTTP/1.1 conforming clients and the rest (MSIE 5) */
ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
/* For HTTP/1.0 conforming clients */
ADD_HEADER("Pragma: no-cache");
}
/* }}} */
static php_session_cache_limiter_t php_session_cache_limiters[] = {
CACHE_LIMITER_ENTRY(public)
CACHE_LIMITER_ENTRY(private)
CACHE_LIMITER_ENTRY(private_no_expire)
CACHE_LIMITER_ENTRY(nocache)
{0}
};
static int php_session_cache_limiter(TSRMLS_D) /* {{{ */
{
php_session_cache_limiter_t *lim;
if (PS(cache_limiter)[0] == '\0') return 0;
if (SG(headers_sent)) {
const char *output_start_filename = php_output_get_start_filename(TSRMLS_C);
int output_start_lineno = php_output_get_start_lineno(TSRMLS_C);
if (output_start_filename) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cache limiter - headers already sent (output started at %s:%d)", output_start_filename, output_start_lineno);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cache limiter - headers already sent");
}
return -2;
}
for (lim = php_session_cache_limiters; lim->name; lim++) {
if (!strcasecmp(lim->name, PS(cache_limiter))) {
lim->func(TSRMLS_C);
return 0;
}
}
return -1;
}
/* }}} */
/* *********************
* Cookie Management *
********************* */
#define COOKIE_SET_COOKIE "Set-Cookie: "
#define COOKIE_EXPIRES "; expires="
#define COOKIE_MAX_AGE "; Max-Age="
#define COOKIE_PATH "; path="
#define COOKIE_DOMAIN "; domain="
#define COOKIE_SECURE "; secure"
#define COOKIE_HTTPONLY "; HttpOnly"
/*
* Remove already sent session ID cookie.
* It must be directly removed from SG(sapi_header) because sapi_add_header_ex()
* removes all of matching cookie. i.e. It deletes all of Set-Cookie headers.
*/
static void php_session_remove_cookie(TSRMLS_D) {
sapi_header_struct *header;
zend_llist *l = &SG(sapi_headers).headers;
zend_llist_element *next;
zend_llist_element *current;
char *session_cookie, *e_session_name;
int session_cookie_len, len = sizeof("Set-Cookie")-1;
e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)), NULL);
spprintf(&session_cookie, 0, "Set-Cookie: %s=", e_session_name);
efree(e_session_name);
session_cookie_len = strlen(session_cookie);
current = l->head;
while (current) {
header = (sapi_header_struct *)(current->data);
next = current->next;
if (header->header_len > len && header->header[len] == ':'
&& !strncmp(header->header, session_cookie, session_cookie_len)) {
if (current->prev) {
current->prev->next = next;
} else {
l->head = next;
}
if (next) {
next->prev = current->prev;
} else {
l->tail = current->prev;
}
sapi_free_header(header);
efree(current);
--l->count;
}
current = next;
}
efree(session_cookie);
}
static void php_session_send_cookie(TSRMLS_D) /* {{{ */
{
smart_str ncookie = {0};
char *date_fmt = NULL;
char *e_session_name, *e_id;
if (SG(headers_sent)) {
const char *output_start_filename = php_output_get_start_filename(TSRMLS_C);
int output_start_lineno = php_output_get_start_lineno(TSRMLS_C);
if (output_start_filename) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent by (output started at %s:%d)", output_start_filename, output_start_lineno);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot send session cookie - headers already sent");
}
return;
}
/* URL encode session_name and id because they might be user supplied */
e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)), NULL);
e_id = php_url_encode(PS(id), strlen(PS(id)), NULL);
smart_str_appends(&ncookie, COOKIE_SET_COOKIE);
smart_str_appends(&ncookie, e_session_name);
smart_str_appendc(&ncookie, '=');
smart_str_appends(&ncookie, e_id);
efree(e_session_name);
efree(e_id);
if (PS(cookie_lifetime) > 0) {
struct timeval tv;
time_t t;
gettimeofday(&tv, NULL);
t = tv.tv_sec + PS(cookie_lifetime);
if (t > 0) {
date_fmt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0 TSRMLS_CC);
smart_str_appends(&ncookie, COOKIE_EXPIRES);
smart_str_appends(&ncookie, date_fmt);
efree(date_fmt);
smart_str_appends(&ncookie, COOKIE_MAX_AGE);
smart_str_append_long(&ncookie, PS(cookie_lifetime));
}
}
if (PS(cookie_path)[0]) {
smart_str_appends(&ncookie, COOKIE_PATH);
smart_str_appends(&ncookie, PS(cookie_path));
}
if (PS(cookie_domain)[0]) {
smart_str_appends(&ncookie, COOKIE_DOMAIN);
smart_str_appends(&ncookie, PS(cookie_domain));
}
if (PS(cookie_secure)) {
smart_str_appends(&ncookie, COOKIE_SECURE);
}
if (PS(cookie_httponly)) {
smart_str_appends(&ncookie, COOKIE_HTTPONLY);
}
smart_str_0(&ncookie);
php_session_remove_cookie(TSRMLS_C); /* remove already sent session ID cookie */
sapi_add_header_ex(ncookie.c, ncookie.len, 0, 0 TSRMLS_CC);
}
/* }}} */
PHPAPI ps_module *_php_find_ps_module(char *name TSRMLS_DC) /* {{{ */
{
ps_module *ret = NULL;
ps_module **mod;
int i;
for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
if (*mod && !strcasecmp(name, (*mod)->s_name)) {
ret = *mod;
break;
}
}
return ret;
}
/* }}} */
PHPAPI const ps_serializer *_php_find_ps_serializer(char *name TSRMLS_DC) /* {{{ */
{
const ps_serializer *ret = NULL;
const ps_serializer *mod;
for (mod = ps_serializers; mod->name; mod++) {
if (!strcasecmp(name, mod->name)) {
ret = mod;
break;
}
}
return ret;
}
/* }}} */
static void ppid2sid(zval **ppid TSRMLS_DC) {
if (Z_TYPE_PP(ppid) != IS_STRING) {
PS(id) = NULL;
PS(send_cookie) = 1;
} else {
convert_to_string((*ppid));
PS(id) = estrndup(Z_STRVAL_PP(ppid), Z_STRLEN_PP(ppid));
PS(send_cookie) = 0;
}
}
PHPAPI void php_session_reset_id(TSRMLS_D) /* {{{ */
{
int module_number = PS(module_number);
if (!PS(id)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot set session ID - session ID is not initialized");
return;
}
if (PS(use_cookies) && PS(send_cookie)) {
php_session_send_cookie(TSRMLS_C);
PS(send_cookie) = 0;
}
/* if the SID constant exists, destroy it. */
zend_hash_del(EG(zend_constants), "sid", sizeof("sid"));
if (PS(define_sid)) {
smart_str var = {0};
smart_str_appends(&var, PS(session_name));
smart_str_appendc(&var, '=');
smart_str_appends(&var, PS(id));
smart_str_0(&var);
REGISTER_STRINGL_CONSTANT("SID", var.c, var.len, 0);
} else {
REGISTER_STRINGL_CONSTANT("SID", STR_EMPTY_ALLOC(), 0, 0);
}
if (PS(apply_trans_sid)) {
php_url_scanner_reset_vars(TSRMLS_C);
php_url_scanner_add_var(PS(session_name), strlen(PS(session_name)), PS(id), strlen(PS(id)), 1 TSRMLS_CC);
}
}
/* }}} */
PHPAPI void php_session_start(TSRMLS_D) /* {{{ */
{
zval **ppid;
zval **data;
char *p, *value;
int nrand;
int lensess;
if (PS(use_only_cookies)) {
PS(apply_trans_sid) = 0;
} else {
PS(apply_trans_sid) = PS(use_trans_sid);
}
switch (PS(session_status)) {
case php_session_active:
php_error(E_NOTICE, "A session had already been started - ignoring session_start()");
return;
break;
case php_session_disabled:
value = zend_ini_string("session.save_handler", sizeof("session.save_handler"), 0);
if (!PS(mod) && value) {
PS(mod) = _php_find_ps_module(value TSRMLS_CC);
if (!PS(mod)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find save handler '%s' - session startup failed", value);
return;
}
}
value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler"), 0);
if (!PS(serializer) && value) {
PS(serializer) = _php_find_ps_serializer(value TSRMLS_CC);
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find serialization handler '%s' - session startup failed", value);
return;
}
}
PS(session_status) = php_session_none;
/* fallthrough */
default:
case php_session_none:
PS(define_sid) = 1;
PS(send_cookie) = 1;
}
lensess = strlen(PS(session_name));
/* Cookies are preferred, because initially
* cookie and get variables will be available. */
if (!PS(id)) {
if (PS(use_cookies) && zend_hash_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS
) {
ppid2sid(ppid TSRMLS_CC);
PS(apply_trans_sid) = 0;
PS(define_sid) = 0;
}
if (!PS(use_only_cookies) && !PS(id) &&
zend_hash_find(&EG(symbol_table), "_GET", sizeof("_GET"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS
) {
ppid2sid(ppid TSRMLS_CC);
}
if (!PS(use_only_cookies) && !PS(id) &&
zend_hash_find(&EG(symbol_table), "_POST", sizeof("_POST"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_ARRAY &&
zend_hash_find(Z_ARRVAL_PP(data), PS(session_name), lensess + 1, (void **) &ppid) == SUCCESS
) {
ppid2sid(ppid TSRMLS_CC);
}
}
/* Check the REQUEST_URI symbol for a string of the form
* '<session-name>=<session-id>' to allow URLs of the form
* http://yoursite/<session-name>=<session-id>/script.php */
if (!PS(use_only_cookies) && !PS(id) && PG(http_globals)[TRACK_VARS_SERVER] &&
zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_STRING &&
(p = strstr(Z_STRVAL_PP(data), PS(session_name))) &&
p[lensess] == '='
) {
char *q;
p += lensess + 1;
if ((q = strpbrk(p, "/?\\"))) {
PS(id) = estrndup(p, q - p);
PS(send_cookie) = 0;
}
}
/* Check whether the current request was referred to by
* an external site which invalidates the previously found id. */
if (PS(id) &&
PS(extern_referer_chk)[0] != '\0' &&
PG(http_globals)[TRACK_VARS_SERVER] &&
zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_REFERER", sizeof("HTTP_REFERER"), (void **) &data) == SUCCESS &&
Z_TYPE_PP(data) == IS_STRING &&
Z_STRLEN_PP(data) != 0 &&
strstr(Z_STRVAL_PP(data), PS(extern_referer_chk)) == NULL
) {
efree(PS(id));
PS(id) = NULL;
PS(send_cookie) = 1;
if (PS(use_trans_sid) && !PS(use_only_cookies)) {
PS(apply_trans_sid) = 1;
}
}
/* Finally check session id for dangarous characters
* Security note: session id may be embedded in HTML pages.*/
if (PS(id) && strpbrk(PS(id), "\r\n\t <>'\"\\")) {
efree(PS(id));
PS(id) = NULL;
}
php_session_initialize(TSRMLS_C);
php_session_cache_limiter(TSRMLS_C);
if ((PS(mod_data) || PS(mod_user_implemented)) && PS(gc_probability) > 0) {
int nrdels = -1;
nrand = (int) ((float) PS(gc_divisor) * php_combined_lcg(TSRMLS_C));
if (nrand < PS(gc_probability)) {
PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &nrdels TSRMLS_CC);
#ifdef SESSION_DEBUG
if (nrdels != -1) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "purged %d expired session objects", nrdels);
}
#endif
}
}
}
/* }}} */
static void php_session_flush(TSRMLS_D) /* {{{ */
{
if (PS(session_status) == php_session_active) {
PS(session_status) = php_session_none;
php_session_save_current_state(TSRMLS_C);
}
}
/* }}} */
static void php_session_abort(TSRMLS_D) /* {{{ */
{
if (PS(session_status) == php_session_active) {
PS(session_status) = php_session_none;
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
}
}
}
/* }}} */
static void php_session_reset(TSRMLS_D) /* {{{ */
{
if (PS(session_status) == php_session_active) {
php_session_initialize(TSRMLS_C);
}
}
/* }}} */
PHPAPI void session_adapt_url(const char *url, size_t urllen, char **new, size_t *newlen TSRMLS_DC) /* {{{ */
{
if (PS(apply_trans_sid) && (PS(session_status) == php_session_active)) {
*new = php_url_scanner_adapt_single_url(url, urllen, PS(session_name), PS(id), newlen TSRMLS_CC);
}
}
/* }}} */
/* ********************************
* Userspace exported functions *
******************************** */
/* {{{ proto void session_set_cookie_params(int lifetime [, string path [, string domain [, bool secure[, bool httponly]]]])
Set session cookie parameters */
static PHP_FUNCTION(session_set_cookie_params)
{
zval **lifetime = NULL;
char *path = NULL, *domain = NULL;
int path_len, domain_len, argc = ZEND_NUM_ARGS();
zend_bool secure = 0, httponly = 0;
if (!PS(use_cookies) ||
zend_parse_parameters(argc TSRMLS_CC, "Z|ssbb", &lifetime, &path, &path_len, &domain, &domain_len, &secure, &httponly) == FAILURE) {
return;
}
convert_to_string_ex(lifetime);
zend_alter_ini_entry("session.cookie_lifetime", sizeof("session.cookie_lifetime"), Z_STRVAL_PP(lifetime), Z_STRLEN_PP(lifetime), PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
if (path) {
zend_alter_ini_entry("session.cookie_path", sizeof("session.cookie_path"), path, path_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
if (domain) {
zend_alter_ini_entry("session.cookie_domain", sizeof("session.cookie_domain"), domain, domain_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
if (argc > 3) {
zend_alter_ini_entry("session.cookie_secure", sizeof("session.cookie_secure"), secure ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
if (argc > 4) {
zend_alter_ini_entry("session.cookie_httponly", sizeof("session.cookie_httponly"), httponly ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto array session_get_cookie_params(void)
Return the session cookie parameters */
static PHP_FUNCTION(session_get_cookie_params)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_assoc_long(return_value, "lifetime", PS(cookie_lifetime));
add_assoc_string(return_value, "path", PS(cookie_path), 1);
add_assoc_string(return_value, "domain", PS(cookie_domain), 1);
add_assoc_bool(return_value, "secure", PS(cookie_secure));
add_assoc_bool(return_value, "httponly", PS(cookie_httponly));
}
/* }}} */
/* {{{ proto string session_name([string newname])
Return the current session name. If newname is given, the session name is replaced with newname */
static PHP_FUNCTION(session_name)
{
char *name = NULL;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
RETVAL_STRING(PS(session_name), 1);
if (name) {
zend_alter_ini_entry("session.name", sizeof("session.name"), name, name_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto string session_module_name([string newname])
Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname */
static PHP_FUNCTION(session_module_name)
{
char *name = NULL;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
/* Set return_value to current module name */
if (PS(mod) && PS(mod)->s_name) {
RETVAL_STRING(safe_estrdup(PS(mod)->s_name), 0);
} else {
RETVAL_EMPTY_STRING();
}
if (name) {
if (!_php_find_ps_module(name TSRMLS_CC)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot find named PHP session module (%s)", name);
zval_dtor(return_value);
RETURN_FALSE;
}
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data) TSRMLS_CC);
}
PS(mod_data) = NULL;
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), name, name_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto void session_set_save_handler(string open, string close, string read, string write, string destroy, string gc, string create_sid)
Sets user-level functions */
static PHP_FUNCTION(session_set_save_handler)
{
zval ***args = NULL;
int i, num_args, argc = ZEND_NUM_ARGS();
char *name;
if (PS(session_status) != php_session_none) {
RETURN_FALSE;
}
if (argc > 0 && argc <= 2) {
zval *obj = NULL, *callback = NULL;
zend_uint func_name_len;
char *func_name;
HashPosition pos;
zend_function *default_mptr, *current_mptr;
ulong func_index;
php_shutdown_function_entry shutdown_function_entry;
zend_bool register_shutdown = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|b", &obj, php_session_iface_entry, ®ister_shutdown) == FAILURE) {
RETURN_FALSE;
}
/* Find implemented methods - SessionHandlerInterface */
zend_hash_internal_pointer_reset_ex(&php_session_iface_entry->function_table, &pos);
i = 0;
while (zend_hash_get_current_data_ex(&php_session_iface_entry->function_table, (void **) &default_mptr, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_session_iface_entry->function_table, &func_name, &func_name_len, &func_index, 0, &pos);
if (zend_hash_find(&Z_OBJCE_P(obj)->function_table, func_name, func_name_len, (void **)¤t_mptr) == SUCCESS) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
MAKE_STD_ZVAL(callback);
array_init_size(callback, 2);
Z_ADDREF_P(obj);
add_next_index_zval(callback, obj);
add_next_index_stringl(callback, func_name, func_name_len - 1, 1);
PS(mod_user_names).names[i] = callback;
} else {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Session handler's function table is corrupt");
RETURN_FALSE;
}
zend_hash_move_forward_ex(&php_session_iface_entry->function_table, &pos);
++i;
}
/* Find implemented methods - SessionIdInterface (optional) */
zend_hash_internal_pointer_reset_ex(&php_session_id_iface_entry->function_table, &pos);
while (zend_hash_get_current_data_ex(&php_session_id_iface_entry->function_table, (void **) &default_mptr, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_session_id_iface_entry->function_table, &func_name, &func_name_len, &func_index, 0, &pos);
if (zend_hash_find(&Z_OBJCE_P(obj)->function_table, func_name, func_name_len, (void **)¤t_mptr) == SUCCESS) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
MAKE_STD_ZVAL(callback);
array_init_size(callback, 2);
Z_ADDREF_P(obj);
add_next_index_zval(callback, obj);
add_next_index_stringl(callback, func_name, func_name_len - 1, 1);
PS(mod_user_names).names[i] = callback;
}
zend_hash_move_forward_ex(&php_session_id_iface_entry->function_table, &pos);
++i;
}
if (register_shutdown) {
/* create shutdown function */
shutdown_function_entry.arg_count = 1;
shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), 1, 0);
MAKE_STD_ZVAL(callback);
ZVAL_STRING(callback, "session_register_shutdown", 1);
shutdown_function_entry.arguments[0] = callback;
/* add shutdown function, removing the old one if it exists */
if (!register_user_shutdown_function("session_shutdown", sizeof("session_shutdown"), &shutdown_function_entry TSRMLS_CC)) {
zval_ptr_dtor(&callback);
efree(shutdown_function_entry.arguments);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to register session shutdown function");
RETURN_FALSE;
}
} else {
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);
}
if (PS(mod) && PS(session_status) == php_session_none && PS(mod) != &ps_mod_user) {
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
RETURN_TRUE;
}
if (argc != 6 && argc != 7) {
WRONG_PARAM_COUNT;
}
if (zend_parse_parameters(argc TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
return;
}
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);
/* at this point argc can only be 6 or 7 */
for (i = 0; i < argc; i++) {
if (!zend_is_callable(*args[i], 0, &name TSRMLS_CC)) {
efree(args);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument %d is not a valid callback", i+1);
efree(name);
RETURN_FALSE;
}
efree(name);
}
if (PS(mod) && PS(mod) != &ps_mod_user) {
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
for (i = 0; i < argc; i++) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
Z_ADDREF_PP(args[i]);
PS(mod_user_names).names[i] = *args[i];
}
efree(args);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string session_save_path([string newname])
Return the current save path passed to module_name. If newname is given, the save path is replaced with newname */
static PHP_FUNCTION(session_save_path)
{
char *name = NULL;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
RETVAL_STRING(PS(save_path), 1);
if (name) {
if (memchr(name, '\0', name_len) != NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The save_path cannot contain NULL characters");
zval_dtor(return_value);
RETURN_FALSE;
}
zend_alter_ini_entry("session.save_path", sizeof("session.save_path"), name, name_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto string session_id([string newid])
Return the current session id. If newid is given, the session id is replaced with newid */
static PHP_FUNCTION(session_id)
{
char *name = NULL;
int name_len, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
if (PS(id)) {
RETVAL_STRING(PS(id), 1);
} else {
RETVAL_EMPTY_STRING();
}
if (name) {
if (PS(id)) {
efree(PS(id));
}
PS(id) = estrndup(name, name_len);
}
}
/* }}} */
/* {{{ proto bool session_regenerate_id([bool delete_old_session])
Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session. */
static PHP_FUNCTION(session_regenerate_id)
{
zend_bool del_ses = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &del_ses) == FAILURE) {
return;
}
if (SG(headers_sent) && PS(use_cookies)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot regenerate session id - headers already sent");
RETURN_FALSE;
}
if (PS(session_status) == php_session_active) {
if (PS(id)) {
if (del_ses && PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed");
RETURN_FALSE;
}
efree(PS(id));
}
PS(id) = PS(mod)->s_create_sid(&PS(mod_data), NULL TSRMLS_CC);
if (PS(id)) {
PS(send_cookie) = 1;
php_session_reset_id(TSRMLS_C);
RETURN_TRUE;
} else {
PS(id) = STR_EMPTY_ALLOC();
}
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto string session_cache_limiter([string new_cache_limiter])
Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter */
static PHP_FUNCTION(session_cache_limiter)
{
char *limiter = NULL;
int limiter_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &limiter, &limiter_len) == FAILURE) {
return;
}
RETVAL_STRING(PS(cache_limiter), 1);
if (limiter) {
zend_alter_ini_entry("session.cache_limiter", sizeof("session.cache_limiter"), limiter, limiter_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto int session_cache_expire([int new_cache_expire])
Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire */
static PHP_FUNCTION(session_cache_expire)
{
zval **expires = NULL;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|Z", &expires) == FAILURE) {
return;
}
RETVAL_LONG(PS(cache_expire));
if (argc == 1) {
convert_to_string_ex(expires);
zend_alter_ini_entry("session.cache_expire", sizeof("session.cache_expire"), Z_STRVAL_PP(expires), Z_STRLEN_PP(expires), ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
}
}
/* }}} */
/* {{{ proto string session_encode(void)
Serializes the current setup and returns the serialized representation */
static PHP_FUNCTION(session_encode)
{
int len;
char *enc;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
enc = php_session_encode(&len TSRMLS_CC);
if (enc == NULL) {
RETURN_FALSE;
}
RETVAL_STRINGL(enc, len, 0);
}
/* }}} */
/* {{{ proto bool session_decode(string data)
Deserializes data and reinitializes the variables */
static PHP_FUNCTION(session_decode)
{
char *str;
int str_len;
if (PS(session_status) == php_session_none) {
RETURN_FALSE;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) {
return;
}
RETVAL_BOOL(php_session_decode(str, str_len TSRMLS_CC) == SUCCESS);
}
/* }}} */
/* {{{ proto bool session_start(void)
Begin session - reinitializes freezed variables, registers browsers etc */
static PHP_FUNCTION(session_start)
{
/* skipping check for non-zero args for performance reasons here ?*/
if (PS(id) && !strlen(PS(id))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot start session with empty session ID");
RETURN_FALSE;
}
php_session_start(TSRMLS_C);
if (PS(session_status) != php_session_active) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool session_destroy(void)
Destroy the current session and all data associated with it */
static PHP_FUNCTION(session_destroy)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(php_session_destroy(TSRMLS_C) == SUCCESS);
}
/* }}} */
/* {{{ proto void session_unset(void)
Unset all registered variables */
static PHP_FUNCTION(session_unset)
{
if (PS(session_status) == php_session_none) {
RETURN_FALSE;
}
IF_SESSION_VARS() {
HashTable *ht_sess_var;
SEPARATE_ZVAL_IF_NOT_REF(&PS(http_session_vars));
ht_sess_var = Z_ARRVAL_P(PS(http_session_vars));
/* Clean $_SESSION. */
zend_hash_clean(ht_sess_var);
}
}
/* }}} */
/* {{{ proto void session_write_close(void)
Write session data and end session */
static PHP_FUNCTION(session_write_close)
{
php_session_flush(TSRMLS_C);
}
/* }}} */
/* {{{ proto void session_abort(void)
Abort session and end session. Session data will not be written */
static PHP_FUNCTION(session_abort)
{
php_session_abort(TSRMLS_C);
}
/* }}} */
/* {{{ proto void session_reset(void)
Reset session data from saved session data */
static PHP_FUNCTION(session_reset)
{
php_session_reset(TSRMLS_C);
}
/* }}} */
/* {{{ proto int session_status(void)
Returns the current session status */
static PHP_FUNCTION(session_status)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(PS(session_status));
}
/* }}} */
/* {{{ proto void session_register_shutdown(void)
Registers session_write_close() as a shutdown function */
static PHP_FUNCTION(session_register_shutdown)
{
php_shutdown_function_entry shutdown_function_entry;
zval *callback;
/* This function is registered itself as a shutdown function by
* session_set_save_handler($obj). The reason we now register another
* shutdown function is in case the user registered their own shutdown
* function after calling session_set_save_handler(), which expects
* the session still to be available.
*/
shutdown_function_entry.arg_count = 1;
shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), 1, 0);
MAKE_STD_ZVAL(callback);
ZVAL_STRING(callback, "session_write_close", 1);
shutdown_function_entry.arguments[0] = callback;
if (!append_user_shutdown_function(shutdown_function_entry TSRMLS_CC)) {
zval_ptr_dtor(&callback);
efree(shutdown_function_entry.arguments);
/* Unable to register shutdown function, presumably because of lack
* of memory, so flush the session now. It would be done in rshutdown
* anyway but the handler will have had it's dtor called by then.
* If the user does have a later shutdown function which needs the
* session then tough luck.
*/
php_session_flush(TSRMLS_C);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to register session flush function");
}
}
/* }}} */
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_name, 0, 0, 0)
ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_module_name, 0, 0, 0)
ZEND_ARG_INFO(0, module)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_save_path, 0, 0, 0)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_id, 0, 0, 0)
ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_regenerate_id, 0, 0, 0)
ZEND_ARG_INFO(0, delete_old_session)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_decode, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_void, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_set_save_handler, 0, 0, 1)
ZEND_ARG_INFO(0, open)
ZEND_ARG_INFO(0, close)
ZEND_ARG_INFO(0, read)
ZEND_ARG_INFO(0, write)
ZEND_ARG_INFO(0, destroy)
ZEND_ARG_INFO(0, gc)
ZEND_ARG_INFO(0, create_sid)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_cache_limiter, 0, 0, 0)
ZEND_ARG_INFO(0, cache_limiter)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_cache_expire, 0, 0, 0)
ZEND_ARG_INFO(0, new_cache_expire)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_set_cookie_params, 0, 0, 1)
ZEND_ARG_INFO(0, lifetime)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, domain)
ZEND_ARG_INFO(0, secure)
ZEND_ARG_INFO(0, httponly)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_open, 0)
ZEND_ARG_INFO(0, save_path)
ZEND_ARG_INFO(0, session_name)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_close, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_read, 0)
ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_write, 0)
ZEND_ARG_INFO(0, key)
ZEND_ARG_INFO(0, val)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_destroy, 0)
ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_gc, 0)
ZEND_ARG_INFO(0, maxlifetime)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_create_sid, 0)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ session_functions[]
*/
static const zend_function_entry session_functions[] = {
PHP_FE(session_name, arginfo_session_name)
PHP_FE(session_module_name, arginfo_session_module_name)
PHP_FE(session_save_path, arginfo_session_save_path)
PHP_FE(session_id, arginfo_session_id)
PHP_FE(session_regenerate_id, arginfo_session_regenerate_id)
PHP_FE(session_decode, arginfo_session_decode)
PHP_FE(session_encode, arginfo_session_void)
PHP_FE(session_start, arginfo_session_void)
PHP_FE(session_destroy, arginfo_session_void)
PHP_FE(session_unset, arginfo_session_void)
PHP_FE(session_set_save_handler, arginfo_session_set_save_handler)
PHP_FE(session_cache_limiter, arginfo_session_cache_limiter)
PHP_FE(session_cache_expire, arginfo_session_cache_expire)
PHP_FE(session_set_cookie_params, arginfo_session_set_cookie_params)
PHP_FE(session_get_cookie_params, arginfo_session_void)
PHP_FE(session_write_close, arginfo_session_void)
PHP_FE(session_abort, arginfo_session_void)
PHP_FE(session_reset, arginfo_session_void)
PHP_FE(session_status, arginfo_session_void)
PHP_FE(session_register_shutdown, arginfo_session_void)
PHP_FALIAS(session_commit, session_write_close, arginfo_session_void)
PHP_FE_END
};
/* }}} */
/* {{{ SessionHandlerInterface functions[]
*/
static const zend_function_entry php_session_iface_functions[] = {
PHP_ABSTRACT_ME(SessionHandlerInterface, open, arginfo_session_class_open)
PHP_ABSTRACT_ME(SessionHandlerInterface, close, arginfo_session_class_close)
PHP_ABSTRACT_ME(SessionHandlerInterface, read, arginfo_session_class_read)
PHP_ABSTRACT_ME(SessionHandlerInterface, write, arginfo_session_class_write)
PHP_ABSTRACT_ME(SessionHandlerInterface, destroy, arginfo_session_class_destroy)
PHP_ABSTRACT_ME(SessionHandlerInterface, gc, arginfo_session_class_gc)
{ NULL, NULL, NULL }
};
/* }}} */
/* {{{ SessionIdInterface functions[]
*/
static const zend_function_entry php_session_id_iface_functions[] = {
PHP_ABSTRACT_ME(SessionIdInterface, create_sid, arginfo_session_class_create_sid)
{ NULL, NULL, NULL }
};
/* }}} */
/* {{{ SessionHandler functions[]
*/
static const zend_function_entry php_session_class_functions[] = {
PHP_ME(SessionHandler, open, arginfo_session_class_open, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, close, arginfo_session_class_close, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, read, arginfo_session_class_read, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, write, arginfo_session_class_write, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, destroy, arginfo_session_class_destroy, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, gc, arginfo_session_class_gc, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, create_sid, arginfo_session_class_create_sid, ZEND_ACC_PUBLIC)
{ NULL, NULL, NULL }
};
/* }}} */
/* ********************************
* Module Setup and Destruction *
******************************** */
static int php_rinit_session(zend_bool auto_start TSRMLS_DC) /* {{{ */
{
php_rinit_session_globals(TSRMLS_C);
if (PS(mod) == NULL) {
char *value;
value = zend_ini_string("session.save_handler", sizeof("session.save_handler"), 0);
if (value) {
PS(mod) = _php_find_ps_module(value TSRMLS_CC);
}
}
if (PS(serializer) == NULL) {
char *value;
value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler"), 0);
if (value) {
PS(serializer) = _php_find_ps_serializer(value TSRMLS_CC);
}
}
if (PS(mod) == NULL || PS(serializer) == NULL) {
/* current status is unusable */
PS(session_status) = php_session_disabled;
return SUCCESS;
}
if (auto_start) {
php_session_start(TSRMLS_C);
}
return SUCCESS;
} /* }}} */
static PHP_RINIT_FUNCTION(session) /* {{{ */
{
return php_rinit_session(PS(auto_start) TSRMLS_CC);
}
/* }}} */
static PHP_RSHUTDOWN_FUNCTION(session) /* {{{ */
{
int i;
zend_try {
php_session_flush(TSRMLS_C);
} zend_end_try();
php_rshutdown_session_globals(TSRMLS_C);
/* this should NOT be done in php_rshutdown_session_globals() */
for (i = 0; i < 7; i++) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
PS(mod_user_names).names[i] = NULL;
}
}
return SUCCESS;
}
/* }}} */
static PHP_GINIT_FUNCTION(ps) /* {{{ */
{
int i;
ps_globals->save_path = NULL;
ps_globals->session_name = NULL;
ps_globals->id = NULL;
ps_globals->mod = NULL;
ps_globals->serializer = NULL;
ps_globals->mod_data = NULL;
ps_globals->session_status = php_session_none;
ps_globals->default_mod = NULL;
ps_globals->mod_user_implemented = 0;
ps_globals->mod_user_is_open = 0;
for (i = 0; i < 7; i++) {
ps_globals->mod_user_names.names[i] = NULL;
}
ps_globals->http_session_vars = NULL;
}
/* }}} */
static PHP_MINIT_FUNCTION(session) /* {{{ */
{
zend_class_entry ce;
zend_register_auto_global("_SESSION", sizeof("_SESSION")-1, 0, NULL TSRMLS_CC);
PS(module_number) = module_number; /* if we really need this var we need to init it in zts mode as well! */
PS(session_status) = php_session_none;
REGISTER_INI_ENTRIES();
#ifdef HAVE_LIBMM
PHP_MINIT(ps_mm) (INIT_FUNC_ARGS_PASSTHRU);
#endif
php_session_rfc1867_orig_callback = php_rfc1867_callback;
php_rfc1867_callback = php_session_rfc1867_callback;
/* Register interfaces */
INIT_CLASS_ENTRY(ce, PS_IFACE_NAME, php_session_iface_functions);
php_session_iface_entry = zend_register_internal_class(&ce TSRMLS_CC);
php_session_iface_entry->ce_flags |= ZEND_ACC_INTERFACE;
INIT_CLASS_ENTRY(ce, PS_SID_IFACE_NAME, php_session_id_iface_functions);
php_session_id_iface_entry = zend_register_internal_class(&ce TSRMLS_CC);
php_session_id_iface_entry->ce_flags |= ZEND_ACC_INTERFACE;
/* Register base class */
INIT_CLASS_ENTRY(ce, PS_CLASS_NAME, php_session_class_functions);
php_session_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_class_implements(php_session_class_entry TSRMLS_CC, 1, php_session_iface_entry);
zend_class_implements(php_session_class_entry TSRMLS_CC, 1, php_session_id_iface_entry);
REGISTER_LONG_CONSTANT("PHP_SESSION_DISABLED", php_session_disabled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_SESSION_NONE", php_session_none, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_SESSION_ACTIVE", php_session_active, CONST_CS | CONST_PERSISTENT);
return SUCCESS;
}
/* }}} */
static PHP_MSHUTDOWN_FUNCTION(session) /* {{{ */
{
UNREGISTER_INI_ENTRIES();
#ifdef HAVE_LIBMM
PHP_MSHUTDOWN(ps_mm) (SHUTDOWN_FUNC_ARGS_PASSTHRU);
#endif
/* reset rfc1867 callbacks */
php_session_rfc1867_orig_callback = NULL;
if (php_rfc1867_callback == php_session_rfc1867_callback) {
php_rfc1867_callback = NULL;
}
ps_serializers[PREDEFINED_SERIALIZERS].name = NULL;
memset(&ps_modules[PREDEFINED_MODULES], 0, (MAX_MODULES-PREDEFINED_MODULES)*sizeof(ps_module *));
return SUCCESS;
}
/* }}} */
static PHP_MINFO_FUNCTION(session) /* {{{ */
{
ps_module **mod;
ps_serializer *ser;
smart_str save_handlers = {0};
smart_str ser_handlers = {0};
int i;
/* Get save handlers */
for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
if (*mod && (*mod)->s_name) {
smart_str_appends(&save_handlers, (*mod)->s_name);
smart_str_appendc(&save_handlers, ' ');
}
}
/* Get serializer handlers */
for (i = 0, ser = ps_serializers; i < MAX_SERIALIZERS; i++, ser++) {
if (ser && ser->name) {
smart_str_appends(&ser_handlers, ser->name);
smart_str_appendc(&ser_handlers, ' ');
}
}
php_info_print_table_start();
php_info_print_table_row(2, "Session Support", "enabled" );
if (save_handlers.c) {
smart_str_0(&save_handlers);
php_info_print_table_row(2, "Registered save handlers", save_handlers.c);
smart_str_free(&save_handlers);
} else {
php_info_print_table_row(2, "Registered save handlers", "none");
}
if (ser_handlers.c) {
smart_str_0(&ser_handlers);
php_info_print_table_row(2, "Registered serializer handlers", ser_handlers.c);
smart_str_free(&ser_handlers);
} else {
php_info_print_table_row(2, "Registered serializer handlers", "none");
}
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
static const zend_module_dep session_deps[] = { /* {{{ */
ZEND_MOD_OPTIONAL("hash")
ZEND_MOD_REQUIRED("spl")
ZEND_MOD_END
};
/* }}} */
/* ************************
* Upload hook handling *
************************ */
static zend_bool early_find_sid_in(zval *dest, int where, php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
zval **ppid;
if (!PG(http_globals)[where]) {
return 0;
}
if (zend_hash_find(Z_ARRVAL_P(PG(http_globals)[where]), PS(session_name), progress->sname_len+1, (void **)&ppid) == SUCCESS
&& Z_TYPE_PP(ppid) == IS_STRING) {
zval_dtor(dest);
ZVAL_ZVAL(dest, *ppid, 1, 0);
return 1;
}
return 0;
} /* }}} */
static void php_session_rfc1867_early_find_sid(php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
if (PS(use_cookies)) {
sapi_module.treat_data(PARSE_COOKIE, NULL, NULL TSRMLS_CC);
if (early_find_sid_in(&progress->sid, TRACK_VARS_COOKIE, progress TSRMLS_CC)) {
progress->apply_trans_sid = 0;
return;
}
}
if (PS(use_only_cookies)) {
return;
}
sapi_module.treat_data(PARSE_GET, NULL, NULL TSRMLS_CC);
early_find_sid_in(&progress->sid, TRACK_VARS_GET, progress TSRMLS_CC);
} /* }}} */
static zend_bool php_check_cancel_upload(php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
zval **progress_ary, **cancel_upload;
if (zend_symtable_find(Z_ARRVAL_P(PS(http_session_vars)), progress->key.c, progress->key.len+1, (void**)&progress_ary) != SUCCESS) {
return 0;
}
if (Z_TYPE_PP(progress_ary) != IS_ARRAY) {
return 0;
}
if (zend_hash_find(Z_ARRVAL_PP(progress_ary), "cancel_upload", sizeof("cancel_upload"), (void**)&cancel_upload) != SUCCESS) {
return 0;
}
return Z_TYPE_PP(cancel_upload) == IS_BOOL && Z_LVAL_PP(cancel_upload);
} /* }}} */
static void php_session_rfc1867_update(php_session_rfc1867_progress *progress, int force_update TSRMLS_DC) /* {{{ */
{
if (!force_update) {
if (Z_LVAL_P(progress->post_bytes_processed) < progress->next_update) {
return;
}
#ifdef HAVE_GETTIMEOFDAY
if (PS(rfc1867_min_freq) > 0.0) {
struct timeval tv = {0};
double dtv;
gettimeofday(&tv, NULL);
dtv = (double) tv.tv_sec + tv.tv_usec / 1000000.0;
if (dtv < progress->next_update_time) {
return;
}
progress->next_update_time = dtv + PS(rfc1867_min_freq);
}
#endif
progress->next_update = Z_LVAL_P(progress->post_bytes_processed) + progress->update_step;
}
php_session_initialize(TSRMLS_C);
PS(session_status) = php_session_active;
IF_SESSION_VARS() {
progress->cancel_upload |= php_check_cancel_upload(progress TSRMLS_CC);
ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), progress->key.c, progress->key.len+1, progress->data, 2, 0);
}
php_session_flush(TSRMLS_C);
} /* }}} */
static void php_session_rfc1867_cleanup(php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
php_session_initialize(TSRMLS_C);
PS(session_status) = php_session_active;
IF_SESSION_VARS() {
zend_hash_del(Z_ARRVAL_P(PS(http_session_vars)), progress->key.c, progress->key.len+1);
}
php_session_flush(TSRMLS_C);
} /* }}} */
static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra TSRMLS_DC) /* {{{ */
{
php_session_rfc1867_progress *progress;
int retval = SUCCESS;
if (php_session_rfc1867_orig_callback) {
retval = php_session_rfc1867_orig_callback(event, event_data, extra TSRMLS_CC);
}
if (!PS(rfc1867_enabled)) {
return retval;
}
progress = PS(rfc1867_progress);
switch(event) {
case MULTIPART_EVENT_START: {
multipart_event_start *data = (multipart_event_start *) event_data;
progress = ecalloc(1, sizeof(php_session_rfc1867_progress));
progress->content_length = data->content_length;
progress->sname_len = strlen(PS(session_name));
PS(rfc1867_progress) = progress;
}
break;
case MULTIPART_EVENT_FORMDATA: {
multipart_event_formdata *data = (multipart_event_formdata *) event_data;
size_t value_len;
if (Z_TYPE(progress->sid) && progress->key.c) {
break;
}
/* orig callback may have modified *data->newlength */
if (data->newlength) {
value_len = *data->newlength;
} else {
value_len = data->length;
}
if (data->name && data->value && value_len) {
size_t name_len = strlen(data->name);
if (name_len == progress->sname_len && memcmp(data->name, PS(session_name), name_len) == 0) {
zval_dtor(&progress->sid);
ZVAL_STRINGL(&progress->sid, (*data->value), value_len, 1);
} else if (name_len == PS(rfc1867_name).len && memcmp(data->name, PS(rfc1867_name).c, name_len) == 0) {
smart_str_free(&progress->key);
smart_str_appendl(&progress->key, PS(rfc1867_prefix).c, PS(rfc1867_prefix).len);
smart_str_appendl(&progress->key, *data->value, value_len);
smart_str_0(&progress->key);
progress->apply_trans_sid = PS(use_trans_sid);
php_session_rfc1867_early_find_sid(progress TSRMLS_CC);
}
}
}
break;
case MULTIPART_EVENT_FILE_START: {
multipart_event_file_start *data = (multipart_event_file_start *) event_data;
/* Do nothing when $_POST["PHP_SESSION_UPLOAD_PROGRESS"] is not set
* or when we have no session id */
if (!Z_TYPE(progress->sid) || !progress->key.c) {
break;
}
/* First FILE_START event, initializing data */
if (!progress->data) {
if (PS(rfc1867_freq) >= 0) {
progress->update_step = PS(rfc1867_freq);
} else if (PS(rfc1867_freq) < 0) { /* % of total size */
progress->update_step = progress->content_length * -PS(rfc1867_freq) / 100;
}
progress->next_update = 0;
progress->next_update_time = 0.0;
ALLOC_INIT_ZVAL(progress->data);
array_init(progress->data);
ALLOC_INIT_ZVAL(progress->post_bytes_processed);
ZVAL_LONG(progress->post_bytes_processed, data->post_bytes_processed);
ALLOC_INIT_ZVAL(progress->files);
array_init(progress->files);
add_assoc_long_ex(progress->data, "start_time", sizeof("start_time"), (long)sapi_get_request_time(TSRMLS_C));
add_assoc_long_ex(progress->data, "content_length", sizeof("content_length"), progress->content_length);
add_assoc_zval_ex(progress->data, "bytes_processed", sizeof("bytes_processed"), progress->post_bytes_processed);
add_assoc_bool_ex(progress->data, "done", sizeof("done"), 0);
add_assoc_zval_ex(progress->data, "files", sizeof("files"), progress->files);
php_rinit_session(0 TSRMLS_CC);
PS(id) = estrndup(Z_STRVAL(progress->sid), Z_STRLEN(progress->sid));
PS(apply_trans_sid) = progress->apply_trans_sid;
PS(send_cookie) = 0;
}
ALLOC_INIT_ZVAL(progress->current_file);
array_init(progress->current_file);
ALLOC_INIT_ZVAL(progress->current_file_bytes_processed);
ZVAL_LONG(progress->current_file_bytes_processed, 0);
/* Each uploaded file has its own array. Trying to make it close to $_FILES entries. */
add_assoc_string_ex(progress->current_file, "field_name", sizeof("field_name"), data->name, 1);
add_assoc_string_ex(progress->current_file, "name", sizeof("name"), *data->filename, 1);
add_assoc_null_ex(progress->current_file, "tmp_name", sizeof("tmp_name"));
add_assoc_long_ex(progress->current_file, "error", sizeof("error"), 0);
add_assoc_bool_ex(progress->current_file, "done", sizeof("done"), 0);
add_assoc_long_ex(progress->current_file, "start_time", sizeof("start_time"), (long)time(NULL));
add_assoc_zval_ex(progress->current_file, "bytes_processed", sizeof("bytes_processed"), progress->current_file_bytes_processed);
add_next_index_zval(progress->files, progress->current_file);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0 TSRMLS_CC);
}
break;
case MULTIPART_EVENT_FILE_DATA: {
multipart_event_file_data *data = (multipart_event_file_data *) event_data;
if (!Z_TYPE(progress->sid) || !progress->key.c) {
break;
}
Z_LVAL_P(progress->current_file_bytes_processed) = data->offset + data->length;
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0 TSRMLS_CC);
}
break;
case MULTIPART_EVENT_FILE_END: {
multipart_event_file_end *data = (multipart_event_file_end *) event_data;
if (!Z_TYPE(progress->sid) || !progress->key.c) {
break;
}
if (data->temp_filename) {
add_assoc_string_ex(progress->current_file, "tmp_name", sizeof("tmp_name"), data->temp_filename, 1);
}
add_assoc_long_ex(progress->current_file, "error", sizeof("error"), data->cancel_upload);
add_assoc_bool_ex(progress->current_file, "done", sizeof("done"), 1);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0 TSRMLS_CC);
}
break;
case MULTIPART_EVENT_END: {
multipart_event_end *data = (multipart_event_end *) event_data;
if (Z_TYPE(progress->sid) && progress->key.c) {
if (PS(rfc1867_cleanup)) {
php_session_rfc1867_cleanup(progress TSRMLS_CC);
} else {
add_assoc_bool_ex(progress->data, "done", sizeof("done"), 1);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 1 TSRMLS_CC);
}
php_rshutdown_session_globals(TSRMLS_C);
}
if (progress->data) {
zval_ptr_dtor(&progress->data);
}
zval_dtor(&progress->sid);
smart_str_free(&progress->key);
efree(progress);
progress = NULL;
PS(rfc1867_progress) = NULL;
}
break;
}
if (progress && progress->cancel_upload) {
return FAILURE;
}
return retval;
} /* }}} */
zend_module_entry session_module_entry = {
STANDARD_MODULE_HEADER_EX,
NULL,
session_deps,
"session",
session_functions,
PHP_MINIT(session), PHP_MSHUTDOWN(session),
PHP_RINIT(session), PHP_RSHUTDOWN(session),
PHP_MINFO(session),
NO_VERSION_YET,
PHP_MODULE_GLOBALS(ps),
PHP_GINIT(ps),
NULL,
NULL,
STANDARD_MODULE_PROPERTIES_EX
};
#ifdef COMPILE_DL_SESSION
ZEND_GET_MODULE(session)
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_5255_0 |
crossvul-cpp_data_good_4069_6 | /**
* @file
* POP helper routines
*
* @authors
* Copyright (C) 2000-2003 Vsevolod Volkov <vvv@mutt.org.ua>
* Copyright (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 pop_lib POP helper routines
*
* POP helper routines
*/
#include "config.h"
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "private.h"
#include "mutt/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "init.h"
#include "mutt_account.h"
#include "mutt_logging.h"
#include "mutt_socket.h"
#include "progress.h"
#ifdef USE_SSL
#include "globals.h"
#endif
/* These Config Variables are only used in pop/pop_lib.c */
char *C_PopOauthRefreshCommand; ///< Config: (pop) External command to generate OAUTH refresh token
char *C_PopPass; ///< Config: (pop) Password of the POP server
unsigned char C_PopReconnect; ///< Config: (pop) Reconnect to the server is the connection is lost
char *C_PopUser; ///< Config: (pop) Username of the POP server
/**
* pop_get_field - Get connection login credentials - Implements ConnAccount::get_field()
*/
const char *pop_get_field(enum ConnAccountField field)
{
switch (field)
{
case MUTT_CA_LOGIN:
case MUTT_CA_USER:
return C_PopUser;
case MUTT_CA_PASS:
return C_PopPass;
case MUTT_CA_OAUTH_CMD:
return C_PopOauthRefreshCommand;
case MUTT_CA_HOST:
default:
return NULL;
}
}
/**
* pop_parse_path - Parse a POP mailbox name
* @param path Path to parse
* @param cac Account to store details
* @retval 0 success
* @retval -1 error
*
* Split a POP path into host, port, username and password
*/
int pop_parse_path(const char *path, struct ConnAccount *cac)
{
/* Defaults */
cac->flags = 0;
cac->type = MUTT_ACCT_TYPE_POP;
cac->port = 0;
cac->service = "pop";
cac->get_field = pop_get_field;
struct Url *url = url_parse(path);
if (!url || ((url->scheme != U_POP) && (url->scheme != U_POPS)) ||
!url->host || (mutt_account_fromurl(cac, url) < 0))
{
url_free(&url);
mutt_error(_("Invalid POP URL: %s"), path);
return -1;
}
if (url->scheme == U_POPS)
cac->flags |= MUTT_ACCT_SSL;
struct servent *service =
getservbyname((url->scheme == U_POP) ? "pop3" : "pop3s", "tcp");
if (cac->port == 0)
{
if (service)
cac->port = ntohs(service->s_port);
else
cac->port = (url->scheme == U_POP) ? POP_PORT : POP_SSL_PORT;
}
url_free(&url);
return 0;
}
/**
* pop_error - Copy error message to err_msg buffer
* @param adata POP Account data
* @param msg Error message to save
*/
static void pop_error(struct PopAccountData *adata, char *msg)
{
char *t = strchr(adata->err_msg, '\0');
char *c = msg;
size_t plen = mutt_str_startswith(msg, "-ERR ", CASE_MATCH);
if (plen != 0)
{
char *c2 = mutt_str_skip_email_wsp(msg + plen);
if (*c2)
c = c2;
}
mutt_str_strfcpy(t, c, sizeof(adata->err_msg) - strlen(adata->err_msg));
mutt_str_remove_trailing_ws(adata->err_msg);
}
/**
* fetch_capa - Parse CAPA output - Implements ::pop_fetch_t
* @param line List of capabilities
* @param data POP data
* @retval 0 (always)
*/
static int fetch_capa(const char *line, void *data)
{
struct PopAccountData *adata = data;
if (mutt_str_startswith(line, "SASL", CASE_IGNORE))
{
const char *c = mutt_str_skip_email_wsp(line + 4);
mutt_buffer_strcpy(&adata->auth_list, c);
}
else if (mutt_str_startswith(line, "STLS", CASE_IGNORE))
adata->cmd_stls = true;
else if (mutt_str_startswith(line, "USER", CASE_IGNORE))
adata->cmd_user = 1;
else if (mutt_str_startswith(line, "UIDL", CASE_IGNORE))
adata->cmd_uidl = 1;
else if (mutt_str_startswith(line, "TOP", CASE_IGNORE))
adata->cmd_top = 1;
return 0;
}
/**
* fetch_auth - Fetch list of the authentication mechanisms - Implements ::pop_fetch_t
* @param line List of authentication methods
* @param data POP data
* @retval 0 (always)
*/
static int fetch_auth(const char *line, void *data)
{
struct PopAccountData *adata = data;
if (!mutt_buffer_is_empty(&adata->auth_list))
{
mutt_buffer_addstr(&adata->auth_list, " ");
}
mutt_buffer_addstr(&adata->auth_list, line);
return 0;
}
/**
* pop_capabilities - Get capabilities from a POP server
* @param adata POP Account data
* @param mode Initial capabilities
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Execution error
*/
static int pop_capabilities(struct PopAccountData *adata, int mode)
{
char buf[1024];
/* don't check capabilities on reconnect */
if (adata->capabilities)
return 0;
/* init capabilities */
if (mode == 0)
{
adata->cmd_capa = false;
adata->cmd_stls = false;
adata->cmd_user = 0;
adata->cmd_uidl = 0;
adata->cmd_top = 0;
adata->resp_codes = false;
adata->expire = true;
adata->login_delay = 0;
mutt_buffer_init(&adata->auth_list);
}
/* Execute CAPA command */
if ((mode == 0) || adata->cmd_capa)
{
mutt_str_strfcpy(buf, "CAPA\r\n", sizeof(buf));
switch (pop_fetch_data(adata, buf, NULL, fetch_capa, adata))
{
case 0:
{
adata->cmd_capa = true;
break;
}
case -1:
return -1;
}
}
/* CAPA not supported, use defaults */
if ((mode == 0) && !adata->cmd_capa)
{
adata->cmd_user = 2;
adata->cmd_uidl = 2;
adata->cmd_top = 2;
mutt_str_strfcpy(buf, "AUTH\r\n", sizeof(buf));
if (pop_fetch_data(adata, buf, NULL, fetch_auth, adata) == -1)
return -1;
}
/* Check capabilities */
if (mode == 2)
{
char *msg = NULL;
if (!adata->expire)
msg = _("Unable to leave messages on server");
if (adata->cmd_top == 0)
msg = _("Command TOP is not supported by server");
if (adata->cmd_uidl == 0)
msg = _("Command UIDL is not supported by server");
if (msg && adata->cmd_capa)
{
mutt_error(msg);
return -2;
}
adata->capabilities = true;
}
return 0;
}
/**
* pop_edata_get - Get the private data for this Email
* @param e Email
* @retval ptr Private Email data
*/
struct PopEmailData *pop_edata_get(struct Email *e)
{
if (!e)
return NULL;
return e->edata;
}
/**
* pop_connect - Open connection
* @param adata POP Account data
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid response
*/
int pop_connect(struct PopAccountData *adata)
{
char buf[1024];
adata->status = POP_NONE;
if ((mutt_socket_open(adata->conn) < 0) ||
(mutt_socket_readln(buf, sizeof(buf), adata->conn) < 0))
{
mutt_error(_("Error connecting to server: %s"), adata->conn->account.host);
return -1;
}
adata->status = POP_CONNECTED;
if (!mutt_str_startswith(buf, "+OK", CASE_MATCH))
{
*adata->err_msg = '\0';
pop_error(adata, buf);
mutt_error("%s", adata->err_msg);
return -2;
}
pop_apop_timestamp(adata, buf);
return 0;
}
/**
* pop_open_connection - Open connection and authenticate
* @param adata POP Account data
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
* @retval -3 Authentication cancelled
*/
int pop_open_connection(struct PopAccountData *adata)
{
char buf[1024];
int rc = pop_connect(adata);
if (rc < 0)
return rc;
rc = pop_capabilities(adata, 0);
if (rc == -1)
goto err_conn;
if (rc == -2)
return -2;
#ifdef USE_SSL
/* Attempt STLS if available and desired. */
if (!adata->conn->ssf && (adata->cmd_stls || C_SslForceTls))
{
if (C_SslForceTls)
adata->use_stls = 2;
if (adata->use_stls == 0)
{
enum QuadOption ans =
query_quadoption(C_SslStarttls, _("Secure connection with TLS?"));
if (ans == MUTT_ABORT)
return -2;
adata->use_stls = 1;
if (ans == MUTT_YES)
adata->use_stls = 2;
}
if (adata->use_stls == 2)
{
mutt_str_strfcpy(buf, "STLS\r\n", sizeof(buf));
rc = pop_query(adata, buf, sizeof(buf));
// Clear any data after the STLS acknowledgement
mutt_socket_empty(adata->conn);
if (rc == -1)
goto err_conn;
if (rc != 0)
{
mutt_error("%s", adata->err_msg);
}
else if (mutt_ssl_starttls(adata->conn))
{
mutt_error(_("Could not negotiate TLS connection"));
return -2;
}
else
{
/* recheck capabilities after STLS completes */
rc = pop_capabilities(adata, 1);
if (rc == -1)
goto err_conn;
if (rc == -2)
return -2;
}
}
}
if (C_SslForceTls && !adata->conn->ssf)
{
mutt_error(_("Encrypted connection unavailable"));
return -2;
}
#endif
rc = pop_authenticate(adata);
if (rc == -1)
goto err_conn;
if (rc == -3)
mutt_clear_error();
if (rc != 0)
return rc;
/* recheck capabilities after authentication */
rc = pop_capabilities(adata, 2);
if (rc == -1)
goto err_conn;
if (rc == -2)
return -2;
/* get total size of mailbox */
mutt_str_strfcpy(buf, "STAT\r\n", sizeof(buf));
rc = pop_query(adata, buf, sizeof(buf));
if (rc == -1)
goto err_conn;
if (rc == -2)
{
mutt_error("%s", adata->err_msg);
return rc;
}
unsigned int n = 0, size = 0;
sscanf(buf, "+OK %u %u", &n, &size);
adata->size = size;
return 0;
err_conn:
adata->status = POP_DISCONNECTED;
mutt_error(_("Server closed connection"));
return -1;
}
/**
* pop_logout - logout from a POP server
* @param m Mailbox
*/
void pop_logout(struct Mailbox *m)
{
struct PopAccountData *adata = pop_adata_get(m);
if (adata->status == POP_CONNECTED)
{
int ret = 0;
char buf[1024];
mutt_message(_("Closing connection to POP server..."));
if (m->readonly)
{
mutt_str_strfcpy(buf, "RSET\r\n", sizeof(buf));
ret = pop_query(adata, buf, sizeof(buf));
}
if (ret != -1)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(adata, buf, sizeof(buf));
}
if (ret < 0)
mutt_debug(LL_DEBUG1, "Error closing POP connection\n");
mutt_clear_error();
}
adata->status = POP_DISCONNECTED;
}
/**
* pop_query_d - Send data from buffer and receive answer to the same buffer
* @param adata POP Account data
* @param buf Buffer to send/store data
* @param buflen Buffer length
* @param msg Progress message
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
*/
int pop_query_d(struct PopAccountData *adata, char *buf, size_t buflen, char *msg)
{
if (adata->status != POP_CONNECTED)
return -1;
/* print msg instead of real command */
if (msg)
{
mutt_debug(MUTT_SOCK_LOG_CMD, "> %s", msg);
}
mutt_socket_send_d(adata->conn, buf, MUTT_SOCK_LOG_FULL);
char *c = strpbrk(buf, " \r\n");
if (c)
*c = '\0';
snprintf(adata->err_msg, sizeof(adata->err_msg), "%s: ", buf);
if (mutt_socket_readln_d(buf, buflen, adata->conn, MUTT_SOCK_LOG_FULL) < 0)
{
adata->status = POP_DISCONNECTED;
return -1;
}
if (mutt_str_startswith(buf, "+OK", CASE_MATCH))
return 0;
pop_error(adata, buf);
return -2;
}
/**
* pop_fetch_data - Read Headers with callback function
* @param adata POP Account data
* @param query POP query to send to server
* @param progress Progress bar
* @param callback Function called for each header read
* @param data Data to pass to the callback
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
* @retval -3 Error in callback(*line, *data)
*
* This function calls callback(*line, *data) for each received line,
* callback(NULL, *data) if rewind(*data) needs, exits when fail or done.
*/
int pop_fetch_data(struct PopAccountData *adata, const char *query,
struct Progress *progress, pop_fetch_t callback, void *data)
{
char buf[1024];
long pos = 0;
size_t lenbuf = 0;
mutt_str_strfcpy(buf, query, sizeof(buf));
int rc = pop_query(adata, buf, sizeof(buf));
if (rc < 0)
return rc;
char *inbuf = mutt_mem_malloc(sizeof(buf));
while (true)
{
const int chunk =
mutt_socket_readln_d(buf, sizeof(buf), adata->conn, MUTT_SOCK_LOG_FULL);
if (chunk < 0)
{
adata->status = POP_DISCONNECTED;
rc = -1;
break;
}
char *p = buf;
if (!lenbuf && (buf[0] == '.'))
{
if (buf[1] != '.')
break;
p++;
}
mutt_str_strfcpy(inbuf + lenbuf, p, sizeof(buf));
pos += chunk;
/* cast is safe since we break out of the loop when chunk<=0 */
if ((size_t) chunk >= sizeof(buf))
{
lenbuf += strlen(p);
}
else
{
if (progress)
mutt_progress_update(progress, pos, -1);
if ((rc == 0) && (callback(inbuf, data) < 0))
rc = -3;
lenbuf = 0;
}
mutt_mem_realloc(&inbuf, lenbuf + sizeof(buf));
}
FREE(&inbuf);
return rc;
}
/**
* check_uidl - find message with this UIDL and set refno - Implements ::pop_fetch_t
* @param line String containing UIDL
* @param data POP data
* @retval 0 Success
* @retval -1 Error
*/
static int check_uidl(const char *line, void *data)
{
if (!line || !data)
return -1;
char *endp = NULL;
errno = 0;
unsigned int index = strtoul(line, &endp, 10);
if (errno != 0)
return -1;
while (*endp == ' ')
endp++;
struct Mailbox *m = data;
for (int i = 0; i < m->msg_count; i++)
{
struct PopEmailData *edata = pop_edata_get(m->emails[i]);
if (mutt_str_strcmp(edata->uid, endp) == 0)
{
edata->refno = index;
break;
}
}
return 0;
}
/**
* pop_reconnect - reconnect and verify indexes if connection was lost
* @param m Mailbox
* @retval 0 Success
* @retval -1 Error
*/
int pop_reconnect(struct Mailbox *m)
{
struct PopAccountData *adata = pop_adata_get(m);
if (adata->status == POP_CONNECTED)
return 0;
while (true)
{
mutt_socket_close(adata->conn);
int ret = pop_open_connection(adata);
if (ret == 0)
{
struct Progress progress;
mutt_progress_init(&progress, _("Verifying message indexes..."), MUTT_PROGRESS_NET, 0);
for (int i = 0; i < m->msg_count; i++)
{
struct PopEmailData *edata = pop_edata_get(m->emails[i]);
edata->refno = -1;
}
ret = pop_fetch_data(adata, "UIDL\r\n", &progress, check_uidl, m);
if (ret == -2)
{
mutt_error("%s", adata->err_msg);
}
}
if (ret == 0)
return 0;
pop_logout(m);
if (ret < -1)
return -1;
if (query_quadoption(C_PopReconnect,
_("Connection lost. Reconnect to POP server?")) != MUTT_YES)
{
return -1;
}
}
}
/**
* pop_adata_get - Get the Account data for this mailbox
* @param m Mailbox
* @retval ptr PopAccountData
*/
struct PopAccountData *pop_adata_get(struct Mailbox *m)
{
if (!m || (m->type != MUTT_POP))
return NULL;
struct Account *a = m->account;
if (!a)
return NULL;
return a->adata;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_4069_6 |
crossvul-cpp_data_good_4400_1 | /*
* Copyright (c) 2009, Natacha Porté
* Copyright (c) 2015, Vicent Marti
*
* 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 "markdown.h"
#include "html.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "houdini.h"
#define USE_XHTML(opt) (opt->flags & HTML_USE_XHTML)
int
sdhtml_is_tag(const uint8_t *tag_data, size_t tag_size, const char *tagname)
{
size_t i;
int closed = 0;
if (tag_size < 3 || tag_data[0] != '<')
return HTML_TAG_NONE;
i = 1;
if (tag_data[i] == '/') {
closed = 1;
i++;
}
for (; i < tag_size; ++i, ++tagname) {
if (*tagname == 0)
break;
if (tag_data[i] != *tagname)
return HTML_TAG_NONE;
}
if (i == tag_size)
return HTML_TAG_NONE;
if (isspace(tag_data[i]) || tag_data[i] == '>')
return closed ? HTML_TAG_CLOSE : HTML_TAG_OPEN;
return HTML_TAG_NONE;
}
static inline void escape_html(struct buf *ob, const uint8_t *source, size_t length)
{
houdini_escape_html0(ob, source, length, 0);
}
static inline void escape_href(struct buf *ob, const uint8_t *source, size_t length)
{
houdini_escape_href(ob, source, length);
}
/********************
* GENERIC RENDERER *
********************/
static int
rndr_autolink(struct buf *ob, const struct buf *link, enum mkd_autolink type, void *opaque)
{
struct html_renderopt *options = opaque;
if (!link || !link->size)
return 0;
if ((options->flags & HTML_SAFELINK) != 0 &&
!sd_autolink_issafe(link->data, link->size) &&
type != MKDA_EMAIL)
return 0;
BUFPUTSL(ob, "<a href=\"");
if (type == MKDA_EMAIL)
BUFPUTSL(ob, "mailto:");
escape_href(ob, link->data, link->size);
if (options->link_attributes) {
bufputc(ob, '\"');
options->link_attributes(ob, link, opaque);
bufputc(ob, '>');
} else {
BUFPUTSL(ob, "\">");
}
/*
* Pretty printing: if we get an email address as
* an actual URI, e.g. `mailto:foo@bar.com`, we don't
* want to print the `mailto:` prefix
*/
if (bufprefix(link, "mailto:") == 0) {
escape_html(ob, link->data + 7, link->size - 7);
} else {
escape_html(ob, link->data, link->size);
}
BUFPUTSL(ob, "</a>");
return 1;
}
static void
rndr_blockcode(struct buf *ob, const struct buf *text, const struct buf *lang, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size) bufputc(ob, '\n');
if (lang && lang->size) {
size_t i, cls;
if (options->flags & HTML_PRETTIFY) {
BUFPUTSL(ob, "<pre><code class=\"prettyprint lang-");
cls++;
} else {
BUFPUTSL(ob, "<pre><code class=\"");
}
for (i = 0, cls = 0; i < lang->size; ++i, ++cls) {
while (i < lang->size && isspace(lang->data[i]))
i++;
if (i < lang->size) {
size_t org = i;
while (i < lang->size && !isspace(lang->data[i]))
i++;
if (lang->data[org] == '.')
org++;
if (cls) bufputc(ob, ' ');
escape_html(ob, lang->data + org, i - org);
}
}
BUFPUTSL(ob, "\">");
} else if (options->flags & HTML_PRETTIFY) {
BUFPUTSL(ob, "<pre><code class=\"prettyprint\">");
} else {
BUFPUTSL(ob, "<pre><code>");
}
if (text)
escape_html(ob, text->data, text->size);
BUFPUTSL(ob, "</code></pre>\n");
}
static void
rndr_blockquote(struct buf *ob, const struct buf *text, void *opaque)
{
if (ob->size) bufputc(ob, '\n');
BUFPUTSL(ob, "<blockquote>\n");
if (text) bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</blockquote>\n");
}
static int
rndr_codespan(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
if (options->flags & HTML_PRETTIFY)
BUFPUTSL(ob, "<code class=\"prettyprint\">");
else
BUFPUTSL(ob, "<code>");
if (text) escape_html(ob, text->data, text->size);
BUFPUTSL(ob, "</code>");
return 1;
}
static int
rndr_strikethrough(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<del>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</del>");
return 1;
}
static int
rndr_double_emphasis(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<strong>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</strong>");
return 1;
}
static int
rndr_emphasis(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size) return 0;
BUFPUTSL(ob, "<em>");
if (text) bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</em>");
return 1;
}
static int
rndr_underline(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<u>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</u>");
return 1;
}
static int
rndr_highlight(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<mark>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</mark>");
return 1;
}
static int
rndr_quote(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
struct html_renderopt *options = opaque;
BUFPUTSL(ob, "<q>");
if (options->flags & HTML_ESCAPE)
escape_html(ob, text->data, text->size);
else
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</q>");
return 1;
}
static int
rndr_linebreak(struct buf *ob, void *opaque)
{
struct html_renderopt *options = opaque;
bufputs(ob, USE_XHTML(options) ? "<br/>\n" : "<br>\n");
return 1;
}
static void
rndr_header_anchor(struct buf *out, const struct buf *anchor)
{
static const char *STRIPPED = " -&+$,/:;=?@\"#{}|^~[]`\\*()%.!'";
const uint8_t *a = anchor->data;
const size_t size = anchor->size;
size_t i = 0;
int stripped = 0, inserted = 0;
for (; i < size; ++i) {
// skip html tags
if (a[i] == '<') {
while (i < size && a[i] != '>')
i++;
// skip html entities
} else if (a[i] == '&') {
while (i < size && a[i] != ';')
i++;
}
// replace non-ascii or invalid characters with dashes
else if (!isascii(a[i]) || strchr(STRIPPED, a[i])) {
if (inserted && !stripped)
bufputc(out, '-');
// and do it only once
stripped = 1;
}
else {
bufputc(out, tolower(a[i]));
stripped = 0;
inserted++;
}
}
// replace the last dash if there was anything added
if (stripped && inserted)
out->size--;
// if anchor found empty, use djb2 hash for it
if (!inserted && anchor->size) {
unsigned long hash = 5381;
for (i = 0; i < size; ++i) {
hash = ((hash << 5) + hash) + a[i]; /* h * 33 + c */
}
bufprintf(out, "part-%lx", hash);
}
}
static void
rndr_header(struct buf *ob, const struct buf *text, int level, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size)
bufputc(ob, '\n');
if ((options->flags & HTML_TOC) && level >= options->toc_data.nesting_bounds[0] &&
level <= options->toc_data.nesting_bounds[1]) {
bufprintf(ob, "<h%d id=\"", level);
rndr_header_anchor(ob, text);
BUFPUTSL(ob, "\">");
}
else
bufprintf(ob, "<h%d>", level);
if (text) bufput(ob, text->data, text->size);
bufprintf(ob, "</h%d>\n", level);
}
static int
rndr_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)
{
struct html_renderopt *options = opaque;
if (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))
return 0;
BUFPUTSL(ob, "<a href=\"");
if (link && link->size)
escape_href(ob, link->data, link->size);
if (title && title->size) {
BUFPUTSL(ob, "\" title=\"");
escape_html(ob, title->data, title->size);
}
if (options->link_attributes) {
bufputc(ob, '\"');
options->link_attributes(ob, link, opaque);
bufputc(ob, '>');
} else {
BUFPUTSL(ob, "\">");
}
if (content && content->size) bufput(ob, content->data, content->size);
BUFPUTSL(ob, "</a>");
return 1;
}
static void
rndr_list(struct buf *ob, const struct buf *text, int flags, void *opaque)
{
if (ob->size) bufputc(ob, '\n');
bufput(ob, flags & MKD_LIST_ORDERED ? "<ol>\n" : "<ul>\n", 5);
if (text) bufput(ob, text->data, text->size);
bufput(ob, flags & MKD_LIST_ORDERED ? "</ol>\n" : "</ul>\n", 6);
}
static void
rndr_listitem(struct buf *ob, const struct buf *text, int flags, void *opaque)
{
BUFPUTSL(ob, "<li>");
if (text) {
size_t size = text->size;
while (size && text->data[size - 1] == '\n')
size--;
bufput(ob, text->data, size);
}
BUFPUTSL(ob, "</li>\n");
}
static void
rndr_paragraph(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
size_t i = 0;
if (ob->size) bufputc(ob, '\n');
if (!text || !text->size)
return;
while (i < text->size && isspace(text->data[i])) i++;
if (i == text->size)
return;
BUFPUTSL(ob, "<p>");
if (options->flags & HTML_HARD_WRAP) {
size_t org;
while (i < text->size) {
org = i;
while (i < text->size && text->data[i] != '\n')
i++;
if (i > org)
bufput(ob, text->data + org, i - org);
/*
* do not insert a line break if this newline
* is the last character on the paragraph
*/
if (i >= text->size - 1)
break;
rndr_linebreak(ob, opaque);
i++;
}
} else {
bufput(ob, &text->data[i], text->size - i);
}
BUFPUTSL(ob, "</p>\n");
}
static void
rndr_raw_block(struct buf *ob, const struct buf *text, void *opaque)
{
size_t org, size;
struct html_renderopt *options = opaque;
if (!text)
return;
size = text->size;
while (size > 0 && text->data[size - 1] == '\n')
size--;
for (org = 0; org < size && text->data[org] == '\n'; ++org)
if (org >= size)
return;
/* Remove style tags if the `:no_styles` option is enabled */
if ((options->flags & HTML_SKIP_STYLE) != 0 &&
sdhtml_is_tag(text->data, size, "style"))
return;
if (ob->size)
bufputc(ob, '\n');
bufput(ob, text->data + org, size - org);
bufputc(ob, '\n');
}
static int
rndr_triple_emphasis(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size) return 0;
BUFPUTSL(ob, "<strong><em>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</em></strong>");
return 1;
}
static void
rndr_hrule(struct buf *ob, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size) bufputc(ob, '\n');
bufputs(ob, USE_XHTML(options) ? "<hr/>\n" : "<hr>\n");
}
static int
rndr_image(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *alt, void *opaque)
{
struct html_renderopt *options = opaque;
if (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))
return 0;
BUFPUTSL(ob, "<img src=\"");
if (link && link->size)
escape_href(ob, link->data, link->size);
BUFPUTSL(ob, "\" alt=\"");
if (alt && alt->size)
escape_html(ob, alt->data, alt->size);
if (title && title->size) {
BUFPUTSL(ob, "\" title=\"");
escape_html(ob, title->data, title->size);
}
bufputs(ob, USE_XHTML(options) ? "\"/>" : "\">");
return 1;
}
static int
rndr_raw_html(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
/* HTML_ESCAPE overrides SKIP_HTML, SKIP_STYLE, SKIP_LINKS and SKIP_IMAGES
It doesn't see if there are any valid tags, just escape all of them. */
if((options->flags & HTML_ESCAPE) != 0) {
escape_html(ob, text->data, text->size);
return 1;
}
if ((options->flags & HTML_SKIP_HTML) != 0)
return 1;
if ((options->flags & HTML_SKIP_STYLE) != 0 &&
sdhtml_is_tag(text->data, text->size, "style"))
return 1;
if ((options->flags & HTML_SKIP_LINKS) != 0 &&
sdhtml_is_tag(text->data, text->size, "a"))
return 1;
if ((options->flags & HTML_SKIP_IMAGES) != 0 &&
sdhtml_is_tag(text->data, text->size, "img"))
return 1;
bufput(ob, text->data, text->size);
return 1;
}
static void
rndr_table(struct buf *ob, const struct buf *header, const struct buf *body, void *opaque)
{
if (ob->size) bufputc(ob, '\n');
BUFPUTSL(ob, "<table><thead>\n");
if (header)
bufput(ob, header->data, header->size);
BUFPUTSL(ob, "</thead><tbody>\n");
if (body)
bufput(ob, body->data, body->size);
BUFPUTSL(ob, "</tbody></table>\n");
}
static void
rndr_tablerow(struct buf *ob, const struct buf *text, void *opaque)
{
BUFPUTSL(ob, "<tr>\n");
if (text)
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</tr>\n");
}
static void
rndr_tablecell(struct buf *ob, const struct buf *text, int flags, void *opaque)
{
if (flags & MKD_TABLE_HEADER) {
BUFPUTSL(ob, "<th");
} else {
BUFPUTSL(ob, "<td");
}
switch (flags & MKD_TABLE_ALIGNMASK) {
case MKD_TABLE_ALIGN_CENTER:
BUFPUTSL(ob, " style=\"text-align: center\">");
break;
case MKD_TABLE_ALIGN_L:
BUFPUTSL(ob, " style=\"text-align: left\">");
break;
case MKD_TABLE_ALIGN_R:
BUFPUTSL(ob, " style=\"text-align: right\">");
break;
default:
BUFPUTSL(ob, ">");
}
if (text)
bufput(ob, text->data, text->size);
if (flags & MKD_TABLE_HEADER) {
BUFPUTSL(ob, "</th>\n");
} else {
BUFPUTSL(ob, "</td>\n");
}
}
static int
rndr_superscript(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size) return 0;
BUFPUTSL(ob, "<sup>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</sup>");
return 1;
}
static void
rndr_normal_text(struct buf *ob, const struct buf *text, void *opaque)
{
if (text)
escape_html(ob, text->data, text->size);
}
static void
rndr_footnotes(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size) bufputc(ob, '\n');
BUFPUTSL(ob, "<div class=\"footnotes\">\n");
bufputs(ob, USE_XHTML(options) ? "<hr/>\n" : "<hr>\n");
BUFPUTSL(ob, "<ol>\n");
if (text)
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "\n</ol>\n</div>\n");
}
static void
rndr_footnote_def(struct buf *ob, const struct buf *text, unsigned int num, void *opaque)
{
size_t i = 0;
int pfound = 0;
/* insert anchor at the end of first paragraph block */
if (text) {
while ((i+3) < text->size) {
if (text->data[i++] != '<') continue;
if (text->data[i++] != '/') continue;
if (text->data[i++] != 'p' && text->data[i] != 'P') continue;
if (text->data[i] != '>') continue;
i -= 3;
pfound = 1;
break;
}
}
bufprintf(ob, "\n<li id=\"fn%d\">\n", num);
if (pfound) {
bufput(ob, text->data, i);
bufprintf(ob, " <a href=\"#fnref%d\">↩</a>", num);
bufput(ob, text->data + i, text->size - i);
} else if (text) {
bufput(ob, text->data, text->size);
}
BUFPUTSL(ob, "</li>\n");
}
static int
rndr_footnote_ref(struct buf *ob, unsigned int num, void *opaque)
{
bufprintf(ob, "<sup id=\"fnref%d\"><a href=\"#fn%d\">%d</a></sup>", num, num, num);
return 1;
}
static void
toc_header(struct buf *ob, const struct buf *text, int level, void *opaque)
{
struct html_renderopt *options = opaque;
if (level >= options->toc_data.nesting_bounds[0] &&
level <= options->toc_data.nesting_bounds[1]) {
/* set the level offset if this is the first header
* we're parsing for the document */
if (options->toc_data.current_level == 0)
options->toc_data.level_offset = level - 1;
level -= options->toc_data.level_offset;
if (level > options->toc_data.current_level) {
while (level > options->toc_data.current_level) {
BUFPUTSL(ob, "<ul>\n<li>\n");
options->toc_data.current_level++;
}
} else if (level < options->toc_data.current_level) {
BUFPUTSL(ob, "</li>\n");
while (level < options->toc_data.current_level) {
BUFPUTSL(ob, "</ul>\n</li>\n");
options->toc_data.current_level--;
}
BUFPUTSL(ob,"<li>\n");
} else {
BUFPUTSL(ob,"</li>\n<li>\n");
}
bufprintf(ob, "<a href=\"#");
rndr_header_anchor(ob, text);
BUFPUTSL(ob, "\">");
if (text) {
if (options->flags & HTML_ESCAPE)
escape_html(ob, text->data, text->size);
else
bufput(ob, text->data, text->size);
}
BUFPUTSL(ob, "</a>\n");
}
}
static int
toc_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)
{
if (content && content->size)
bufput(ob, content->data, content->size);
return 1;
}
static void
toc_finalize(struct buf *ob, void *opaque)
{
struct html_renderopt *options = opaque;
while (options->toc_data.current_level > 0) {
BUFPUTSL(ob, "</li>\n</ul>\n");
options->toc_data.current_level--;
}
}
void
sdhtml_toc_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)
{
static const struct sd_callbacks cb_default = {
NULL,
NULL,
NULL,
toc_header,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
rndr_footnotes,
rndr_footnote_def,
NULL,
rndr_codespan,
rndr_double_emphasis,
rndr_emphasis,
rndr_underline,
rndr_highlight,
rndr_quote,
NULL,
NULL,
toc_link,
NULL,
rndr_triple_emphasis,
rndr_strikethrough,
rndr_superscript,
rndr_footnote_ref,
NULL,
NULL,
NULL,
toc_finalize,
};
memset(options, 0x0, sizeof(struct html_renderopt));
options->flags = render_flags;
memcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));
}
void
sdhtml_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)
{
static const struct sd_callbacks cb_default = {
rndr_blockcode,
rndr_blockquote,
rndr_raw_block,
rndr_header,
rndr_hrule,
rndr_list,
rndr_listitem,
rndr_paragraph,
rndr_table,
rndr_tablerow,
rndr_tablecell,
rndr_footnotes,
rndr_footnote_def,
rndr_autolink,
rndr_codespan,
rndr_double_emphasis,
rndr_emphasis,
rndr_underline,
rndr_highlight,
rndr_quote,
rndr_image,
rndr_linebreak,
rndr_link,
rndr_raw_html,
rndr_triple_emphasis,
rndr_strikethrough,
rndr_superscript,
rndr_footnote_ref,
NULL,
rndr_normal_text,
NULL,
NULL,
};
/* Prepare the options pointer */
memset(options, 0x0, sizeof(struct html_renderopt));
options->flags = render_flags;
options->toc_data.nesting_bounds[0] = 1;
options->toc_data.nesting_bounds[1] = 6;
/* Prepare the callbacks */
memcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));
if (render_flags & HTML_SKIP_IMAGES)
callbacks->image = NULL;
if (render_flags & HTML_SKIP_LINKS) {
callbacks->link = NULL;
callbacks->autolink = NULL;
}
if (render_flags & HTML_SKIP_HTML || render_flags & HTML_ESCAPE)
callbacks->blockhtml = NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_4400_1 |
crossvul-cpp_data_good_5014_0 | /*
* APEI Error INJection support
*
* EINJ provides a hardware error injection mechanism, this is useful
* for debugging and testing of other APEI and RAS features.
*
* For more information about EINJ, please refer to ACPI Specification
* version 4.0, section 17.5.
*
* Copyright 2009-2010 Intel Corp.
* Author: Huang Ying <ying.huang@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/nmi.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/security.h>
#include <asm/unaligned.h>
#include "apei-internal.h"
#define EINJ_PFX "EINJ: "
#define SPIN_UNIT 100 /* 100ns */
/* Firmware should respond within 1 milliseconds */
#define FIRMWARE_TIMEOUT (1 * NSEC_PER_MSEC)
#define ACPI5_VENDOR_BIT BIT(31)
#define MEM_ERROR_MASK (ACPI_EINJ_MEMORY_CORRECTABLE | \
ACPI_EINJ_MEMORY_UNCORRECTABLE | \
ACPI_EINJ_MEMORY_FATAL)
/*
* ACPI version 5 provides a SET_ERROR_TYPE_WITH_ADDRESS action.
*/
static int acpi5;
struct set_error_type_with_address {
u32 type;
u32 vendor_extension;
u32 flags;
u32 apicid;
u64 memory_address;
u64 memory_address_range;
u32 pcie_sbdf;
};
enum {
SETWA_FLAGS_APICID = 1,
SETWA_FLAGS_MEM = 2,
SETWA_FLAGS_PCIE_SBDF = 4,
};
/*
* Vendor extensions for platform specific operations
*/
struct vendor_error_type_extension {
u32 length;
u32 pcie_sbdf;
u16 vendor_id;
u16 device_id;
u8 rev_id;
u8 reserved[3];
};
static u32 notrigger;
static u32 vendor_flags;
static struct debugfs_blob_wrapper vendor_blob;
static char vendor_dev[64];
/*
* Some BIOSes allow parameters to the SET_ERROR_TYPE entries in the
* EINJ table through an unpublished extension. Use with caution as
* most will ignore the parameter and make their own choice of address
* for error injection. This extension is used only if
* param_extension module parameter is specified.
*/
struct einj_parameter {
u64 type;
u64 reserved1;
u64 reserved2;
u64 param1;
u64 param2;
};
#define EINJ_OP_BUSY 0x1
#define EINJ_STATUS_SUCCESS 0x0
#define EINJ_STATUS_FAIL 0x1
#define EINJ_STATUS_INVAL 0x2
#define EINJ_TAB_ENTRY(tab) \
((struct acpi_whea_header *)((char *)(tab) + \
sizeof(struct acpi_table_einj)))
static bool param_extension;
module_param(param_extension, bool, 0);
static struct acpi_table_einj *einj_tab;
static struct apei_resources einj_resources;
static struct apei_exec_ins_type einj_ins_type[] = {
[ACPI_EINJ_READ_REGISTER] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_read_register,
},
[ACPI_EINJ_READ_REGISTER_VALUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_read_register_value,
},
[ACPI_EINJ_WRITE_REGISTER] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_write_register,
},
[ACPI_EINJ_WRITE_REGISTER_VALUE] = {
.flags = APEI_EXEC_INS_ACCESS_REGISTER,
.run = apei_exec_write_register_value,
},
[ACPI_EINJ_NOOP] = {
.flags = 0,
.run = apei_exec_noop,
},
};
/*
* Prevent EINJ interpreter to run simultaneously, because the
* corresponding firmware implementation may not work properly when
* invoked simultaneously.
*/
static DEFINE_MUTEX(einj_mutex);
static void *einj_param;
static void einj_exec_ctx_init(struct apei_exec_context *ctx)
{
apei_exec_ctx_init(ctx, einj_ins_type, ARRAY_SIZE(einj_ins_type),
EINJ_TAB_ENTRY(einj_tab), einj_tab->entries);
}
static int __einj_get_available_error_type(u32 *type)
{
struct apei_exec_context ctx;
int rc;
einj_exec_ctx_init(&ctx);
rc = apei_exec_run(&ctx, ACPI_EINJ_GET_ERROR_TYPE);
if (rc)
return rc;
*type = apei_exec_ctx_get_output(&ctx);
return 0;
}
/* Get error injection capabilities of the platform */
static int einj_get_available_error_type(u32 *type)
{
int rc;
mutex_lock(&einj_mutex);
rc = __einj_get_available_error_type(type);
mutex_unlock(&einj_mutex);
return rc;
}
static int einj_timedout(u64 *t)
{
if ((s64)*t < SPIN_UNIT) {
pr_warning(FW_WARN EINJ_PFX
"Firmware does not respond in time\n");
return 1;
}
*t -= SPIN_UNIT;
ndelay(SPIN_UNIT);
touch_nmi_watchdog();
return 0;
}
static void check_vendor_extension(u64 paddr,
struct set_error_type_with_address *v5param)
{
int offset = v5param->vendor_extension;
struct vendor_error_type_extension *v;
u32 sbdf;
if (!offset)
return;
v = acpi_os_map_iomem(paddr + offset, sizeof(*v));
if (!v)
return;
sbdf = v->pcie_sbdf;
sprintf(vendor_dev, "%x:%x:%x.%x vendor_id=%x device_id=%x rev_id=%x\n",
sbdf >> 24, (sbdf >> 16) & 0xff,
(sbdf >> 11) & 0x1f, (sbdf >> 8) & 0x7,
v->vendor_id, v->device_id, v->rev_id);
acpi_os_unmap_iomem(v, sizeof(*v));
}
static void *einj_get_parameter_address(void)
{
int i;
u64 pa_v4 = 0, pa_v5 = 0;
struct acpi_whea_header *entry;
entry = EINJ_TAB_ENTRY(einj_tab);
for (i = 0; i < einj_tab->entries; i++) {
if (entry->action == ACPI_EINJ_SET_ERROR_TYPE &&
entry->instruction == ACPI_EINJ_WRITE_REGISTER &&
entry->register_region.space_id ==
ACPI_ADR_SPACE_SYSTEM_MEMORY)
pa_v4 = get_unaligned(&entry->register_region.address);
if (entry->action == ACPI_EINJ_SET_ERROR_TYPE_WITH_ADDRESS &&
entry->instruction == ACPI_EINJ_WRITE_REGISTER &&
entry->register_region.space_id ==
ACPI_ADR_SPACE_SYSTEM_MEMORY)
pa_v5 = get_unaligned(&entry->register_region.address);
entry++;
}
if (pa_v5) {
struct set_error_type_with_address *v5param;
v5param = acpi_os_map_iomem(pa_v5, sizeof(*v5param));
if (v5param) {
acpi5 = 1;
check_vendor_extension(pa_v5, v5param);
return v5param;
}
}
if (param_extension && pa_v4) {
struct einj_parameter *v4param;
v4param = acpi_os_map_iomem(pa_v4, sizeof(*v4param));
if (!v4param)
return NULL;
if (v4param->reserved1 || v4param->reserved2) {
acpi_os_unmap_iomem(v4param, sizeof(*v4param));
return NULL;
}
return v4param;
}
return NULL;
}
/* do sanity check to trigger table */
static int einj_check_trigger_header(struct acpi_einj_trigger *trigger_tab)
{
if (trigger_tab->header_size != sizeof(struct acpi_einj_trigger))
return -EINVAL;
if (trigger_tab->table_size > PAGE_SIZE ||
trigger_tab->table_size < trigger_tab->header_size)
return -EINVAL;
if (trigger_tab->entry_count !=
(trigger_tab->table_size - trigger_tab->header_size) /
sizeof(struct acpi_einj_entry))
return -EINVAL;
return 0;
}
static struct acpi_generic_address *einj_get_trigger_parameter_region(
struct acpi_einj_trigger *trigger_tab, u64 param1, u64 param2)
{
int i;
struct acpi_whea_header *entry;
entry = (struct acpi_whea_header *)
((char *)trigger_tab + sizeof(struct acpi_einj_trigger));
for (i = 0; i < trigger_tab->entry_count; i++) {
if (entry->action == ACPI_EINJ_TRIGGER_ERROR &&
entry->instruction == ACPI_EINJ_WRITE_REGISTER_VALUE &&
entry->register_region.space_id ==
ACPI_ADR_SPACE_SYSTEM_MEMORY &&
(entry->register_region.address & param2) == (param1 & param2))
return &entry->register_region;
entry++;
}
return NULL;
}
/* Execute instructions in trigger error action table */
static int __einj_error_trigger(u64 trigger_paddr, u32 type,
u64 param1, u64 param2)
{
struct acpi_einj_trigger *trigger_tab = NULL;
struct apei_exec_context trigger_ctx;
struct apei_resources trigger_resources;
struct acpi_whea_header *trigger_entry;
struct resource *r;
u32 table_size;
int rc = -EIO;
struct acpi_generic_address *trigger_param_region = NULL;
r = request_mem_region(trigger_paddr, sizeof(*trigger_tab),
"APEI EINJ Trigger Table");
if (!r) {
pr_err(EINJ_PFX
"Can not request [mem %#010llx-%#010llx] for Trigger table\n",
(unsigned long long)trigger_paddr,
(unsigned long long)trigger_paddr +
sizeof(*trigger_tab) - 1);
goto out;
}
trigger_tab = ioremap_cache(trigger_paddr, sizeof(*trigger_tab));
if (!trigger_tab) {
pr_err(EINJ_PFX "Failed to map trigger table!\n");
goto out_rel_header;
}
rc = einj_check_trigger_header(trigger_tab);
if (rc) {
pr_warning(FW_BUG EINJ_PFX
"The trigger error action table is invalid\n");
goto out_rel_header;
}
/* No action structures in the TRIGGER_ERROR table, nothing to do */
if (!trigger_tab->entry_count)
goto out_rel_header;
rc = -EIO;
table_size = trigger_tab->table_size;
r = request_mem_region(trigger_paddr + sizeof(*trigger_tab),
table_size - sizeof(*trigger_tab),
"APEI EINJ Trigger Table");
if (!r) {
pr_err(EINJ_PFX
"Can not request [mem %#010llx-%#010llx] for Trigger Table Entry\n",
(unsigned long long)trigger_paddr + sizeof(*trigger_tab),
(unsigned long long)trigger_paddr + table_size - 1);
goto out_rel_header;
}
iounmap(trigger_tab);
trigger_tab = ioremap_cache(trigger_paddr, table_size);
if (!trigger_tab) {
pr_err(EINJ_PFX "Failed to map trigger table!\n");
goto out_rel_entry;
}
trigger_entry = (struct acpi_whea_header *)
((char *)trigger_tab + sizeof(struct acpi_einj_trigger));
apei_resources_init(&trigger_resources);
apei_exec_ctx_init(&trigger_ctx, einj_ins_type,
ARRAY_SIZE(einj_ins_type),
trigger_entry, trigger_tab->entry_count);
rc = apei_exec_collect_resources(&trigger_ctx, &trigger_resources);
if (rc)
goto out_fini;
rc = apei_resources_sub(&trigger_resources, &einj_resources);
if (rc)
goto out_fini;
/*
* Some firmware will access target address specified in
* param1 to trigger the error when injecting memory error.
* This will cause resource conflict with regular memory. So
* remove it from trigger table resources.
*/
if ((param_extension || acpi5) && (type & MEM_ERROR_MASK) && param2) {
struct apei_resources addr_resources;
apei_resources_init(&addr_resources);
trigger_param_region = einj_get_trigger_parameter_region(
trigger_tab, param1, param2);
if (trigger_param_region) {
rc = apei_resources_add(&addr_resources,
trigger_param_region->address,
trigger_param_region->bit_width/8, true);
if (rc)
goto out_fini;
rc = apei_resources_sub(&trigger_resources,
&addr_resources);
}
apei_resources_fini(&addr_resources);
if (rc)
goto out_fini;
}
rc = apei_resources_request(&trigger_resources, "APEI EINJ Trigger");
if (rc)
goto out_fini;
rc = apei_exec_pre_map_gars(&trigger_ctx);
if (rc)
goto out_release;
rc = apei_exec_run(&trigger_ctx, ACPI_EINJ_TRIGGER_ERROR);
apei_exec_post_unmap_gars(&trigger_ctx);
out_release:
apei_resources_release(&trigger_resources);
out_fini:
apei_resources_fini(&trigger_resources);
out_rel_entry:
release_mem_region(trigger_paddr + sizeof(*trigger_tab),
table_size - sizeof(*trigger_tab));
out_rel_header:
release_mem_region(trigger_paddr, sizeof(*trigger_tab));
out:
if (trigger_tab)
iounmap(trigger_tab);
return rc;
}
static int __einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,
u64 param3, u64 param4)
{
struct apei_exec_context ctx;
u64 val, trigger_paddr, timeout = FIRMWARE_TIMEOUT;
int rc;
einj_exec_ctx_init(&ctx);
rc = apei_exec_run_optional(&ctx, ACPI_EINJ_BEGIN_OPERATION);
if (rc)
return rc;
apei_exec_ctx_set_input(&ctx, type);
if (acpi5) {
struct set_error_type_with_address *v5param = einj_param;
v5param->type = type;
if (type & ACPI5_VENDOR_BIT) {
switch (vendor_flags) {
case SETWA_FLAGS_APICID:
v5param->apicid = param1;
break;
case SETWA_FLAGS_MEM:
v5param->memory_address = param1;
v5param->memory_address_range = param2;
break;
case SETWA_FLAGS_PCIE_SBDF:
v5param->pcie_sbdf = param1;
break;
}
v5param->flags = vendor_flags;
} else if (flags) {
v5param->flags = flags;
v5param->memory_address = param1;
v5param->memory_address_range = param2;
v5param->apicid = param3;
v5param->pcie_sbdf = param4;
} else {
switch (type) {
case ACPI_EINJ_PROCESSOR_CORRECTABLE:
case ACPI_EINJ_PROCESSOR_UNCORRECTABLE:
case ACPI_EINJ_PROCESSOR_FATAL:
v5param->apicid = param1;
v5param->flags = SETWA_FLAGS_APICID;
break;
case ACPI_EINJ_MEMORY_CORRECTABLE:
case ACPI_EINJ_MEMORY_UNCORRECTABLE:
case ACPI_EINJ_MEMORY_FATAL:
v5param->memory_address = param1;
v5param->memory_address_range = param2;
v5param->flags = SETWA_FLAGS_MEM;
break;
case ACPI_EINJ_PCIX_CORRECTABLE:
case ACPI_EINJ_PCIX_UNCORRECTABLE:
case ACPI_EINJ_PCIX_FATAL:
v5param->pcie_sbdf = param1;
v5param->flags = SETWA_FLAGS_PCIE_SBDF;
break;
}
}
} else {
rc = apei_exec_run(&ctx, ACPI_EINJ_SET_ERROR_TYPE);
if (rc)
return rc;
if (einj_param) {
struct einj_parameter *v4param = einj_param;
v4param->param1 = param1;
v4param->param2 = param2;
}
}
rc = apei_exec_run(&ctx, ACPI_EINJ_EXECUTE_OPERATION);
if (rc)
return rc;
for (;;) {
rc = apei_exec_run(&ctx, ACPI_EINJ_CHECK_BUSY_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
if (!(val & EINJ_OP_BUSY))
break;
if (einj_timedout(&timeout))
return -EIO;
}
rc = apei_exec_run(&ctx, ACPI_EINJ_GET_COMMAND_STATUS);
if (rc)
return rc;
val = apei_exec_ctx_get_output(&ctx);
if (val != EINJ_STATUS_SUCCESS)
return -EBUSY;
rc = apei_exec_run(&ctx, ACPI_EINJ_GET_TRIGGER_TABLE);
if (rc)
return rc;
trigger_paddr = apei_exec_ctx_get_output(&ctx);
if (notrigger == 0) {
rc = __einj_error_trigger(trigger_paddr, type, param1, param2);
if (rc)
return rc;
}
rc = apei_exec_run_optional(&ctx, ACPI_EINJ_END_OPERATION);
return rc;
}
/* Inject the specified hardware error */
static int einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,
u64 param3, u64 param4)
{
int rc;
u64 base_addr, size;
if (get_securelevel() > 0)
return -EPERM;
/* If user manually set "flags", make sure it is legal */
if (flags && (flags &
~(SETWA_FLAGS_APICID|SETWA_FLAGS_MEM|SETWA_FLAGS_PCIE_SBDF)))
return -EINVAL;
/*
* We need extra sanity checks for memory errors.
* Other types leap directly to injection.
*/
/* ensure param1/param2 existed */
if (!(param_extension || acpi5))
goto inject;
/* ensure injection is memory related */
if (type & ACPI5_VENDOR_BIT) {
if (vendor_flags != SETWA_FLAGS_MEM)
goto inject;
} else if (!(type & MEM_ERROR_MASK) && !(flags & SETWA_FLAGS_MEM))
goto inject;
/*
* Disallow crazy address masks that give BIOS leeway to pick
* injection address almost anywhere. Insist on page or
* better granularity and that target address is normal RAM or
* NVDIMM.
*/
base_addr = param1 & param2;
size = ~param2 + 1;
if (((param2 & PAGE_MASK) != PAGE_MASK) ||
((region_intersects(base_addr, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE)
!= REGION_INTERSECTS) &&
(region_intersects(base_addr, size, IORESOURCE_MEM, IORES_DESC_PERSISTENT_MEMORY)
!= REGION_INTERSECTS)))
return -EINVAL;
inject:
mutex_lock(&einj_mutex);
rc = __einj_error_inject(type, flags, param1, param2, param3, param4);
mutex_unlock(&einj_mutex);
return rc;
}
static u32 error_type;
static u32 error_flags;
static u64 error_param1;
static u64 error_param2;
static u64 error_param3;
static u64 error_param4;
static struct dentry *einj_debug_dir;
static int available_error_type_show(struct seq_file *m, void *v)
{
int rc;
u32 available_error_type = 0;
rc = einj_get_available_error_type(&available_error_type);
if (rc)
return rc;
if (available_error_type & 0x0001)
seq_printf(m, "0x00000001\tProcessor Correctable\n");
if (available_error_type & 0x0002)
seq_printf(m, "0x00000002\tProcessor Uncorrectable non-fatal\n");
if (available_error_type & 0x0004)
seq_printf(m, "0x00000004\tProcessor Uncorrectable fatal\n");
if (available_error_type & 0x0008)
seq_printf(m, "0x00000008\tMemory Correctable\n");
if (available_error_type & 0x0010)
seq_printf(m, "0x00000010\tMemory Uncorrectable non-fatal\n");
if (available_error_type & 0x0020)
seq_printf(m, "0x00000020\tMemory Uncorrectable fatal\n");
if (available_error_type & 0x0040)
seq_printf(m, "0x00000040\tPCI Express Correctable\n");
if (available_error_type & 0x0080)
seq_printf(m, "0x00000080\tPCI Express Uncorrectable non-fatal\n");
if (available_error_type & 0x0100)
seq_printf(m, "0x00000100\tPCI Express Uncorrectable fatal\n");
if (available_error_type & 0x0200)
seq_printf(m, "0x00000200\tPlatform Correctable\n");
if (available_error_type & 0x0400)
seq_printf(m, "0x00000400\tPlatform Uncorrectable non-fatal\n");
if (available_error_type & 0x0800)
seq_printf(m, "0x00000800\tPlatform Uncorrectable fatal\n");
return 0;
}
static int available_error_type_open(struct inode *inode, struct file *file)
{
return single_open(file, available_error_type_show, NULL);
}
static const struct file_operations available_error_type_fops = {
.open = available_error_type_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int error_type_get(void *data, u64 *val)
{
*val = error_type;
return 0;
}
static int error_type_set(void *data, u64 val)
{
int rc;
u32 available_error_type = 0;
u32 tval, vendor;
/*
* Vendor defined types have 0x80000000 bit set, and
* are not enumerated by ACPI_EINJ_GET_ERROR_TYPE
*/
vendor = val & ACPI5_VENDOR_BIT;
tval = val & 0x7fffffff;
/* Only one error type can be specified */
if (tval & (tval - 1))
return -EINVAL;
if (!vendor) {
rc = einj_get_available_error_type(&available_error_type);
if (rc)
return rc;
if (!(val & available_error_type))
return -EINVAL;
}
error_type = val;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(error_type_fops, error_type_get,
error_type_set, "0x%llx\n");
static int error_inject_set(void *data, u64 val)
{
if (!error_type)
return -EINVAL;
return einj_error_inject(error_type, error_flags, error_param1, error_param2,
error_param3, error_param4);
}
DEFINE_SIMPLE_ATTRIBUTE(error_inject_fops, NULL,
error_inject_set, "%llu\n");
static int einj_check_table(struct acpi_table_einj *einj_tab)
{
if ((einj_tab->header_length !=
(sizeof(struct acpi_table_einj) - sizeof(einj_tab->header)))
&& (einj_tab->header_length != sizeof(struct acpi_table_einj)))
return -EINVAL;
if (einj_tab->header.length < sizeof(struct acpi_table_einj))
return -EINVAL;
if (einj_tab->entries !=
(einj_tab->header.length - sizeof(struct acpi_table_einj)) /
sizeof(struct acpi_einj_entry))
return -EINVAL;
return 0;
}
static int __init einj_init(void)
{
int rc;
acpi_status status;
struct dentry *fentry;
struct apei_exec_context ctx;
if (acpi_disabled)
return -ENODEV;
status = acpi_get_table(ACPI_SIG_EINJ, 0,
(struct acpi_table_header **)&einj_tab);
if (status == AE_NOT_FOUND)
return -ENODEV;
else if (ACPI_FAILURE(status)) {
const char *msg = acpi_format_exception(status);
pr_err(EINJ_PFX "Failed to get table, %s\n", msg);
return -EINVAL;
}
rc = einj_check_table(einj_tab);
if (rc) {
pr_warning(FW_BUG EINJ_PFX "EINJ table is invalid\n");
return -EINVAL;
}
rc = -ENOMEM;
einj_debug_dir = debugfs_create_dir("einj", apei_get_debugfs_dir());
if (!einj_debug_dir)
goto err_cleanup;
fentry = debugfs_create_file("available_error_type", S_IRUSR,
einj_debug_dir, NULL,
&available_error_type_fops);
if (!fentry)
goto err_cleanup;
fentry = debugfs_create_file("error_type", S_IRUSR | S_IWUSR,
einj_debug_dir, NULL, &error_type_fops);
if (!fentry)
goto err_cleanup;
fentry = debugfs_create_file("error_inject", S_IWUSR,
einj_debug_dir, NULL, &error_inject_fops);
if (!fentry)
goto err_cleanup;
apei_resources_init(&einj_resources);
einj_exec_ctx_init(&ctx);
rc = apei_exec_collect_resources(&ctx, &einj_resources);
if (rc)
goto err_fini;
rc = apei_resources_request(&einj_resources, "APEI EINJ");
if (rc)
goto err_fini;
rc = apei_exec_pre_map_gars(&ctx);
if (rc)
goto err_release;
rc = -ENOMEM;
einj_param = einj_get_parameter_address();
if ((param_extension || acpi5) && einj_param) {
fentry = debugfs_create_x32("flags", S_IRUSR | S_IWUSR,
einj_debug_dir, &error_flags);
if (!fentry)
goto err_unmap;
fentry = debugfs_create_x64("param1", S_IRUSR | S_IWUSR,
einj_debug_dir, &error_param1);
if (!fentry)
goto err_unmap;
fentry = debugfs_create_x64("param2", S_IRUSR | S_IWUSR,
einj_debug_dir, &error_param2);
if (!fentry)
goto err_unmap;
fentry = debugfs_create_x64("param3", S_IRUSR | S_IWUSR,
einj_debug_dir, &error_param3);
if (!fentry)
goto err_unmap;
fentry = debugfs_create_x64("param4", S_IRUSR | S_IWUSR,
einj_debug_dir, &error_param4);
if (!fentry)
goto err_unmap;
fentry = debugfs_create_x32("notrigger", S_IRUSR | S_IWUSR,
einj_debug_dir, ¬rigger);
if (!fentry)
goto err_unmap;
}
if (vendor_dev[0]) {
vendor_blob.data = vendor_dev;
vendor_blob.size = strlen(vendor_dev);
fentry = debugfs_create_blob("vendor", S_IRUSR,
einj_debug_dir, &vendor_blob);
if (!fentry)
goto err_unmap;
fentry = debugfs_create_x32("vendor_flags", S_IRUSR | S_IWUSR,
einj_debug_dir, &vendor_flags);
if (!fentry)
goto err_unmap;
}
pr_info(EINJ_PFX "Error INJection is initialized.\n");
return 0;
err_unmap:
if (einj_param) {
acpi_size size = (acpi5) ?
sizeof(struct set_error_type_with_address) :
sizeof(struct einj_parameter);
acpi_os_unmap_iomem(einj_param, size);
}
apei_exec_post_unmap_gars(&ctx);
err_release:
apei_resources_release(&einj_resources);
err_fini:
apei_resources_fini(&einj_resources);
err_cleanup:
debugfs_remove_recursive(einj_debug_dir);
return rc;
}
static void __exit einj_exit(void)
{
struct apei_exec_context ctx;
if (einj_param) {
acpi_size size = (acpi5) ?
sizeof(struct set_error_type_with_address) :
sizeof(struct einj_parameter);
acpi_os_unmap_iomem(einj_param, size);
}
einj_exec_ctx_init(&ctx);
apei_exec_post_unmap_gars(&ctx);
apei_resources_release(&einj_resources);
apei_resources_fini(&einj_resources);
debugfs_remove_recursive(einj_debug_dir);
}
module_init(einj_init);
module_exit(einj_exit);
MODULE_AUTHOR("Huang Ying");
MODULE_DESCRIPTION("APEI Error INJection support");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_5014_0 |
crossvul-cpp_data_good_4069_5 | /**
* @file
* Usenet network mailbox type; talk to an NNTP server
*
* @authors
* Copyright (C) 1998 Brandon Long <blong@fiction.net>
* Copyright (C) 1999 Andrej Gritsenko <andrej@lucky.net>
* Copyright (C) 2000-2017 Vsevolod Volkov <vvv@mutt.org.ua>
* Copyright (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 nntp_nntp Usenet network mailbox type; talk to an NNTP server
*
* Usenet network mailbox type; talk to an NNTP server
*/
#include "config.h"
#include <ctype.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include "private.h"
#include "mutt/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "gui/lib.h"
#include "lib.h"
#include "globals.h"
#include "hook.h"
#include "init.h"
#include "mutt_logging.h"
#include "mutt_parse.h"
#include "mutt_socket.h"
#include "muttlib.h"
#include "mx.h"
#include "progress.h"
#include "sort.h"
#include "bcache/lib.h"
#include "hcache/lib.h"
#include "ncrypt/lib.h"
#ifdef USE_HCACHE
#include "protos.h"
#endif
#ifdef USE_SASL
#include <sasl/sasl.h>
#include <sasl/saslutil.h>
#endif
#if defined(USE_SSL) || defined(USE_HCACHE)
#include "mutt.h"
#endif
struct stat;
/* These Config Variables are only used in nntp/nntp.c */
char *C_NntpAuthenticators; ///< Config: (nntp) Allowed authentication methods
short C_NntpContext; ///< Config: (nntp) Maximum number of articles to list (0 for all articles)
bool C_NntpListgroup; ///< Config: (nntp) Check all articles when opening a newsgroup
bool C_NntpLoadDescription; ///< Config: (nntp) Load descriptions for newsgroups when adding to the list
short C_NntpPoll; ///< Config: (nntp) Interval between checks for new posts
bool C_ShowNewNews; ///< Config: (nntp) Check for new newsgroups when entering the browser
struct NntpAccountData *CurrentNewsSrv;
const char *OverviewFmt = "Subject:\0"
"From:\0"
"Date:\0"
"Message-ID:\0"
"References:\0"
"Content-Length:\0"
"Lines:\0"
"\0";
/**
* struct FetchCtx - Keep track when getting data from a server
*/
struct FetchCtx
{
struct Mailbox *mailbox;
anum_t first;
anum_t last;
bool restore;
unsigned char *messages;
struct Progress progress;
header_cache_t *hc;
};
/**
* struct ChildCtx - Keep track of the children of an article
*/
struct ChildCtx
{
struct Mailbox *mailbox;
unsigned int num;
unsigned int max;
anum_t *child;
};
/**
* nntp_adata_free - Free data attached to the Mailbox
* @param[out] ptr NNTP data
*
* The NntpAccountData struct stores global NNTP data, such as the connection to
* the database. This function will close the database, free the resources and
* the struct itself.
*/
static void nntp_adata_free(void **ptr)
{
if (!ptr || !*ptr)
return;
struct NntpAccountData *adata = *ptr;
mutt_file_fclose(&adata->fp_newsrc);
FREE(&adata->newsrc_file);
FREE(&adata->authenticators);
FREE(&adata->overview_fmt);
FREE(&adata->conn);
FREE(&adata->groups_list);
mutt_hash_free(&adata->groups_hash);
FREE(ptr);
}
/**
* nntp_hashelem_free - Free our hash table data - Implements ::hash_hdata_free_t
*/
static void nntp_hashelem_free(int type, void *obj, intptr_t data)
{
nntp_mdata_free(&obj);
}
/**
* nntp_adata_new - Allocate and initialise a new NntpAccountData structure
* @param conn Network connection
* @retval ptr New NntpAccountData
*/
struct NntpAccountData *nntp_adata_new(struct Connection *conn)
{
struct NntpAccountData *adata = mutt_mem_calloc(1, sizeof(struct NntpAccountData));
adata->conn = conn;
adata->groups_hash = mutt_hash_new(1009, MUTT_HASH_NO_FLAGS);
mutt_hash_set_destructor(adata->groups_hash, nntp_hashelem_free, 0);
adata->groups_max = 16;
adata->groups_list =
mutt_mem_malloc(adata->groups_max * sizeof(struct NntpMboxData *));
return adata;
}
#if 0
/**
* nntp_adata_get - Get the Account data for this mailbox
* @retval ptr Private Account data
*/
struct NntpAccountData *nntp_adata_get(struct Mailbox *m)
{
if (!m || (m->type != MUTT_NNTP))
return NULL;
struct Account *a = m->account;
if (!a)
return NULL;
return a->adata;
}
#endif
/**
* nntp_mdata_free - Free NntpMboxData, used to destroy hash elements
* @param[out] ptr NNTP data
*/
void nntp_mdata_free(void **ptr)
{
if (!ptr || !*ptr)
return;
struct NntpMboxData *mdata = *ptr;
nntp_acache_free(mdata);
mutt_bcache_close(&mdata->bcache);
FREE(&mdata->newsrc_ent);
FREE(&mdata->desc);
FREE(ptr);
}
/**
* nntp_edata_free - Free data attached to an Email
* @param[out] ptr Email data
*/
static void nntp_edata_free(void **ptr)
{
// struct NntpEmailData *edata = *ptr;
FREE(ptr);
}
/**
* nntp_edata_new - Create a new NntpEmailData for an Email
* @retval ptr New NntpEmailData struct
*/
static struct NntpEmailData *nntp_edata_new(void)
{
return mutt_mem_calloc(1, sizeof(struct NntpEmailData));
}
/**
* nntp_edata_get - Get the private data for this Email
* @param e Email
* @retval ptr Private Email data
*/
struct NntpEmailData *nntp_edata_get(struct Email *e)
{
if (!e)
return NULL;
return e->edata;
}
/**
* nntp_connect_error - Signal a failed connection
* @param adata NNTP server
* @retval -1 Always
*/
static int nntp_connect_error(struct NntpAccountData *adata)
{
adata->status = NNTP_NONE;
mutt_error(_("Server closed connection"));
return -1;
}
/**
* nntp_capabilities - Get capabilities
* @param adata NNTP server
* @retval -1 Error, connection is closed
* @retval 0 Mode is reader, capabilities set up
* @retval 1 Need to switch to reader mode
*/
static int nntp_capabilities(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
bool mode_reader = false;
char buf[1024];
char authinfo[1024] = { 0 };
adata->hasCAPABILITIES = false;
adata->hasSTARTTLS = false;
adata->hasDATE = false;
adata->hasLIST_NEWSGROUPS = false;
adata->hasLISTGROUP = false;
adata->hasLISTGROUPrange = false;
adata->hasOVER = false;
FREE(&adata->authenticators);
if ((mutt_socket_send(conn, "CAPABILITIES\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
/* no capabilities */
if (!mutt_str_startswith(buf, "101", CASE_MATCH))
return 1;
adata->hasCAPABILITIES = true;
/* parse capabilities */
do
{
size_t plen = 0;
if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
return nntp_connect_error(adata);
if (mutt_str_strcmp("STARTTLS", buf) == 0)
adata->hasSTARTTLS = true;
else if (mutt_str_strcmp("MODE-READER", buf) == 0)
mode_reader = true;
else if (mutt_str_strcmp("READER", buf) == 0)
{
adata->hasDATE = true;
adata->hasLISTGROUP = true;
adata->hasLISTGROUPrange = true;
}
else if ((plen = mutt_str_startswith(buf, "AUTHINFO ", CASE_MATCH)))
{
mutt_str_strcat(buf, sizeof(buf), " ");
mutt_str_strfcpy(authinfo, buf + plen - 1, sizeof(authinfo));
}
#ifdef USE_SASL
else if ((plen = mutt_str_startswith(buf, "SASL ", CASE_MATCH)))
{
char *p = buf + plen;
while (*p == ' ')
p++;
adata->authenticators = mutt_str_strdup(p);
}
#endif
else if (mutt_str_strcmp("OVER", buf) == 0)
adata->hasOVER = true;
else if (mutt_str_startswith(buf, "LIST ", CASE_MATCH))
{
char *p = strstr(buf, " NEWSGROUPS");
if (p)
{
p += 11;
if ((*p == '\0') || (*p == ' '))
adata->hasLIST_NEWSGROUPS = true;
}
}
} while (mutt_str_strcmp(".", buf) != 0);
*buf = '\0';
#ifdef USE_SASL
if (adata->authenticators && strcasestr(authinfo, " SASL "))
mutt_str_strfcpy(buf, adata->authenticators, sizeof(buf));
#endif
if (strcasestr(authinfo, " USER "))
{
if (*buf != '\0')
mutt_str_strcat(buf, sizeof(buf), " ");
mutt_str_strcat(buf, sizeof(buf), "USER");
}
mutt_str_replace(&adata->authenticators, buf);
/* current mode is reader */
if (adata->hasDATE)
return 0;
/* server is mode-switching, need to switch to reader mode */
if (mode_reader)
return 1;
mutt_socket_close(conn);
adata->status = NNTP_BYE;
mutt_error(_("Server doesn't support reader mode"));
return -1;
}
/**
* nntp_attempt_features - Detect supported commands
* @param adata NNTP server
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_attempt_features(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
char buf[1024];
/* no CAPABILITIES, trying DATE, LISTGROUP, LIST NEWSGROUPS */
if (!adata->hasCAPABILITIES)
{
if ((mutt_socket_send(conn, "DATE\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasDATE = true;
if ((mutt_socket_send(conn, "LISTGROUP\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasLISTGROUP = true;
if ((mutt_socket_send(conn, "LIST NEWSGROUPS +\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasLIST_NEWSGROUPS = true;
if (mutt_str_startswith(buf, "215", CASE_MATCH))
{
do
{
if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
return nntp_connect_error(adata);
} while (mutt_str_strcmp(".", buf) != 0);
}
}
/* no LIST NEWSGROUPS, trying XGTITLE */
if (!adata->hasLIST_NEWSGROUPS)
{
if ((mutt_socket_send(conn, "XGTITLE\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasXGTITLE = true;
}
/* no OVER, trying XOVER */
if (!adata->hasOVER)
{
if ((mutt_socket_send(conn, "XOVER\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
adata->hasXOVER = true;
}
/* trying LIST OVERVIEW.FMT */
if (adata->hasOVER || adata->hasXOVER)
{
if ((mutt_socket_send(conn, "LIST OVERVIEW.FMT\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "215", CASE_MATCH))
adata->overview_fmt = mutt_str_strdup(OverviewFmt);
else
{
bool cont = false;
size_t buflen = 2048, off = 0, b = 0;
FREE(&adata->overview_fmt);
adata->overview_fmt = mutt_mem_malloc(buflen);
while (true)
{
if ((buflen - off) < 1024)
{
buflen *= 2;
mutt_mem_realloc(&adata->overview_fmt, buflen);
}
const int chunk = mutt_socket_readln_d(adata->overview_fmt + off,
buflen - off, conn, MUTT_SOCK_LOG_HDR);
if (chunk < 0)
{
FREE(&adata->overview_fmt);
return nntp_connect_error(adata);
}
if (!cont && (mutt_str_strcmp(".", adata->overview_fmt + off) == 0))
break;
cont = (chunk >= (buflen - off));
off += strlen(adata->overview_fmt + off);
if (!cont)
{
if (adata->overview_fmt[b] == ':')
{
memmove(adata->overview_fmt + b, adata->overview_fmt + b + 1, off - b - 1);
adata->overview_fmt[off - 1] = ':';
}
char *colon = strchr(adata->overview_fmt + b, ':');
if (!colon)
adata->overview_fmt[off++] = ':';
else if (strcmp(colon + 1, "full") != 0)
off = colon + 1 - adata->overview_fmt;
if (strcasecmp(adata->overview_fmt + b, "Bytes:") == 0)
{
size_t len = strlen(adata->overview_fmt + b);
mutt_str_strfcpy(adata->overview_fmt + b, "Content-Length:", len + 1);
off = b + len;
}
adata->overview_fmt[off++] = '\0';
b = off;
}
}
adata->overview_fmt[off++] = '\0';
mutt_mem_realloc(&adata->overview_fmt, off);
}
}
return 0;
}
#ifdef USE_SASL
/**
* nntp_memchr - look for a char in a binary buf, conveniently
* @param haystack [in/out] input: start here, output: store address of hit
* @param sentinel points just beyond (1 byte after) search area
* @param needle the character to search for
* @retval true found and updated haystack
* @retval false not found
*/
static bool nntp_memchr(char **haystack, char *sentinel, int needle)
{
char *start = *haystack;
size_t max_offset = sentinel - start;
void *vp = memchr(start, max_offset, needle);
if (!vp)
return false;
*haystack = vp;
return true;
}
/**
* nntp_log_binbuf - log a buffer possibly containing NUL bytes
* @param buf source buffer
* @param len how many bytes from buf
* @param pfx logging prefix (protocol etc.)
* @param dbg which loglevel does message belong
*/
static void nntp_log_binbuf(const char *buf, size_t len, const char *pfx, int dbg)
{
char tmp[1024];
char *p = tmp;
char *sentinel = tmp + len;
if (C_DebugLevel < dbg)
return;
memcpy(tmp, buf, len);
tmp[len] = '\0';
while (nntp_memchr(&p, sentinel, '\0'))
*p = '.';
mutt_debug(dbg, "%s> %s\n", pfx, tmp);
}
#endif
/**
* nntp_auth - Get login, password and authenticate
* @param adata NNTP server
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_auth(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
char buf[1024];
char authenticators[1024] = "USER";
char *method = NULL, *a = NULL, *p = NULL;
unsigned char flags = conn->account.flags;
while (true)
{
/* get login and password */
if ((mutt_account_getuser(&conn->account) < 0) || (conn->account.user[0] == '\0') ||
(mutt_account_getpass(&conn->account) < 0) || (conn->account.pass[0] == '\0'))
{
break;
}
/* get list of authenticators */
if (C_NntpAuthenticators)
mutt_str_strfcpy(authenticators, C_NntpAuthenticators, sizeof(authenticators));
else if (adata->hasCAPABILITIES)
{
mutt_str_strfcpy(authenticators, adata->authenticators, sizeof(authenticators));
p = authenticators;
while (*p)
{
if (*p == ' ')
*p = ':';
p++;
}
}
p = authenticators;
while (*p)
{
*p = toupper(*p);
p++;
}
mutt_debug(LL_DEBUG1, "available methods: %s\n", adata->authenticators);
a = authenticators;
while (true)
{
if (!a)
{
mutt_error(_("No authenticators available"));
break;
}
method = a;
a = strchr(a, ':');
if (a)
*a++ = '\0';
/* check authenticator */
if (adata->hasCAPABILITIES)
{
char *m = NULL;
if (!adata->authenticators)
continue;
m = strcasestr(adata->authenticators, method);
if (!m)
continue;
if ((m > adata->authenticators) && (*(m - 1) != ' '))
continue;
m += strlen(method);
if ((*m != '\0') && (*m != ' '))
continue;
}
mutt_debug(LL_DEBUG1, "trying method %s\n", method);
/* AUTHINFO USER authentication */
if (strcmp(method, "USER") == 0)
{
mutt_message(_("Authenticating (%s)..."), method);
snprintf(buf, sizeof(buf), "AUTHINFO USER %s\r\n", conn->account.user);
if ((mutt_socket_send(conn, buf) < 0) ||
(mutt_socket_readln_d(buf, sizeof(buf), conn, MUTT_SOCK_LOG_FULL) < 0))
{
break;
}
/* authenticated, password is not required */
if (mutt_str_startswith(buf, "281", CASE_MATCH))
return 0;
/* username accepted, sending password */
if (mutt_str_startswith(buf, "381", CASE_MATCH))
{
mutt_debug(MUTT_SOCK_LOG_FULL, "%d> AUTHINFO PASS *\n", conn->fd);
snprintf(buf, sizeof(buf), "AUTHINFO PASS %s\r\n", conn->account.pass);
if ((mutt_socket_send_d(conn, buf, MUTT_SOCK_LOG_FULL) < 0) ||
(mutt_socket_readln_d(buf, sizeof(buf), conn, MUTT_SOCK_LOG_FULL) < 0))
{
break;
}
/* authenticated */
if (mutt_str_startswith(buf, "281", CASE_MATCH))
return 0;
}
/* server doesn't support AUTHINFO USER, trying next method */
if (*buf == '5')
continue;
}
else
{
#ifdef USE_SASL
sasl_conn_t *saslconn = NULL;
sasl_interact_t *interaction = NULL;
int rc;
char inbuf[1024] = { 0 };
const char *mech = NULL;
const char *client_out = NULL;
unsigned int client_len, len;
if (mutt_sasl_client_new(conn, &saslconn) < 0)
{
mutt_debug(LL_DEBUG1, "error allocating SASL connection\n");
continue;
}
while (true)
{
rc = sasl_client_start(saslconn, method, &interaction, &client_out,
&client_len, &mech);
if (rc != SASL_INTERACT)
break;
mutt_sasl_interact(interaction);
}
if ((rc != SASL_OK) && (rc != SASL_CONTINUE))
{
sasl_dispose(&saslconn);
mutt_debug(LL_DEBUG1,
"error starting SASL authentication exchange\n");
continue;
}
mutt_message(_("Authenticating (%s)..."), method);
snprintf(buf, sizeof(buf), "AUTHINFO SASL %s", method);
/* looping protocol */
while ((rc == SASL_CONTINUE) || ((rc == SASL_OK) && client_len))
{
/* send out client response */
if (client_len)
{
nntp_log_binbuf(client_out, client_len, "SASL", MUTT_SOCK_LOG_FULL);
if (*buf != '\0')
mutt_str_strcat(buf, sizeof(buf), " ");
len = strlen(buf);
if (sasl_encode64(client_out, client_len, buf + len,
sizeof(buf) - len, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "error base64-encoding client response\n");
break;
}
}
mutt_str_strcat(buf, sizeof(buf), "\r\n");
if (strchr(buf, ' '))
{
mutt_debug(MUTT_SOCK_LOG_CMD, "%d> AUTHINFO SASL %s%s\n", conn->fd,
method, client_len ? " sasl_data" : "");
}
else
mutt_debug(MUTT_SOCK_LOG_CMD, "%d> sasl_data\n", conn->fd);
client_len = 0;
if ((mutt_socket_send_d(conn, buf, MUTT_SOCK_LOG_FULL) < 0) ||
(mutt_socket_readln_d(inbuf, sizeof(inbuf), conn, MUTT_SOCK_LOG_FULL) < 0))
{
break;
}
if (!mutt_str_startswith(inbuf, "283 ", CASE_MATCH) &&
!mutt_str_startswith(inbuf, "383 ", CASE_MATCH))
{
mutt_debug(MUTT_SOCK_LOG_FULL, "%d< %s\n", conn->fd, inbuf);
break;
}
inbuf[3] = '\0';
mutt_debug(MUTT_SOCK_LOG_FULL, "%d< %s sasl_data\n", conn->fd, inbuf);
if (strcmp("=", inbuf + 4) == 0)
len = 0;
else if (sasl_decode64(inbuf + 4, strlen(inbuf + 4), buf,
sizeof(buf) - 1, &len) != SASL_OK)
{
mutt_debug(LL_DEBUG1, "error base64-decoding server response\n");
break;
}
else
nntp_log_binbuf(buf, len, "SASL", MUTT_SOCK_LOG_FULL);
while (true)
{
rc = sasl_client_step(saslconn, buf, len, &interaction, &client_out, &client_len);
if (rc != SASL_INTERACT)
break;
mutt_sasl_interact(interaction);
}
if (*inbuf != '3')
break;
*buf = '\0';
} /* looping protocol */
if ((rc == SASL_OK) && (client_len == 0) && (*inbuf == '2'))
{
mutt_sasl_setup_conn(conn, saslconn);
return 0;
}
/* terminate SASL session */
sasl_dispose(&saslconn);
if (conn->fd < 0)
break;
if (mutt_str_startswith(inbuf, "383 ", CASE_MATCH))
{
if ((mutt_socket_send(conn, "*\r\n") < 0) ||
(mutt_socket_readln(inbuf, sizeof(inbuf), conn) < 0))
{
break;
}
}
/* server doesn't support AUTHINFO SASL, trying next method */
if (*inbuf == '5')
continue;
#else
continue;
#endif /* USE_SASL */
}
mutt_error(_("%s authentication failed"), method);
break;
}
break;
}
/* error */
adata->status = NNTP_BYE;
conn->account.flags = flags;
if (conn->fd < 0)
{
mutt_error(_("Server closed connection"));
}
else
mutt_socket_close(conn);
return -1;
}
/**
* nntp_query - Send data from buffer and receive answer to same buffer
* @param mdata NNTP Mailbox data
* @param line Buffer containing data
* @param linelen Length of buffer
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_query(struct NntpMboxData *mdata, char *line, size_t linelen)
{
struct NntpAccountData *adata = mdata->adata;
char buf[1024] = { 0 };
if (adata->status == NNTP_BYE)
return -1;
while (true)
{
if (adata->status == NNTP_OK)
{
int rc = 0;
if (*line)
rc = mutt_socket_send(adata->conn, line);
else if (mdata->group)
{
snprintf(buf, sizeof(buf), "GROUP %s\r\n", mdata->group);
rc = mutt_socket_send(adata->conn, buf);
}
if (rc >= 0)
rc = mutt_socket_readln(buf, sizeof(buf), adata->conn);
if (rc >= 0)
break;
}
/* reconnect */
while (true)
{
adata->status = NNTP_NONE;
if (nntp_open_connection(adata) == 0)
break;
snprintf(buf, sizeof(buf), _("Connection to %s lost. Reconnect?"),
adata->conn->account.host);
if (mutt_yesorno(buf, MUTT_YES) != MUTT_YES)
{
adata->status = NNTP_BYE;
return -1;
}
}
/* select newsgroup after reconnection */
if (mdata->group)
{
snprintf(buf, sizeof(buf), "GROUP %s\r\n", mdata->group);
if ((mutt_socket_send(adata->conn, buf) < 0) ||
(mutt_socket_readln(buf, sizeof(buf), adata->conn) < 0))
{
return nntp_connect_error(adata);
}
}
if (*line == '\0')
break;
}
mutt_str_strfcpy(line, buf, linelen);
return 0;
}
/**
* nntp_fetch_lines - Read lines, calling a callback function for each
* @param mdata NNTP Mailbox data
* @param query Query to match
* @param qlen Length of query
* @param msg Progress message (OPTIONAL)
* @param func Callback function
* @param data Data for callback function
* @retval 0 Success
* @retval 1 Bad response (answer in query buffer)
* @retval -1 Connection lost
* @retval -2 Error in func(*line, *data)
*
* This function calls func(*line, *data) for each received line,
* func(NULL, *data) if rewind(*data) needs, exits when fail or done:
*/
static int nntp_fetch_lines(struct NntpMboxData *mdata, char *query, size_t qlen,
const char *msg, int (*func)(char *, void *), void *data)
{
bool done = false;
int rc;
while (!done)
{
char buf[1024];
char *line = NULL;
unsigned int lines = 0;
size_t off = 0;
struct Progress progress;
if (msg)
mutt_progress_init(&progress, msg, MUTT_PROGRESS_READ, 0);
mutt_str_strfcpy(buf, query, sizeof(buf));
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
return -1;
if (buf[0] != '2')
{
mutt_str_strfcpy(query, buf, qlen);
return 1;
}
line = mutt_mem_malloc(sizeof(buf));
rc = 0;
while (true)
{
char *p = NULL;
int chunk = mutt_socket_readln_d(buf, sizeof(buf), mdata->adata->conn, MUTT_SOCK_LOG_FULL);
if (chunk < 0)
{
mdata->adata->status = NNTP_NONE;
break;
}
p = buf;
if (!off && (buf[0] == '.'))
{
if (buf[1] == '\0')
{
done = true;
break;
}
if (buf[1] == '.')
p++;
}
mutt_str_strfcpy(line + off, p, sizeof(buf));
if (chunk >= sizeof(buf))
off += strlen(p);
else
{
if (msg)
mutt_progress_update(&progress, ++lines, -1);
if ((rc == 0) && (func(line, data) < 0))
rc = -2;
off = 0;
}
mutt_mem_realloc(&line, off + sizeof(buf));
}
FREE(&line);
func(NULL, data);
}
return rc;
}
/**
* fetch_description - Parse newsgroup description
* @param line String to parse
* @param data NNTP Server
* @retval 0 Always
*/
static int fetch_description(char *line, void *data)
{
if (!line)
return 0;
struct NntpAccountData *adata = data;
char *desc = strpbrk(line, " \t");
if (desc)
{
*desc++ = '\0';
desc += strspn(desc, " \t");
}
else
desc = strchr(line, '\0');
struct NntpMboxData *mdata = mutt_hash_find(adata->groups_hash, line);
if (mdata && (mutt_str_strcmp(desc, mdata->desc) != 0))
{
mutt_str_replace(&mdata->desc, desc);
mutt_debug(LL_DEBUG2, "group: %s, desc: %s\n", line, desc);
}
return 0;
}
/**
* get_description - Fetch newsgroups descriptions
* @param mdata NNTP Mailbox data
* @param wildmat String to match
* @param msg Progress message
* @retval 0 Success
* @retval 1 Bad response (answer in query buffer)
* @retval -1 Connection lost
* @retval -2 Error
*/
static int get_description(struct NntpMboxData *mdata, const char *wildmat, const char *msg)
{
char buf[256];
const char *cmd = NULL;
/* get newsgroup description, if possible */
struct NntpAccountData *adata = mdata->adata;
if (!wildmat)
wildmat = mdata->group;
if (adata->hasLIST_NEWSGROUPS)
cmd = "LIST NEWSGROUPS";
else if (adata->hasXGTITLE)
cmd = "XGTITLE";
else
return 0;
snprintf(buf, sizeof(buf), "%s %s\r\n", cmd, wildmat);
int rc = nntp_fetch_lines(mdata, buf, sizeof(buf), msg, fetch_description, adata);
if (rc > 0)
{
mutt_error("%s: %s", cmd, buf);
}
return rc;
}
/**
* nntp_parse_xref - Parse cross-reference
* @param m Mailbox
* @param e Email
*
* Update read flag and set article number if empty
*/
static void nntp_parse_xref(struct Mailbox *m, struct Email *e)
{
struct NntpMboxData *mdata = m->mdata;
char *buf = mutt_str_strdup(e->env->xref);
char *p = buf;
while (p)
{
anum_t anum;
/* skip to next word */
p += strspn(p, " \t");
char *grp = p;
/* skip to end of word */
p = strpbrk(p, " \t");
if (p)
*p++ = '\0';
/* find colon */
char *colon = strchr(grp, ':');
if (!colon)
continue;
*colon++ = '\0';
if (sscanf(colon, ANUM, &anum) != 1)
continue;
nntp_article_status(m, e, grp, anum);
if (!nntp_edata_get(e)->article_num && (mutt_str_strcmp(mdata->group, grp) == 0))
nntp_edata_get(e)->article_num = anum;
}
FREE(&buf);
}
/**
* fetch_tempfile - Write line to temporary file
* @param line Text to write
* @param data FILE pointer
* @retval 0 Success
* @retval -1 Failure
*/
static int fetch_tempfile(char *line, void *data)
{
FILE *fp = data;
if (!line)
rewind(fp);
else if ((fputs(line, fp) == EOF) || (fputc('\n', fp) == EOF))
return -1;
return 0;
}
/**
* fetch_numbers - Parse article number
* @param line Article number
* @param data FetchCtx
* @retval 0 Always
*/
static int fetch_numbers(char *line, void *data)
{
struct FetchCtx *fc = data;
anum_t anum;
if (!line)
return 0;
if (sscanf(line, ANUM, &anum) != 1)
return 0;
if ((anum < fc->first) || (anum > fc->last))
return 0;
fc->messages[anum - fc->first] = 1;
return 0;
}
/**
* parse_overview_line - Parse overview line
* @param line String to parse
* @param data FetchCtx
* @retval 0 Success
* @retval -1 Failure
*/
static int parse_overview_line(char *line, void *data)
{
if (!line || !data)
return 0;
struct FetchCtx *fc = data;
struct Mailbox *m = fc->mailbox;
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct Email *e = NULL;
char *header = NULL, *field = NULL;
bool save = true;
anum_t anum;
/* parse article number */
field = strchr(line, '\t');
if (field)
*field++ = '\0';
if (sscanf(line, ANUM, &anum) != 1)
return 0;
mutt_debug(LL_DEBUG2, "" ANUM "\n", anum);
/* out of bounds */
if ((anum < fc->first) || (anum > fc->last))
return 0;
/* not in LISTGROUP */
if (!fc->messages[anum - fc->first])
{
/* progress */
if (m->verbose)
mutt_progress_update(&fc->progress, anum - fc->first + 1, -1);
return 0;
}
/* convert overview line to header */
FILE *fp = mutt_file_mkstemp();
if (!fp)
return -1;
header = mdata->adata->overview_fmt;
while (field)
{
char *b = field;
if (*header)
{
if (!strstr(header, ":full") && (fputs(header, fp) == EOF))
{
mutt_file_fclose(&fp);
return -1;
}
header = strchr(header, '\0') + 1;
}
field = strchr(field, '\t');
if (field)
*field++ = '\0';
if ((fputs(b, fp) == EOF) || (fputc('\n', fp) == EOF))
{
mutt_file_fclose(&fp);
return -1;
}
}
rewind(fp);
/* allocate memory for headers */
if (m->msg_count >= m->email_max)
mx_alloc_memory(m);
/* parse header */
m->emails[m->msg_count] = email_new();
e = m->emails[m->msg_count];
e->env = mutt_rfc822_read_header(fp, e, false, false);
e->env->newsgroups = mutt_str_strdup(mdata->group);
e->received = e->date_sent;
mutt_file_fclose(&fp);
#ifdef USE_HCACHE
if (fc->hc)
{
char buf[16];
/* try to replace with header from cache */
snprintf(buf, sizeof(buf), "%u", anum);
struct HCacheEntry hce = mutt_hcache_fetch(fc->hc, buf, strlen(buf), 0);
if (hce.email)
{
mutt_debug(LL_DEBUG2, "mutt_hcache_fetch %s\n", buf);
email_free(&e);
e = hce.email;
m->emails[m->msg_count] = e;
e->edata = NULL;
e->read = false;
e->old = false;
/* skip header marked as deleted in cache */
if (e->deleted && !fc->restore)
{
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
save = false;
}
}
/* not cached yet, store header */
else
{
mutt_debug(LL_DEBUG2, "mutt_hcache_store %s\n", buf);
mutt_hcache_store(fc->hc, buf, strlen(buf), e, 0);
}
}
#endif
if (save)
{
e->index = m->msg_count++;
e->read = false;
e->old = false;
e->deleted = false;
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
nntp_edata_get(e)->article_num = anum;
if (fc->restore)
e->changed = true;
else
{
nntp_article_status(m, e, NULL, anum);
if (!e->read)
nntp_parse_xref(m, e);
}
if (anum > mdata->last_loaded)
mdata->last_loaded = anum;
}
else
email_free(&e);
/* progress */
if (m->verbose)
mutt_progress_update(&fc->progress, anum - fc->first + 1, -1);
return 0;
}
/**
* nntp_fetch_headers - Fetch headers
* @param m Mailbox
* @param hc Header cache
* @param first Number of first header to fetch
* @param last Number of last header to fetch
* @param restore Restore message listed as deleted
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_fetch_headers(struct Mailbox *m, void *hc, anum_t first, anum_t last, bool restore)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct FetchCtx fc;
struct Email *e = NULL;
char buf[8192];
int rc = 0;
anum_t current;
anum_t first_over = first;
/* if empty group or nothing to do */
if (!last || (first > last))
return 0;
/* init fetch context */
fc.mailbox = m;
fc.first = first;
fc.last = last;
fc.restore = restore;
fc.messages = mutt_mem_calloc(last - first + 1, sizeof(unsigned char));
if (!fc.messages)
return -1;
fc.hc = hc;
/* fetch list of articles */
if (C_NntpListgroup && mdata->adata->hasLISTGROUP && !mdata->deleted)
{
if (m->verbose)
mutt_message(_("Fetching list of articles..."));
if (mdata->adata->hasLISTGROUPrange)
snprintf(buf, sizeof(buf), "LISTGROUP %s %u-%u\r\n", mdata->group, first, last);
else
snprintf(buf, sizeof(buf), "LISTGROUP %s\r\n", mdata->group);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_numbers, &fc);
if (rc > 0)
{
mutt_error("LISTGROUP: %s", buf);
}
if (rc == 0)
{
for (current = first; current <= last && rc == 0; current++)
{
if (fc.messages[current - first])
continue;
snprintf(buf, sizeof(buf), "%u", current);
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "#1 mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
#ifdef USE_HCACHE
if (fc.hc)
{
mutt_debug(LL_DEBUG2, "mutt_hcache_delete_header %s\n", buf);
mutt_hcache_delete_header(fc.hc, buf, strlen(buf));
}
#endif
}
}
}
else
{
for (current = first; current <= last; current++)
fc.messages[current - first] = 1;
}
/* fetching header from cache or server, or fallback to fetch overview */
if (m->verbose)
{
mutt_progress_init(&fc.progress, _("Fetching message headers..."),
MUTT_PROGRESS_READ, last - first + 1);
}
for (current = first; current <= last && rc == 0; current++)
{
if (m->verbose)
mutt_progress_update(&fc.progress, current - first + 1, -1);
#ifdef USE_HCACHE
snprintf(buf, sizeof(buf), "%u", current);
#endif
/* delete header from cache that does not exist on server */
if (!fc.messages[current - first])
continue;
/* allocate memory for headers */
if (m->msg_count >= m->email_max)
mx_alloc_memory(m);
#ifdef USE_HCACHE
/* try to fetch header from cache */
struct HCacheEntry hce = mutt_hcache_fetch(fc.hc, buf, strlen(buf), 0);
if (hce.email)
{
mutt_debug(LL_DEBUG2, "mutt_hcache_fetch %s\n", buf);
e = hce.email;
m->emails[m->msg_count] = e;
e->edata = NULL;
/* skip header marked as deleted in cache */
if (e->deleted && !restore)
{
email_free(&e);
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "#2 mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
continue;
}
e->read = false;
e->old = false;
}
else
#endif
if (mdata->deleted)
{
/* don't try to fetch header from removed newsgroup */
continue;
}
/* fallback to fetch overview */
else if (mdata->adata->hasOVER || mdata->adata->hasXOVER)
{
if (C_NntpListgroup && mdata->adata->hasLISTGROUP)
break;
else
continue;
}
/* fetch header from server */
else
{
FILE *fp = mutt_file_mkstemp();
if (!fp)
{
mutt_perror(_("Can't create temporary file"));
rc = -1;
break;
}
snprintf(buf, sizeof(buf), "HEAD %u\r\n", current);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_tempfile, fp);
if (rc)
{
mutt_file_fclose(&fp);
if (rc < 0)
break;
/* invalid response */
if (!mutt_str_startswith(buf, "423", CASE_MATCH))
{
mutt_error("HEAD: %s", buf);
break;
}
/* no such article */
if (mdata->bcache)
{
snprintf(buf, sizeof(buf), "%u", current);
mutt_debug(LL_DEBUG2, "#3 mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
rc = 0;
continue;
}
/* parse header */
m->emails[m->msg_count] = email_new();
e = m->emails[m->msg_count];
e->env = mutt_rfc822_read_header(fp, e, false, false);
e->received = e->date_sent;
mutt_file_fclose(&fp);
}
/* save header in context */
e->index = m->msg_count++;
e->read = false;
e->old = false;
e->deleted = false;
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
nntp_edata_get(e)->article_num = current;
if (restore)
e->changed = true;
else
{
nntp_article_status(m, e, NULL, nntp_edata_get(e)->article_num);
if (!e->read)
nntp_parse_xref(m, e);
}
if (current > mdata->last_loaded)
mdata->last_loaded = current;
first_over = current + 1;
}
if (!C_NntpListgroup || !mdata->adata->hasLISTGROUP)
current = first_over;
/* fetch overview information */
if ((current <= last) && (rc == 0) && !mdata->deleted)
{
char *cmd = mdata->adata->hasOVER ? "OVER" : "XOVER";
snprintf(buf, sizeof(buf), "%s %u-%u\r\n", cmd, current, last);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, parse_overview_line, &fc);
if (rc > 0)
{
mutt_error("%s: %s", cmd, buf);
}
}
FREE(&fc.messages);
if (rc != 0)
return -1;
mutt_clear_error();
return 0;
}
/**
* nntp_group_poll - Check newsgroup for new articles
* @param mdata NNTP Mailbox data
* @param update_stat Update the stats?
* @retval 1 New articles found
* @retval 0 No change
* @retval -1 Lost connection
*/
static int nntp_group_poll(struct NntpMboxData *mdata, bool update_stat)
{
char buf[1024] = { 0 };
anum_t count, first, last;
/* use GROUP command to poll newsgroup */
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
return -1;
if (sscanf(buf, "211 " ANUM " " ANUM " " ANUM, &count, &first, &last) != 3)
return 0;
if ((first == mdata->first_message) && (last == mdata->last_message))
return 0;
/* articles have been renumbered */
if (last < mdata->last_message)
{
mdata->last_cached = 0;
if (mdata->newsrc_len)
{
mutt_mem_realloc(&mdata->newsrc_ent, sizeof(struct NewsrcEntry));
mdata->newsrc_len = 1;
mdata->newsrc_ent[0].first = 1;
mdata->newsrc_ent[0].last = 0;
}
}
mdata->first_message = first;
mdata->last_message = last;
if (!update_stat)
return 1;
/* update counters */
else if (!last || (!mdata->newsrc_ent && !mdata->last_cached))
mdata->unread = count;
else
nntp_group_unread_stat(mdata);
return 1;
}
/**
* check_mailbox - Check current newsgroup for new articles
* @param m Mailbox
* @retval #MUTT_REOPENED Articles have been renumbered or removed from server
* @retval #MUTT_NEW_MAIL New articles found
* @retval 0 No change
* @retval -1 Lost connection
*
* Leave newsrc locked
*/
static int check_mailbox(struct Mailbox *m)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct NntpAccountData *adata = mdata->adata;
time_t now = mutt_date_epoch();
int rc = 0;
void *hc = NULL;
if (adata->check_time + C_NntpPoll > now)
return 0;
mutt_message(_("Checking for new messages..."));
if (nntp_newsrc_parse(adata) < 0)
return -1;
adata->check_time = now;
int rc2 = nntp_group_poll(mdata, false);
if (rc2 < 0)
{
nntp_newsrc_close(adata);
return -1;
}
if (rc2 != 0)
nntp_active_save_cache(adata);
/* articles have been renumbered, remove all headers */
if (mdata->last_message < mdata->last_loaded)
{
for (int i = 0; i < m->msg_count; i++)
email_free(&m->emails[i]);
m->msg_count = 0;
m->msg_tagged = 0;
if (mdata->last_message < mdata->last_loaded)
{
mdata->last_loaded = mdata->first_message - 1;
if (C_NntpContext && (mdata->last_message - mdata->last_loaded > C_NntpContext))
mdata->last_loaded = mdata->last_message - C_NntpContext;
}
rc = MUTT_REOPENED;
}
/* .newsrc has been externally modified */
if (adata->newsrc_modified)
{
#ifdef USE_HCACHE
unsigned char *messages = NULL;
char buf[16];
struct Email *e = NULL;
anum_t first = mdata->first_message;
if (C_NntpContext && (mdata->last_message - first + 1 > C_NntpContext))
first = mdata->last_message - C_NntpContext + 1;
messages = mutt_mem_calloc(mdata->last_loaded - first + 1, sizeof(unsigned char));
hc = nntp_hcache_open(mdata);
nntp_hcache_update(mdata, hc);
#endif
/* update flags according to .newsrc */
int j = 0;
for (int i = 0; i < m->msg_count; i++)
{
if (!m->emails[i])
continue;
bool flagged = false;
anum_t anum = nntp_edata_get(m->emails[i])->article_num;
#ifdef USE_HCACHE
/* check hcache for flagged and deleted flags */
if (hc)
{
if ((anum >= first) && (anum <= mdata->last_loaded))
messages[anum - first] = 1;
snprintf(buf, sizeof(buf), "%u", anum);
struct HCacheEntry hce = mutt_hcache_fetch(hc, buf, strlen(buf), 0);
if (hce.email)
{
bool deleted;
mutt_debug(LL_DEBUG2, "#1 mutt_hcache_fetch %s\n", buf);
e = hce.email;
e->edata = NULL;
deleted = e->deleted;
flagged = e->flagged;
email_free(&e);
/* header marked as deleted, removing from context */
if (deleted)
{
mutt_set_flag(m, m->emails[i], MUTT_TAG, false);
email_free(&m->emails[i]);
continue;
}
}
}
#endif
if (!m->emails[i]->changed)
{
m->emails[i]->flagged = flagged;
m->emails[i]->read = false;
m->emails[i]->old = false;
nntp_article_status(m, m->emails[i], NULL, anum);
if (!m->emails[i]->read)
nntp_parse_xref(m, m->emails[i]);
}
m->emails[j++] = m->emails[i];
}
#ifdef USE_HCACHE
m->msg_count = j;
/* restore headers without "deleted" flag */
for (anum_t anum = first; anum <= mdata->last_loaded; anum++)
{
if (messages[anum - first])
continue;
snprintf(buf, sizeof(buf), "%u", anum);
struct HCacheEntry hce = mutt_hcache_fetch(hc, buf, strlen(buf), 0);
if (hce.email)
{
mutt_debug(LL_DEBUG2, "#2 mutt_hcache_fetch %s\n", buf);
if (m->msg_count >= m->email_max)
mx_alloc_memory(m);
e = hce.email;
m->emails[m->msg_count] = e;
e->edata = NULL;
if (e->deleted)
{
email_free(&e);
if (mdata->bcache)
{
mutt_debug(LL_DEBUG2, "mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
continue;
}
m->msg_count++;
e->read = false;
e->old = false;
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
nntp_edata_get(e)->article_num = anum;
nntp_article_status(m, e, NULL, anum);
if (!e->read)
nntp_parse_xref(m, e);
}
}
FREE(&messages);
#endif
adata->newsrc_modified = false;
rc = MUTT_REOPENED;
}
/* some headers were removed, context must be updated */
if (rc == MUTT_REOPENED)
mailbox_changed(m, NT_MAILBOX_INVALID);
/* fetch headers of new articles */
if (mdata->last_message > mdata->last_loaded)
{
int oldmsgcount = m->msg_count;
bool verbose = m->verbose;
m->verbose = false;
#ifdef USE_HCACHE
if (!hc)
{
hc = nntp_hcache_open(mdata);
nntp_hcache_update(mdata, hc);
}
#endif
int old_msg_count = m->msg_count;
rc2 = nntp_fetch_headers(m, hc, mdata->last_loaded + 1, mdata->last_message, false);
m->verbose = verbose;
if (rc2 == 0)
{
if (m->msg_count > old_msg_count)
mailbox_changed(m, NT_MAILBOX_INVALID);
mdata->last_loaded = mdata->last_message;
}
if ((rc == 0) && (m->msg_count > oldmsgcount))
rc = MUTT_NEW_MAIL;
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (rc)
nntp_newsrc_close(adata);
mutt_clear_error();
return rc;
}
/**
* nntp_date - Get date and time from server
* @param adata NNTP server
* @param now Server time
* @retval 0 Success
* @retval -1 Failure
*/
static int nntp_date(struct NntpAccountData *adata, time_t *now)
{
if (adata->hasDATE)
{
struct NntpMboxData mdata = { 0 };
char buf[1024];
struct tm tm = { 0 };
mdata.adata = adata;
mdata.group = NULL;
mutt_str_strfcpy(buf, "DATE\r\n", sizeof(buf));
if (nntp_query(&mdata, buf, sizeof(buf)) < 0)
return -1;
if (sscanf(buf, "111 %4d%2d%2d%2d%2d%2d%*s", &tm.tm_year, &tm.tm_mon,
&tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6)
{
tm.tm_year -= 1900;
tm.tm_mon--;
*now = timegm(&tm);
if (*now >= 0)
{
mutt_debug(LL_DEBUG1, "server time is %lu\n", *now);
return 0;
}
}
}
*now = mutt_date_epoch();
return 0;
}
/**
* fetch_children - Parse XPAT line
* @param line String to parse
* @param data ChildCtx
* @retval 0 Always
*/
static int fetch_children(char *line, void *data)
{
struct ChildCtx *cc = data;
anum_t anum;
if (!line || (sscanf(line, ANUM, &anum) != 1))
return 0;
for (unsigned int i = 0; i < cc->mailbox->msg_count; i++)
{
struct Email *e = cc->mailbox->emails[i];
if (!e)
break;
if (nntp_edata_get(e)->article_num == anum)
return 0;
}
if (cc->num >= cc->max)
{
cc->max *= 2;
mutt_mem_realloc(&cc->child, sizeof(anum_t) * cc->max);
}
cc->child[cc->num++] = anum;
return 0;
}
/**
* nntp_open_connection - Connect to server, authenticate and get capabilities
* @param adata NNTP server
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_open_connection(struct NntpAccountData *adata)
{
struct Connection *conn = adata->conn;
char buf[256];
int cap;
bool posting = false, auth = true;
if (adata->status == NNTP_OK)
return 0;
if (adata->status == NNTP_BYE)
return -1;
adata->status = NNTP_NONE;
if (mutt_socket_open(conn) < 0)
return -1;
if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)
return nntp_connect_error(adata);
if (mutt_str_startswith(buf, "200", CASE_MATCH))
posting = true;
else if (!mutt_str_startswith(buf, "201", CASE_MATCH))
{
mutt_socket_close(conn);
mutt_str_remove_trailing_ws(buf);
mutt_error("%s", buf);
return -1;
}
/* get initial capabilities */
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
/* tell news server to switch to mode reader if it isn't so */
if (cap > 0)
{
if ((mutt_socket_send(conn, "MODE READER\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (mutt_str_startswith(buf, "200", CASE_MATCH))
posting = true;
else if (mutt_str_startswith(buf, "201", CASE_MATCH))
posting = false;
/* error if has capabilities, ignore result if no capabilities */
else if (adata->hasCAPABILITIES)
{
mutt_socket_close(conn);
mutt_error(_("Could not switch to reader mode"));
return -1;
}
/* recheck capabilities after MODE READER */
if (adata->hasCAPABILITIES)
{
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
}
}
mutt_message(_("Connected to %s. %s"), conn->account.host,
posting ? _("Posting is ok") : _("Posting is NOT ok"));
mutt_sleep(1);
#ifdef USE_SSL
/* Attempt STARTTLS if available and desired. */
if ((adata->use_tls != 1) && (adata->hasSTARTTLS || C_SslForceTls))
{
if (adata->use_tls == 0)
{
adata->use_tls =
C_SslForceTls || query_quadoption(C_SslStarttls,
_("Secure connection with TLS?")) == MUTT_YES ?
2 :
1;
}
if (adata->use_tls == 2)
{
if ((mutt_socket_send(conn, "STARTTLS\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
// Clear any data after the STARTTLS acknowledgement
mutt_socket_empty(conn);
if (!mutt_str_startswith(buf, "382", CASE_MATCH))
{
adata->use_tls = 0;
mutt_error("STARTTLS: %s", buf);
}
else if (mutt_ssl_starttls(conn))
{
adata->use_tls = 0;
adata->status = NNTP_NONE;
mutt_socket_close(adata->conn);
mutt_error(_("Could not negotiate TLS connection"));
return -1;
}
else
{
/* recheck capabilities after STARTTLS */
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
}
}
}
#endif
/* authentication required? */
if (conn->account.flags & MUTT_ACCT_USER)
{
if (!conn->account.user[0])
auth = false;
}
else
{
if ((mutt_socket_send(conn, "STAT\r\n") < 0) ||
(mutt_socket_readln(buf, sizeof(buf), conn) < 0))
{
return nntp_connect_error(adata);
}
if (!mutt_str_startswith(buf, "480", CASE_MATCH))
auth = false;
}
/* authenticate */
if (auth && (nntp_auth(adata) < 0))
return -1;
/* get final capabilities after authentication */
if (adata->hasCAPABILITIES && (auth || (cap > 0)))
{
cap = nntp_capabilities(adata);
if (cap < 0)
return -1;
if (cap > 0)
{
mutt_socket_close(conn);
mutt_error(_("Could not switch to reader mode"));
return -1;
}
}
/* attempt features */
if (nntp_attempt_features(adata) < 0)
return -1;
adata->status = NNTP_OK;
return 0;
}
/**
* nntp_post - Post article
* @param m Mailbox
* @param msg Message to post
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_post(struct Mailbox *m, const char *msg)
{
struct NntpMboxData *mdata = NULL;
struct NntpMboxData tmp_mdata = { 0 };
char buf[1024];
if (m && (m->type == MUTT_NNTP))
mdata = m->mdata;
else
{
CurrentNewsSrv = nntp_select_server(m, C_NewsServer, false);
if (!CurrentNewsSrv)
return -1;
mdata = &tmp_mdata;
mdata->adata = CurrentNewsSrv;
mdata->group = NULL;
}
FILE *fp = mutt_file_fopen(msg, "r");
if (!fp)
{
mutt_perror(msg);
return -1;
}
mutt_str_strfcpy(buf, "POST\r\n", sizeof(buf));
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
{
mutt_file_fclose(&fp);
return -1;
}
if (buf[0] != '3')
{
mutt_error(_("Can't post article: %s"), buf);
mutt_file_fclose(&fp);
return -1;
}
buf[0] = '.';
buf[1] = '\0';
while (fgets(buf + 1, sizeof(buf) - 2, fp))
{
size_t len = strlen(buf);
if (buf[len - 1] == '\n')
{
buf[len - 1] = '\r';
buf[len] = '\n';
len++;
buf[len] = '\0';
}
if (mutt_socket_send_d(mdata->adata->conn, (buf[1] == '.') ? buf : buf + 1,
MUTT_SOCK_LOG_FULL) < 0)
{
mutt_file_fclose(&fp);
return nntp_connect_error(mdata->adata);
}
}
mutt_file_fclose(&fp);
if (((buf[strlen(buf) - 1] != '\n') &&
(mutt_socket_send_d(mdata->adata->conn, "\r\n", MUTT_SOCK_LOG_FULL) < 0)) ||
(mutt_socket_send_d(mdata->adata->conn, ".\r\n", MUTT_SOCK_LOG_FULL) < 0) ||
(mutt_socket_readln(buf, sizeof(buf), mdata->adata->conn) < 0))
{
return nntp_connect_error(mdata->adata);
}
if (buf[0] != '2')
{
mutt_error(_("Can't post article: %s"), buf);
return -1;
}
return 0;
}
/**
* nntp_active_fetch - Fetch list of all newsgroups from server
* @param adata NNTP server
* @param mark_new Mark the groups as new
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_active_fetch(struct NntpAccountData *adata, bool mark_new)
{
struct NntpMboxData tmp_mdata = { 0 };
char msg[256];
char buf[1024];
unsigned int i;
int rc;
snprintf(msg, sizeof(msg), _("Loading list of groups from server %s..."),
adata->conn->account.host);
mutt_message(msg);
if (nntp_date(adata, &adata->newgroups_time) < 0)
return -1;
tmp_mdata.adata = adata;
tmp_mdata.group = NULL;
i = adata->groups_num;
mutt_str_strfcpy(buf, "LIST\r\n", sizeof(buf));
rc = nntp_fetch_lines(&tmp_mdata, buf, sizeof(buf), msg, nntp_add_group, adata);
if (rc)
{
if (rc > 0)
{
mutt_error("LIST: %s", buf);
}
return -1;
}
if (mark_new)
{
for (; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
mdata->has_new_mail = true;
}
}
for (i = 0; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
if (mdata && mdata->deleted && !mdata->newsrc_ent)
{
nntp_delete_group_cache(mdata);
mutt_hash_delete(adata->groups_hash, mdata->group, NULL);
adata->groups_list[i] = NULL;
}
}
if (C_NntpLoadDescription)
rc = get_description(&tmp_mdata, "*", _("Loading descriptions..."));
nntp_active_save_cache(adata);
if (rc < 0)
return -1;
mutt_clear_error();
return 0;
}
/**
* nntp_check_new_groups - Check for new groups/articles in subscribed groups
* @param m Mailbox
* @param adata NNTP server
* @retval 1 New groups found
* @retval 0 No new groups
* @retval -1 Error
*/
int nntp_check_new_groups(struct Mailbox *m, struct NntpAccountData *adata)
{
struct NntpMboxData tmp_mdata = { 0 };
time_t now;
char buf[1024];
char *msg = _("Checking for new newsgroups...");
unsigned int i;
int rc, update_active = false;
if (!adata || !adata->newgroups_time)
return -1;
/* check subscribed newsgroups for new articles */
if (C_ShowNewNews)
{
mutt_message(_("Checking for new messages..."));
for (i = 0; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
if (mdata && mdata->subscribed)
{
rc = nntp_group_poll(mdata, true);
if (rc < 0)
return -1;
if (rc > 0)
update_active = true;
}
}
}
else if (adata->newgroups_time)
return 0;
/* get list of new groups */
mutt_message(msg);
if (nntp_date(adata, &now) < 0)
return -1;
tmp_mdata.adata = adata;
if (m && m->mdata)
tmp_mdata.group = ((struct NntpMboxData *) m->mdata)->group;
else
tmp_mdata.group = NULL;
i = adata->groups_num;
struct tm tm = mutt_date_gmtime(adata->newgroups_time);
snprintf(buf, sizeof(buf), "NEWGROUPS %02d%02d%02d %02d%02d%02d GMT\r\n",
tm.tm_year % 100, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
rc = nntp_fetch_lines(&tmp_mdata, buf, sizeof(buf), msg, nntp_add_group, adata);
if (rc)
{
if (rc > 0)
{
mutt_error("NEWGROUPS: %s", buf);
}
return -1;
}
/* new groups found */
rc = 0;
if (adata->groups_num != i)
{
int groups_num = i;
adata->newgroups_time = now;
for (; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
mdata->has_new_mail = true;
}
/* loading descriptions */
if (C_NntpLoadDescription)
{
unsigned int count = 0;
struct Progress progress;
mutt_progress_init(&progress, _("Loading descriptions..."),
MUTT_PROGRESS_READ, adata->groups_num - i);
for (i = groups_num; i < adata->groups_num; i++)
{
struct NntpMboxData *mdata = adata->groups_list[i];
if (get_description(mdata, NULL, NULL) < 0)
return -1;
mutt_progress_update(&progress, ++count, -1);
}
}
update_active = true;
rc = 1;
}
if (update_active)
nntp_active_save_cache(adata);
mutt_clear_error();
return rc;
}
/**
* nntp_check_msgid - Fetch article by Message-ID
* @param m Mailbox
* @param msgid Message ID
* @retval 0 Success
* @retval 1 No such article
* @retval -1 Error
*/
int nntp_check_msgid(struct Mailbox *m, const char *msgid)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
char buf[1024];
FILE *fp = mutt_file_mkstemp();
if (!fp)
{
mutt_perror(_("Can't create temporary file"));
return -1;
}
snprintf(buf, sizeof(buf), "HEAD %s\r\n", msgid);
int rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_tempfile, fp);
if (rc)
{
mutt_file_fclose(&fp);
if (rc < 0)
return -1;
if (mutt_str_startswith(buf, "430", CASE_MATCH))
return 1;
mutt_error("HEAD: %s", buf);
return -1;
}
/* parse header */
if (m->msg_count == m->email_max)
mx_alloc_memory(m);
m->emails[m->msg_count] = email_new();
struct Email *e = m->emails[m->msg_count];
e->edata = nntp_edata_new();
e->edata_free = nntp_edata_free;
e->env = mutt_rfc822_read_header(fp, e, false, false);
mutt_file_fclose(&fp);
/* get article number */
if (e->env->xref)
nntp_parse_xref(m, e);
else
{
snprintf(buf, sizeof(buf), "STAT %s\r\n", msgid);
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
{
email_free(&e);
return -1;
}
sscanf(buf + 4, ANUM, &nntp_edata_get(e)->article_num);
}
/* reset flags */
e->read = false;
e->old = false;
e->deleted = false;
e->changed = true;
e->received = e->date_sent;
e->index = m->msg_count++;
mailbox_changed(m, NT_MAILBOX_INVALID);
return 0;
}
/**
* nntp_check_children - Fetch children of article with the Message-ID
* @param m Mailbox
* @param msgid Message ID to find
* @retval 0 Success
* @retval -1 Failure
*/
int nntp_check_children(struct Mailbox *m, const char *msgid)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct ChildCtx cc;
char buf[256];
int rc;
void *hc = NULL;
if (!mdata || !mdata->adata)
return -1;
if (mdata->first_message > mdata->last_loaded)
return 0;
/* init context */
cc.mailbox = m;
cc.num = 0;
cc.max = 10;
cc.child = mutt_mem_malloc(sizeof(anum_t) * cc.max);
/* fetch numbers of child messages */
snprintf(buf, sizeof(buf), "XPAT References %u-%u *%s*\r\n",
mdata->first_message, mdata->last_loaded, msgid);
rc = nntp_fetch_lines(mdata, buf, sizeof(buf), NULL, fetch_children, &cc);
if (rc)
{
FREE(&cc.child);
if (rc > 0)
{
if (!mutt_str_startswith(buf, "500", CASE_MATCH))
mutt_error("XPAT: %s", buf);
else
{
mutt_error(_("Unable to find child articles because server does not "
"support XPAT command"));
}
}
return -1;
}
/* fetch all found messages */
bool verbose = m->verbose;
m->verbose = false;
#ifdef USE_HCACHE
hc = nntp_hcache_open(mdata);
#endif
int old_msg_count = m->msg_count;
for (int i = 0; i < cc.num; i++)
{
rc = nntp_fetch_headers(m, hc, cc.child[i], cc.child[i], true);
if (rc < 0)
break;
}
if (m->msg_count > old_msg_count)
mailbox_changed(m, NT_MAILBOX_INVALID);
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
m->verbose = verbose;
FREE(&cc.child);
return (rc < 0) ? -1 : 0;
}
/**
* nntp_compare_order - Sort to mailbox order - Implements ::sort_t
*/
int nntp_compare_order(const void *a, const void *b)
{
const struct Email *ea = *(struct Email const *const *) a;
const struct Email *eb = *(struct Email const *const *) b;
anum_t na = nntp_edata_get((struct Email *) ea)->article_num;
anum_t nb = nntp_edata_get((struct Email *) eb)->article_num;
int result = (na == nb) ? 0 : (na > nb) ? 1 : -1;
result = perform_auxsort(result, a, b);
return SORT_CODE(result);
}
/**
* nntp_ac_find - Find an Account that matches a Mailbox path - Implements MxOps::ac_find()
*/
static struct Account *nntp_ac_find(struct Account *a, const char *path)
{
#if 0
if (!a || (a->type != MUTT_NNTP) || !path)
return NULL;
struct Url url = { 0 };
char tmp[PATH_MAX];
mutt_str_strfcpy(tmp, path, sizeof(tmp));
url_parse(&url, tmp);
struct ImapAccountData *adata = a->data;
struct ConnAccount *cac = &adata->conn_account;
if (mutt_str_strcasecmp(url.host, cac->host) != 0)
return NULL;
if (mutt_str_strcasecmp(url.user, cac->user) != 0)
return NULL;
// if (mutt_str_strcmp(path, a->mailbox->realpath) == 0)
// return a;
#endif
return a;
}
/**
* nntp_ac_add - Add a Mailbox to an Account - Implements MxOps::ac_add()
*/
static int nntp_ac_add(struct Account *a, struct Mailbox *m)
{
if (!a || !m || (m->type != MUTT_NNTP))
return -1;
return 0;
}
/**
* nntp_mbox_open - Open a Mailbox - Implements MxOps::mbox_open()
*/
static int nntp_mbox_open(struct Mailbox *m)
{
if (!m || !m->account)
return -1;
char buf[8192];
char server[1024];
char *group = NULL;
int rc;
void *hc = NULL;
anum_t first, last, count = 0;
struct Url *url = url_parse(mailbox_path(m));
if (!url || !url->host || !url->path ||
!((url->scheme == U_NNTP) || (url->scheme == U_NNTPS)))
{
url_free(&url);
mutt_error(_("%s is an invalid newsgroup specification"), mailbox_path(m));
return -1;
}
group = url->path;
if (group[0] == '/') /* Skip a leading '/' */
group++;
url->path = strchr(url->path, '\0');
url_tostring(url, server, sizeof(server), 0);
mutt_account_hook(m->realpath);
struct NntpAccountData *adata = m->account->adata;
if (!adata)
{
adata = nntp_select_server(m, server, true);
m->account->adata = adata;
m->account->adata_free = nntp_adata_free;
}
if (!adata)
{
url_free(&url);
return -1;
}
CurrentNewsSrv = adata;
m->msg_count = 0;
m->msg_unread = 0;
m->vcount = 0;
if (group[0] == '/')
group++;
/* find news group data structure */
struct NntpMboxData *mdata = mutt_hash_find(adata->groups_hash, group);
if (!mdata)
{
nntp_newsrc_close(adata);
mutt_error(_("Newsgroup %s not found on the server"), group);
url_free(&url);
return -1;
}
m->rights &= ~MUTT_ACL_INSERT; // Clear the flag
if (!mdata->newsrc_ent && !mdata->subscribed && !C_SaveUnsubscribed)
m->readonly = true;
/* select newsgroup */
mutt_message(_("Selecting %s..."), group);
url_free(&url);
buf[0] = '\0';
if (nntp_query(mdata, buf, sizeof(buf)) < 0)
{
nntp_newsrc_close(adata);
return -1;
}
/* newsgroup not found, remove it */
if (mutt_str_startswith(buf, "411", CASE_MATCH))
{
mutt_error(_("Newsgroup %s has been removed from the server"), mdata->group);
if (!mdata->deleted)
{
mdata->deleted = true;
nntp_active_save_cache(adata);
}
if (mdata->newsrc_ent && !mdata->subscribed && !C_SaveUnsubscribed)
{
FREE(&mdata->newsrc_ent);
mdata->newsrc_len = 0;
nntp_delete_group_cache(mdata);
nntp_newsrc_update(adata);
}
}
/* parse newsgroup info */
else
{
if (sscanf(buf, "211 " ANUM " " ANUM " " ANUM, &count, &first, &last) != 3)
{
nntp_newsrc_close(adata);
mutt_error("GROUP: %s", buf);
return -1;
}
mdata->first_message = first;
mdata->last_message = last;
mdata->deleted = false;
/* get description if empty */
if (C_NntpLoadDescription && !mdata->desc)
{
if (get_description(mdata, NULL, NULL) < 0)
{
nntp_newsrc_close(adata);
return -1;
}
if (mdata->desc)
nntp_active_save_cache(adata);
}
}
adata->check_time = mutt_date_epoch();
m->mdata = mdata;
// Every known newsgroup has an mdata which is stored in adata->groups_list.
// Currently we don't let the Mailbox free the mdata.
// m->mdata_free = nntp_mdata_free;
if (!mdata->bcache && (mdata->newsrc_ent || mdata->subscribed || C_SaveUnsubscribed))
mdata->bcache = mutt_bcache_open(&adata->conn->account, mdata->group);
/* strip off extra articles if adding context is greater than $nntp_context */
first = mdata->first_message;
if (C_NntpContext && (mdata->last_message - first + 1 > C_NntpContext))
first = mdata->last_message - C_NntpContext + 1;
mdata->last_loaded = first ? first - 1 : 0;
count = mdata->first_message;
mdata->first_message = first;
nntp_bcache_update(mdata);
mdata->first_message = count;
#ifdef USE_HCACHE
hc = nntp_hcache_open(mdata);
nntp_hcache_update(mdata, hc);
#endif
if (!hc)
m->rights &= ~(MUTT_ACL_WRITE | MUTT_ACL_DELETE); // Clear the flags
nntp_newsrc_close(adata);
rc = nntp_fetch_headers(m, hc, first, mdata->last_message, false);
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (rc < 0)
return -1;
mdata->last_loaded = mdata->last_message;
adata->newsrc_modified = false;
return 0;
}
/**
* nntp_mbox_check - Check for new mail - Implements MxOps::mbox_check()
* @param m Mailbox
* @param index_hint Current message (UNUSED)
* @retval #MUTT_REOPENED Articles have been renumbered or removed from server
* @retval #MUTT_NEW_MAIL New articles found
* @retval 0 No change
* @retval -1 Lost connection
*/
static int nntp_mbox_check(struct Mailbox *m, int *index_hint)
{
if (!m)
return -1;
int rc = check_mailbox(m);
if (rc == 0)
{
struct NntpMboxData *mdata = m->mdata;
struct NntpAccountData *adata = mdata->adata;
nntp_newsrc_close(adata);
}
return rc;
}
/**
* nntp_mbox_sync - Save changes to the Mailbox - Implements MxOps::mbox_sync()
*
* @note May also return values from check_mailbox()
*/
static int nntp_mbox_sync(struct Mailbox *m, int *index_hint)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
int rc;
/* check for new articles */
mdata->adata->check_time = 0;
rc = check_mailbox(m);
if (rc)
return rc;
#ifdef USE_HCACHE
mdata->last_cached = 0;
header_cache_t *hc = nntp_hcache_open(mdata);
#endif
for (int i = 0; i < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
char buf[16];
snprintf(buf, sizeof(buf), ANUM, nntp_edata_get(e)->article_num);
if (mdata->bcache && e->deleted)
{
mutt_debug(LL_DEBUG2, "mutt_bcache_del %s\n", buf);
mutt_bcache_del(mdata->bcache, buf);
}
#ifdef USE_HCACHE
if (hc && (e->changed || e->deleted))
{
if (e->deleted && !e->read)
mdata->unread--;
mutt_debug(LL_DEBUG2, "mutt_hcache_store %s\n", buf);
mutt_hcache_store(hc, buf, strlen(buf), e, 0);
}
#endif
}
#ifdef USE_HCACHE
if (hc)
{
mutt_hcache_close(hc);
mdata->last_cached = mdata->last_loaded;
}
#endif
/* save .newsrc entries */
nntp_newsrc_gen_entries(m);
nntp_newsrc_update(mdata->adata);
nntp_newsrc_close(mdata->adata);
return 0;
}
/**
* nntp_mbox_close - Close a Mailbox - Implements MxOps::mbox_close()
* @retval 0 Always
*/
static int nntp_mbox_close(struct Mailbox *m)
{
if (!m)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct NntpMboxData *tmp_mdata = NULL;
if (!mdata)
return 0;
mdata->unread = m->msg_unread;
nntp_acache_free(mdata);
if (!mdata->adata || !mdata->adata->groups_hash || !mdata->group)
return 0;
tmp_mdata = mutt_hash_find(mdata->adata->groups_hash, mdata->group);
if (!tmp_mdata || (tmp_mdata != mdata))
nntp_mdata_free((void **) &mdata);
return 0;
}
/**
* nntp_msg_open - Open an email message in a Mailbox - Implements MxOps::msg_open()
*/
static int nntp_msg_open(struct Mailbox *m, struct Message *msg, int msgno)
{
if (!m || !m->emails || (msgno >= m->msg_count) || !msg)
return -1;
struct NntpMboxData *mdata = m->mdata;
struct Email *e = m->emails[msgno];
if (!e)
return -1;
char article[16];
/* try to get article from cache */
struct NntpAcache *acache = &mdata->acache[e->index % NNTP_ACACHE_LEN];
if (acache->path)
{
if (acache->index == e->index)
{
msg->fp = mutt_file_fopen(acache->path, "r");
if (msg->fp)
return 0;
}
/* clear previous entry */
else
{
unlink(acache->path);
FREE(&acache->path);
}
}
snprintf(article, sizeof(article), ANUM, nntp_edata_get(e)->article_num);
msg->fp = mutt_bcache_get(mdata->bcache, article);
if (msg->fp)
{
if (nntp_edata_get(e)->parsed)
return 0;
}
else
{
char buf[PATH_MAX];
/* don't try to fetch article from removed newsgroup */
if (mdata->deleted)
return -1;
/* create new cache file */
const char *fetch_msg = _("Fetching message...");
mutt_message(fetch_msg);
msg->fp = mutt_bcache_put(mdata->bcache, article);
if (!msg->fp)
{
mutt_mktemp(buf, sizeof(buf));
acache->path = mutt_str_strdup(buf);
acache->index = e->index;
msg->fp = mutt_file_fopen(acache->path, "w+");
if (!msg->fp)
{
mutt_perror(acache->path);
unlink(acache->path);
FREE(&acache->path);
return -1;
}
}
/* fetch message to cache file */
snprintf(buf, sizeof(buf), "ARTICLE %s\r\n",
nntp_edata_get(e)->article_num ? article : e->env->message_id);
const int rc =
nntp_fetch_lines(mdata, buf, sizeof(buf), fetch_msg, fetch_tempfile, msg->fp);
if (rc)
{
mutt_file_fclose(&msg->fp);
if (acache->path)
{
unlink(acache->path);
FREE(&acache->path);
}
if (rc > 0)
{
if (mutt_str_startswith(buf, nntp_edata_get(e)->article_num ? "423" : "430", CASE_MATCH))
{
mutt_error(_("Article %s not found on the server"),
nntp_edata_get(e)->article_num ? article : e->env->message_id);
}
else
mutt_error("ARTICLE: %s", buf);
}
return -1;
}
if (!acache->path)
mutt_bcache_commit(mdata->bcache, article);
}
/* replace envelope with new one
* hash elements must be updated because pointers will be changed */
if (m->id_hash && e->env->message_id)
mutt_hash_delete(m->id_hash, e->env->message_id, e);
if (m->subj_hash && e->env->real_subj)
mutt_hash_delete(m->subj_hash, e->env->real_subj, e);
mutt_env_free(&e->env);
e->env = mutt_rfc822_read_header(msg->fp, e, false, false);
if (m->id_hash && e->env->message_id)
mutt_hash_insert(m->id_hash, e->env->message_id, e);
if (m->subj_hash && e->env->real_subj)
mutt_hash_insert(m->subj_hash, e->env->real_subj, e);
/* fix content length */
fseek(msg->fp, 0, SEEK_END);
e->content->length = ftell(msg->fp) - e->content->offset;
/* this is called in neomutt before the open which fetches the message,
* which is probably wrong, but we just call it again here to handle
* the problem instead of fixing it */
nntp_edata_get(e)->parsed = true;
mutt_parse_mime_message(m, e);
/* these would normally be updated in ctx_update(), but the
* full headers aren't parsed with overview, so the information wasn't
* available then */
if (WithCrypto)
e->security = crypt_query(e->content);
rewind(msg->fp);
mutt_clear_error();
return 0;
}
/**
* nntp_msg_close - Close an email - Implements MxOps::msg_close()
*
* @note May also return EOF Failure, see errno
*/
static int nntp_msg_close(struct Mailbox *m, struct Message *msg)
{
return mutt_file_fclose(&msg->fp);
}
/**
* nntp_path_probe - Is this an NNTP Mailbox? - Implements MxOps::path_probe()
*/
enum MailboxType nntp_path_probe(const char *path, const struct stat *st)
{
if (!path)
return MUTT_UNKNOWN;
if (mutt_str_startswith(path, "news://", CASE_IGNORE))
return MUTT_NNTP;
if (mutt_str_startswith(path, "snews://", CASE_IGNORE))
return MUTT_NNTP;
return MUTT_UNKNOWN;
}
/**
* nntp_path_canon - Canonicalise a Mailbox path - Implements MxOps::path_canon()
*/
static int nntp_path_canon(char *buf, size_t buflen)
{
if (!buf)
return -1;
return 0;
}
/**
* nntp_path_pretty - Abbreviate a Mailbox path - Implements MxOps::path_pretty()
*/
static int nntp_path_pretty(char *buf, size_t buflen, const char *folder)
{
/* Succeed, but don't do anything, for now */
return 0;
}
/**
* nntp_path_parent - Find the parent of a Mailbox path - Implements MxOps::path_parent()
*/
static int nntp_path_parent(char *buf, size_t buflen)
{
/* Succeed, but don't do anything, for now */
return 0;
}
// clang-format off
/**
* MxNntpOps - NNTP Mailbox - Implements ::MxOps
*/
struct MxOps MxNntpOps = {
.type = MUTT_NNTP,
.name = "nntp",
.is_local = false,
.ac_find = nntp_ac_find,
.ac_add = nntp_ac_add,
.mbox_open = nntp_mbox_open,
.mbox_open_append = NULL,
.mbox_check = nntp_mbox_check,
.mbox_check_stats = NULL,
.mbox_sync = nntp_mbox_sync,
.mbox_close = nntp_mbox_close,
.msg_open = nntp_msg_open,
.msg_open_new = NULL,
.msg_commit = NULL,
.msg_close = nntp_msg_close,
.msg_padding_size = NULL,
.msg_save_hcache = NULL,
.tags_edit = NULL,
.tags_commit = NULL,
.path_probe = nntp_path_probe,
.path_canon = nntp_path_canon,
.path_pretty = nntp_path_pretty,
.path_parent = nntp_path_parent,
};
// clang-format on
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_4069_5 |
crossvul-cpp_data_good_1204_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* reverse packet and flow */
SCLogDebug("reversing flow and packet");
PacketSwap(p);
FlowSwap(p->flow);
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permitted on SYN packet", ssn);
}
if (TCP_HAS_TFO(p)) {
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
if (p->payload_len) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
SCLogDebug("ssn: %p (TFO) [len: %d] isn %u base_seq %u next_seq %u payload len %u",
ssn, p->tcpvars.tfo.len, ssn->client.isn, ssn->client.base_seq, ssn->client.next_seq, p->payload_len);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
}
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/** \internal
* \brief detect timestamp anomalies when processing responses to the
* SYN packet.
* \retval true packet is ok
* \retval false packet is bad
*/
static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)
{
/* we only care about evil server here, so skip TS packets */
if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {
return true;
}
TcpStream *receiver_stream = &ssn->client;
uint32_t ts_echo = TCP_GET_TSECR(p);
if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {
if (receiver_stream->last_ts != 0 && ts_echo != 0 &&
ts_echo != receiver_stream->last_ts)
{
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
} else {
if (receiver_stream->last_ts == 0 && ts_echo != 0) {
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
}
return true;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* check for bad responses */
if (StateSynSentValidateTimestamp(ssn, p) == false)
return -1;
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
if (!(TCP_HAS_TFO(p) || (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN))) {
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
} else {
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: (TFO) ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
return -1;
}
SCLogDebug("ssn %p: (TFO) ACK match, packet ACK %" PRIu32 " == "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else if (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN) {
SCLogDebug("ssn %p: ACK received on TFO session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if ((ack_indicates_missed_3whs_ack_packet ||
(ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
if (ack_indicates_missed_3whs_ack_packet) {
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
} else {
SCLogDebug("ssn %p: (TFO) expected packet fits perfectly after SYN/ACK", ssn);
}
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
static inline void HandleThreadId(ThreadVars *tv, Packet *p, StreamTcpThread *stt)
{
const int idx = (!(PKT_IS_TOSERVER(p)));
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id[idx] == 0)) {
p->flow->thread_id[idx] = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id[idx])) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id[idx], tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
HandleThreadId(tv, p, stt);
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
if (p->flow->flags & FLOW_WRONG_THREAD ||
ssn->client.flags & STREAMTCP_STREAM_FLAG_GAP ||
ssn->server.flags & STREAMTCP_STREAM_FLAG_GAP)
{
/* Stream and/or session in known bad condition. Block events
* from being set. */
p->flags |= PKT_STREAM_NO_EVENTS;
}
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadExpand(ssn_pool);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
np->vlan_id[0] = f->vlan_id[0];
np->vlan_id[1] = f->vlan_id[1];
np->vlan_idx = f->vlan_idx;
np->livedev = (struct LiveDevice_ *)f->livedev;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1204_0 |
crossvul-cpp_data_bad_4069_0 | /**
* @file
* Low-level socket handling
*
* @authors
* Copyright (C) 1998,2000 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1999-2006,2008 Brendan Cully <brendan@kublai.com>
* Copyright (C) 1999-2000 Tommi Komulainen <Tommi.Komulainen@iki.fi>
*
* @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 conn_socket Low-level socket handling
*
* Low-level socket handling
*/
#include "config.h"
#include <errno.h>
#include <string.h>
#include <time.h>
#include "private.h"
#include "mutt/lib.h"
#include "socket.h"
#include "conn_globals.h"
#include "connaccount.h"
#include "connection.h"
#include "protos.h"
#include "ssl.h"
/**
* socket_preconnect - Execute a command before opening a socket
* @retval 0 Success
* @retval >0 An errno, e.g. EPERM
*/
static int socket_preconnect(void)
{
if (!C_Preconnect)
return 0;
mutt_debug(LL_DEBUG2, "Executing preconnect: %s\n", C_Preconnect);
const int rc = mutt_system(C_Preconnect);
mutt_debug(LL_DEBUG2, "Preconnect result: %d\n", rc);
if (rc != 0)
{
const int save_errno = errno;
mutt_perror(_("Preconnect command failed"));
return save_errno;
}
return 0;
}
/**
* mutt_socket_open - Simple wrapper
* @param conn Connection to a server
* @retval 0 Success
* @retval -1 Error
*/
int mutt_socket_open(struct Connection *conn)
{
int rc;
if (socket_preconnect())
return -1;
rc = conn->open(conn);
mutt_debug(LL_DEBUG2, "Connected to %s:%d on fd=%d\n", conn->account.host,
conn->account.port, conn->fd);
return rc;
}
/**
* mutt_socket_close - Close a socket
* @param conn Connection to a server
* @retval 0 Success
* @retval -1 Error
*/
int mutt_socket_close(struct Connection *conn)
{
if (!conn)
return 0;
int rc = -1;
if (conn->fd < 0)
mutt_debug(LL_DEBUG1, "Attempt to close closed connection\n");
else
rc = conn->close(conn);
conn->fd = -1;
conn->ssf = 0;
conn->bufpos = 0;
conn->available = 0;
return rc;
}
/**
* mutt_socket_read - read from a Connection
* @param conn Connection a server
* @param buf Buffer to store read data
* @param len length of the buffer
* @retval >0 Success, number of bytes read
* @retval -1 Error, see errno
*/
int mutt_socket_read(struct Connection *conn, char *buf, size_t len)
{
return conn->read(conn, buf, len);
}
/**
* mutt_socket_write - write to a Connection
* @param conn Connection to a server
* @param buf Buffer with data to write
* @param len Length of data to write
* @retval >0 Number of bytes written
* @retval -1 Error
*/
int mutt_socket_write(struct Connection *conn, const char *buf, size_t len)
{
return conn->write(conn, buf, len);
}
/**
* mutt_socket_write_d - Write data to a socket
* @param conn Connection to a server
* @param buf Buffer with data to write
* @param len Length of data to write
* @param dbg Debug level for logging
* @retval >0 Number of bytes written
* @retval -1 Error
*/
int mutt_socket_write_d(struct Connection *conn, const char *buf, int len, int dbg)
{
int sent = 0;
mutt_debug(dbg, "%d> %s", conn->fd, buf);
if (conn->fd < 0)
{
mutt_debug(LL_DEBUG1, "attempt to write to closed connection\n");
return -1;
}
while (sent < len)
{
const int rc = conn->write(conn, buf + sent, len - sent);
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "error writing (%s), closing socket\n", strerror(errno));
mutt_socket_close(conn);
return -1;
}
if (rc < len - sent)
mutt_debug(LL_DEBUG3, "short write (%d of %d bytes)\n", rc, len - sent);
sent += rc;
}
return sent;
}
/**
* mutt_socket_poll - Checks whether reads would block
* @param conn Connection to a server
* @param wait_secs How long to wait for a response
* @retval >0 There is data to read
* @retval 0 Read would block
* @retval -1 Connection doesn't support polling
*/
int mutt_socket_poll(struct Connection *conn, time_t wait_secs)
{
if (conn->bufpos < conn->available)
return conn->available - conn->bufpos;
if (conn->poll)
return conn->poll(conn, wait_secs);
return -1;
}
/**
* mutt_socket_readchar - simple read buffering to speed things up
* @param[in] conn Connection to a server
* @param[out] c Character that was read
* @retval 1 Success
* @retval -1 Error
*/
int mutt_socket_readchar(struct Connection *conn, char *c)
{
if (conn->bufpos >= conn->available)
{
if (conn->fd >= 0)
conn->available = conn->read(conn, conn->inbuf, sizeof(conn->inbuf));
else
{
mutt_debug(LL_DEBUG1, "attempt to read from closed connection\n");
return -1;
}
conn->bufpos = 0;
if (conn->available == 0)
{
mutt_error(_("Connection to %s closed"), conn->account.host);
}
if (conn->available <= 0)
{
mutt_socket_close(conn);
return -1;
}
}
*c = conn->inbuf[conn->bufpos];
conn->bufpos++;
return 1;
}
/**
* mutt_socket_readln_d - Read a line from a socket
* @param buf Buffer to store the line
* @param buflen Length of data to write
* @param conn Connection to a server
* @param dbg Debug level for logging
* @retval >0 Success, number of bytes read
* @retval -1 Error
*/
int mutt_socket_readln_d(char *buf, size_t buflen, struct Connection *conn, int dbg)
{
char ch;
int i;
for (i = 0; i < buflen - 1; i++)
{
if (mutt_socket_readchar(conn, &ch) != 1)
{
buf[i] = '\0';
return -1;
}
if (ch == '\n')
break;
buf[i] = ch;
}
/* strip \r from \r\n termination */
if (i && (buf[i - 1] == '\r'))
i--;
buf[i] = '\0';
mutt_debug(dbg, "%d< %s\n", conn->fd, buf);
/* number of bytes read, not strlen */
return i + 1;
}
/**
* mutt_socket_new - allocate and initialise a new connection
* @param type Type of the new Connection
* @retval ptr New Connection
*/
struct Connection *mutt_socket_new(enum ConnectionType type)
{
struct Connection *conn = mutt_mem_calloc(1, sizeof(struct Connection));
conn->fd = -1;
if (type == MUTT_CONNECTION_TUNNEL)
{
mutt_tunnel_socket_setup(conn);
}
else if (type == MUTT_CONNECTION_SSL)
{
int rc = mutt_ssl_socket_setup(conn);
if (rc < 0)
FREE(&conn);
}
else
{
conn->read = raw_socket_read;
conn->write = raw_socket_write;
conn->open = raw_socket_open;
conn->close = raw_socket_close;
conn->poll = raw_socket_poll;
}
return conn;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_4069_0 |
crossvul-cpp_data_good_433_1 | // SPDX-License-Identifier: GPL-3.0-or-later
#include "web_api_v1.h"
static struct {
const char *name;
uint32_t hash;
RRDR_OPTIONS value;
} api_v1_data_options[] = {
{ "nonzero" , 0 , RRDR_OPTION_NONZERO}
, {"flip" , 0 , RRDR_OPTION_REVERSED}
, {"reversed" , 0 , RRDR_OPTION_REVERSED}
, {"reverse" , 0 , RRDR_OPTION_REVERSED}
, {"jsonwrap" , 0 , RRDR_OPTION_JSON_WRAP}
, {"min2max" , 0 , RRDR_OPTION_MIN2MAX}
, {"ms" , 0 , RRDR_OPTION_MILLISECONDS}
, {"milliseconds" , 0 , RRDR_OPTION_MILLISECONDS}
, {"abs" , 0 , RRDR_OPTION_ABSOLUTE}
, {"absolute" , 0 , RRDR_OPTION_ABSOLUTE}
, {"absolute_sum" , 0 , RRDR_OPTION_ABSOLUTE}
, {"absolute-sum" , 0 , RRDR_OPTION_ABSOLUTE}
, {"display_absolute", 0 , RRDR_OPTION_DISPLAY_ABS}
, {"display-absolute", 0 , RRDR_OPTION_DISPLAY_ABS}
, {"seconds" , 0 , RRDR_OPTION_SECONDS}
, {"null2zero" , 0 , RRDR_OPTION_NULL2ZERO}
, {"objectrows" , 0 , RRDR_OPTION_OBJECTSROWS}
, {"google_json" , 0 , RRDR_OPTION_GOOGLE_JSON}
, {"google-json" , 0 , RRDR_OPTION_GOOGLE_JSON}
, {"percentage" , 0 , RRDR_OPTION_PERCENTAGE}
, {"unaligned" , 0 , RRDR_OPTION_NOT_ALIGNED}
, {"match_ids" , 0 , RRDR_OPTION_MATCH_IDS}
, {"match-ids" , 0 , RRDR_OPTION_MATCH_IDS}
, {"match_names" , 0 , RRDR_OPTION_MATCH_NAMES}
, {"match-names" , 0 , RRDR_OPTION_MATCH_NAMES}
, { NULL, 0, 0}
};
static struct {
const char *name;
uint32_t hash;
uint32_t value;
} api_v1_data_formats[] = {
{ DATASOURCE_FORMAT_DATATABLE_JSON , 0 , DATASOURCE_DATATABLE_JSON}
, {DATASOURCE_FORMAT_DATATABLE_JSONP, 0 , DATASOURCE_DATATABLE_JSONP}
, {DATASOURCE_FORMAT_JSON , 0 , DATASOURCE_JSON}
, {DATASOURCE_FORMAT_JSONP , 0 , DATASOURCE_JSONP}
, {DATASOURCE_FORMAT_SSV , 0 , DATASOURCE_SSV}
, {DATASOURCE_FORMAT_CSV , 0 , DATASOURCE_CSV}
, {DATASOURCE_FORMAT_TSV , 0 , DATASOURCE_TSV}
, {"tsv-excel" , 0 , DATASOURCE_TSV}
, {DATASOURCE_FORMAT_HTML , 0 , DATASOURCE_HTML}
, {DATASOURCE_FORMAT_JS_ARRAY , 0 , DATASOURCE_JS_ARRAY}
, {DATASOURCE_FORMAT_SSV_COMMA , 0 , DATASOURCE_SSV_COMMA}
, {DATASOURCE_FORMAT_CSV_JSON_ARRAY , 0 , DATASOURCE_CSV_JSON_ARRAY}
, {DATASOURCE_FORMAT_CSV_MARKDOWN , 0 , DATASOURCE_CSV_MARKDOWN}
, { NULL, 0, 0}
};
static struct {
const char *name;
uint32_t hash;
uint32_t value;
} api_v1_data_google_formats[] = {
// this is not error - when google requests json, it expects javascript
// https://developers.google.com/chart/interactive/docs/dev/implementing_data_source#responseformat
{ "json" , 0 , DATASOURCE_DATATABLE_JSONP}
, {"html" , 0 , DATASOURCE_HTML}
, {"csv" , 0 , DATASOURCE_CSV}
, {"tsv-excel", 0 , DATASOURCE_TSV}
, { NULL, 0, 0}
};
void web_client_api_v1_init(void) {
int i;
for(i = 0; api_v1_data_options[i].name ; i++)
api_v1_data_options[i].hash = simple_hash(api_v1_data_options[i].name);
for(i = 0; api_v1_data_formats[i].name ; i++)
api_v1_data_formats[i].hash = simple_hash(api_v1_data_formats[i].name);
for(i = 0; api_v1_data_google_formats[i].name ; i++)
api_v1_data_google_formats[i].hash = simple_hash(api_v1_data_google_formats[i].name);
web_client_api_v1_init_grouping();
}
inline uint32_t web_client_api_request_v1_data_options(char *o) {
uint32_t ret = 0x00000000;
char *tok;
while(o && *o && (tok = mystrsep(&o, ", |"))) {
if(!*tok) continue;
uint32_t hash = simple_hash(tok);
int i;
for(i = 0; api_v1_data_options[i].name ; i++) {
if (unlikely(hash == api_v1_data_options[i].hash && !strcmp(tok, api_v1_data_options[i].name))) {
ret |= api_v1_data_options[i].value;
break;
}
}
}
return ret;
}
inline uint32_t web_client_api_request_v1_data_format(char *name) {
uint32_t hash = simple_hash(name);
int i;
for(i = 0; api_v1_data_formats[i].name ; i++) {
if (unlikely(hash == api_v1_data_formats[i].hash && !strcmp(name, api_v1_data_formats[i].name))) {
return api_v1_data_formats[i].value;
}
}
return DATASOURCE_JSON;
}
inline uint32_t web_client_api_request_v1_data_google_format(char *name) {
uint32_t hash = simple_hash(name);
int i;
for(i = 0; api_v1_data_google_formats[i].name ; i++) {
if (unlikely(hash == api_v1_data_google_formats[i].hash && !strcmp(name, api_v1_data_google_formats[i].name))) {
return api_v1_data_google_formats[i].value;
}
}
return DATASOURCE_JSON;
}
inline int web_client_api_request_v1_alarms(RRDHOST *host, struct web_client *w, char *url) {
int all = 0;
while(url) {
char *value = mystrsep(&url, "?&");
if (!value || !*value) continue;
if(!strcmp(value, "all")) all = 1;
else if(!strcmp(value, "active")) all = 0;
}
buffer_flush(w->response.data);
w->response.data->contenttype = CT_APPLICATION_JSON;
health_alarms2json(host, w->response.data, all);
return 200;
}
inline int web_client_api_request_v1_alarm_log(RRDHOST *host, struct web_client *w, char *url) {
uint32_t after = 0;
while(url) {
char *value = mystrsep(&url, "?&");
if (!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
if(!strcmp(name, "after")) after = (uint32_t)strtoul(value, NULL, 0);
}
buffer_flush(w->response.data);
w->response.data->contenttype = CT_APPLICATION_JSON;
health_alarm_log2json(host, w->response.data, after);
return 200;
}
inline int web_client_api_request_single_chart(RRDHOST *host, struct web_client *w, char *url, void callback(RRDSET *st, BUFFER *buf)) {
int ret = 400;
char *chart = NULL;
buffer_flush(w->response.data);
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
// name and value are now the parameters
// they are not null and not empty
if(!strcmp(name, "chart")) chart = value;
//else {
/// buffer_sprintf(w->response.data, "Unknown parameter '%s' in request.", name);
// goto cleanup;
//}
}
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
w->response.data->contenttype = CT_APPLICATION_JSON;
st->last_accessed_time = now_realtime_sec();
callback(st, w->response.data);
return 200;
cleanup:
return ret;
}
inline int web_client_api_request_v1_alarm_variables(RRDHOST *host, struct web_client *w, char *url) {
return web_client_api_request_single_chart(host, w, url, health_api_v1_chart_variables2json);
}
inline int web_client_api_request_v1_charts(RRDHOST *host, struct web_client *w, char *url) {
(void)url;
buffer_flush(w->response.data);
w->response.data->contenttype = CT_APPLICATION_JSON;
charts2json(host, w->response.data);
return 200;
}
inline int web_client_api_request_v1_chart(RRDHOST *host, struct web_client *w, char *url) {
return web_client_api_request_single_chart(host, w, url, rrd_stats_api_v1_chart);
}
void fix_google_param(char *s) {
if(unlikely(!s)) return;
for( ; *s ;s++) {
if(!isalnum(*s) && *s != '.' && *s != '_' && *s != '-')
*s = '_';
}
}
// returns the HTTP code
inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {
debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
int ret = 400;
BUFFER *dimensions = NULL;
buffer_flush(w->response.data);
char *google_version = "0.6",
*google_reqId = "0",
*google_sig = "0",
*google_out = "json",
*responseHandler = NULL,
*outFileName = NULL;
time_t last_timestamp_in_data = 0, google_timestamp = 0;
char *chart = NULL
, *before_str = NULL
, *after_str = NULL
, *group_time_str = NULL
, *points_str = NULL;
int group = RRDR_GROUPING_AVERAGE;
uint32_t format = DATASOURCE_JSON;
uint32_t options = 0x00000000;
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
// name and value are now the parameters
// they are not null and not empty
if(!strcmp(name, "chart")) chart = value;
else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
if(!dimensions) dimensions = buffer_create(100);
buffer_strcat(dimensions, "|");
buffer_strcat(dimensions, value);
}
else if(!strcmp(name, "after")) after_str = value;
else if(!strcmp(name, "before")) before_str = value;
else if(!strcmp(name, "points")) points_str = value;
else if(!strcmp(name, "gtime")) group_time_str = value;
else if(!strcmp(name, "group")) {
group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE);
}
else if(!strcmp(name, "format")) {
format = web_client_api_request_v1_data_format(value);
}
else if(!strcmp(name, "options")) {
options |= web_client_api_request_v1_data_options(value);
}
else if(!strcmp(name, "callback")) {
responseHandler = value;
}
else if(!strcmp(name, "filename")) {
outFileName = value;
}
else if(!strcmp(name, "tqx")) {
// parse Google Visualization API options
// https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
char *tqx_name, *tqx_value;
while(value) {
tqx_value = mystrsep(&value, ";");
if(!tqx_value || !*tqx_value) continue;
tqx_name = mystrsep(&tqx_value, ":");
if(!tqx_name || !*tqx_name) continue;
if(!tqx_value || !*tqx_value) continue;
if(!strcmp(tqx_name, "version"))
google_version = tqx_value;
else if(!strcmp(tqx_name, "reqId"))
google_reqId = tqx_value;
else if(!strcmp(tqx_name, "sig")) {
google_sig = tqx_value;
google_timestamp = strtoul(google_sig, NULL, 0);
}
else if(!strcmp(tqx_name, "out")) {
google_out = tqx_value;
format = web_client_api_request_v1_data_google_format(google_out);
}
else if(!strcmp(tqx_name, "responseHandler"))
responseHandler = tqx_value;
else if(!strcmp(tqx_name, "outFileName"))
outFileName = tqx_value;
}
}
}
// validate the google parameters given
fix_google_param(google_out);
fix_google_param(google_sig);
fix_google_param(google_reqId);
fix_google_param(google_version);
fix_google_param(responseHandler);
fix_google_param(outFileName);
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
st->last_accessed_time = now_realtime_sec();
long long before = (before_str && *before_str)?str2l(before_str):0;
long long after = (after_str && *after_str) ?str2l(after_str):0;
int points = (points_str && *points_str)?str2i(points_str):0;
long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;
debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
, w->id
, chart
, (dimensions)?buffer_tostring(dimensions):""
, after
, before
, points
, group
, format
, options
);
if(outFileName && *outFileName) {
buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
}
if(format == DATASOURCE_DATATABLE_JSONP) {
if(responseHandler == NULL)
responseHandler = "google.visualization.Query.setResponse";
debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
}
else if(format == DATASOURCE_JSONP) {
if(responseHandler == NULL)
responseHandler = "callback";
buffer_strcat(w->response.data, responseHandler);
buffer_strcat(w->response.data, "(");
}
ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time
, options, &last_timestamp_in_data);
if(format == DATASOURCE_DATATABLE_JSONP) {
if(google_timestamp < last_timestamp_in_data)
buffer_strcat(w->response.data, "});");
else {
// the client already has the latest data
buffer_flush(w->response.data);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
responseHandler, google_version, google_reqId);
}
}
else if(format == DATASOURCE_JSONP)
buffer_strcat(w->response.data, ");");
cleanup:
buffer_free(dimensions);
return ret;
}
inline int web_client_api_request_v1_registry(RRDHOST *host, struct web_client *w, char *url) {
static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0,
hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0,
hash_to = 0 /*, hash_redirects = 0 */;
if(unlikely(!hash_action)) {
hash_action = simple_hash("action");
hash_access = simple_hash("access");
hash_hello = simple_hash("hello");
hash_delete = simple_hash("delete");
hash_search = simple_hash("search");
hash_switch = simple_hash("switch");
hash_machine = simple_hash("machine");
hash_url = simple_hash("url");
hash_name = simple_hash("name");
hash_delete_url = simple_hash("delete_url");
hash_for = simple_hash("for");
hash_to = simple_hash("to");
/*
hash_redirects = simple_hash("redirects");
*/
}
char person_guid[GUID_LEN + 1] = "";
debug(D_WEB_CLIENT, "%llu: API v1 registry with URL '%s'", w->id, url);
// TODO
// The browser may send multiple cookies with our id
char *cookie = strstr(w->response.data->buffer, NETDATA_REGISTRY_COOKIE_NAME "=");
if(cookie)
strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME)], 36);
char action = '\0';
char *machine_guid = NULL,
*machine_url = NULL,
*url_name = NULL,
*search_machine_guid = NULL,
*delete_url = NULL,
*to_person_guid = NULL;
/*
int redirects = 0;
*/
while(url) {
char *value = mystrsep(&url, "?&");
if (!value || !*value) continue;
char *name = mystrsep(&value, "=");
if (!name || !*name) continue;
if (!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 registry query param '%s' with value '%s'", w->id, name, value);
uint32_t hash = simple_hash(name);
if(hash == hash_action && !strcmp(name, "action")) {
uint32_t vhash = simple_hash(value);
if(vhash == hash_access && !strcmp(value, "access")) action = 'A';
else if(vhash == hash_hello && !strcmp(value, "hello")) action = 'H';
else if(vhash == hash_delete && !strcmp(value, "delete")) action = 'D';
else if(vhash == hash_search && !strcmp(value, "search")) action = 'S';
else if(vhash == hash_switch && !strcmp(value, "switch")) action = 'W';
#ifdef NETDATA_INTERNAL_CHECKS
else error("unknown registry action '%s'", value);
#endif /* NETDATA_INTERNAL_CHECKS */
}
/*
else if(hash == hash_redirects && !strcmp(name, "redirects"))
redirects = atoi(value);
*/
else if(hash == hash_machine && !strcmp(name, "machine"))
machine_guid = value;
else if(hash == hash_url && !strcmp(name, "url"))
machine_url = value;
else if(action == 'A') {
if(hash == hash_name && !strcmp(name, "name"))
url_name = value;
}
else if(action == 'D') {
if(hash == hash_delete_url && !strcmp(name, "delete_url"))
delete_url = value;
}
else if(action == 'S') {
if(hash == hash_for && !strcmp(name, "for"))
search_machine_guid = value;
}
else if(action == 'W') {
if(hash == hash_to && !strcmp(name, "to"))
to_person_guid = value;
}
#ifdef NETDATA_INTERNAL_CHECKS
else error("unused registry URL parameter '%s' with value '%s'", name, value);
#endif /* NETDATA_INTERNAL_CHECKS */
}
if(unlikely(respect_web_browser_do_not_track_policy && web_client_has_donottrack(w))) {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data, "Your web browser is sending 'DNT: 1' (Do Not Track). The registry requires persistent cookies on your browser to work.");
return 400;
}
if(unlikely(action == 'H')) {
// HELLO request, dashboard ACL
if(unlikely(!web_client_can_access_dashboard(w)))
return web_client_permission_denied(w);
}
else {
// everything else, registry ACL
if(unlikely(!web_client_can_access_registry(w)))
return web_client_permission_denied(w);
}
switch(action) {
case 'A':
if(unlikely(!machine_guid || !machine_url || !url_name)) {
error("Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')", machine_guid ? machine_guid : "UNSET", machine_url ? machine_url : "UNSET", url_name ? url_name : "UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Access request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_access_json(host, w, person_guid, machine_guid, machine_url, url_name, now_realtime_sec());
case 'D':
if(unlikely(!machine_guid || !machine_url || !delete_url)) {
error("Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", delete_url?delete_url:"UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Delete request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_delete_json(host, w, person_guid, machine_guid, machine_url, delete_url, now_realtime_sec());
case 'S':
if(unlikely(!machine_guid || !machine_url || !search_machine_guid)) {
error("Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", search_machine_guid?search_machine_guid:"UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Search request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_search_json(host, w, person_guid, machine_guid, machine_url, search_machine_guid, now_realtime_sec());
case 'W':
if(unlikely(!machine_guid || !machine_url || !to_person_guid)) {
error("Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')", machine_guid?machine_guid:"UNSET", machine_url?machine_url:"UNSET", to_person_guid?to_person_guid:"UNSET");
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry Switch request.");
return 400;
}
web_client_enable_tracking_required(w);
return registry_request_switch_json(host, w, person_guid, machine_guid, machine_url, to_person_guid, now_realtime_sec());
case 'H':
return registry_request_hello_json(host, w);
default:
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Invalid registry request - you need to set an action: hello, access, delete, search");
return 400;
}
}
static struct api_command {
const char *command;
uint32_t hash;
WEB_CLIENT_ACL acl;
int (*callback)(RRDHOST *host, struct web_client *w, char *url);
} api_commands[] = {
{ "data", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_data },
{ "chart", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_chart },
{ "charts", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_charts },
// registry checks the ACL by itself, so we allow everything
{ "registry", 0, WEB_CLIENT_ACL_NOCHECK, web_client_api_request_v1_registry },
// badges can be fetched with both dashboard and badge permissions
{ "badge.svg", 0, WEB_CLIENT_ACL_DASHBOARD|WEB_CLIENT_ACL_BADGE, web_client_api_request_v1_badge },
{ "alarms", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_alarms },
{ "alarm_log", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_alarm_log },
{ "alarm_variables", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_alarm_variables },
{ "allmetrics", 0, WEB_CLIENT_ACL_DASHBOARD, web_client_api_request_v1_allmetrics },
// terminator
{ NULL, 0, WEB_CLIENT_ACL_NONE, NULL },
};
inline int web_client_api_request_v1(RRDHOST *host, struct web_client *w, char *url) {
static int initialized = 0;
int i;
if(unlikely(initialized == 0)) {
initialized = 1;
for(i = 0; api_commands[i].command ; i++)
api_commands[i].hash = simple_hash(api_commands[i].command);
}
// get the command
char *tok = mystrsep(&url, "/?&");
if(tok && *tok) {
debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
uint32_t hash = simple_hash(tok);
for(i = 0; api_commands[i].command ;i++) {
if(unlikely(hash == api_commands[i].hash && !strcmp(tok, api_commands[i].command))) {
if(unlikely(api_commands[i].acl != WEB_CLIENT_ACL_NOCHECK) && !(w->acl & api_commands[i].acl))
return web_client_permission_denied(w);
return api_commands[i].callback(host, w, url);
}
}
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Unsupported v1 API command: ");
buffer_strcat_htmlescape(w->response.data, tok);
return 404;
}
else {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data, "Which API v1 command?");
return 400;
}
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_433_1 |
crossvul-cpp_data_bad_1003_1 | /***********************************************************************
* *
* This software is part of the ast package *
* Copyright (c) 1982-2013 AT&T Intellectual Property *
* and is licensed under the *
* Eclipse Public License, Version 1.0 *
* by AT&T Intellectual Property *
* *
* A copy of the License is available at *
* http://www.eclipse.org/org/documents/epl-v10.html *
* (with md5 checksum b35adb5213ca9657e911e9befb180842) *
* *
* Information and Software Systems Research *
* AT&T Research *
* Florham Park NJ *
* *
* David Korn <dgkorn@gmail.com> *
* *
***********************************************************************/
//
// Shell arithmetic - uses streval library
// David Korn
// AT&T Labs
//
#include "config_ast.h" // IWYU pragma: keep
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "ast.h"
#include "builtins.h"
#include "cdt.h"
#include "defs.h"
#include "error.h"
#include "lexstates.h"
#include "name.h"
#include "sfio.h"
#include "shcmd.h"
#include "stk.h"
#include "streval.h"
#include "variables.h"
#ifndef LLONG_MAX
#define LLONG_MAX LONG_MAX
#endif
typedef Sfdouble_t (*Math_f)(Sfdouble_t, ...);
extern const Namdisc_t ENUM_disc;
static bool Varsubscript;
static Sfdouble_t NaN, Inf, Fun;
static Namval_t Infnod = {.nvname = "Inf"};
static Namval_t NaNnod = {.nvname = "NaN"};
static Namval_t FunNode = {.nvname = "?"};
struct Mathconst {
char name[9];
Sfdouble_t value;
};
#ifndef M_1_PIl
#define M_1_PIl 0.3183098861837906715377675267450287L
#endif
#ifndef M_2_PIl
#define M_2_PIl 0.6366197723675813430755350534900574L
#endif
#ifndef M_2_SQRTPIl
#define M_2_SQRTPIl 1.1283791670955125738961589031215452L
#endif
#ifndef M_El
#define M_El 2.7182818284590452353602874713526625L
#endif
#ifndef M_LOG2El
#define M_LOG2El 1.4426950408889634073599246810018921L
#endif
#ifndef M_LOG10El
#define M_LOG10El 0.4342944819032518276511289189166051L
#endif
#ifndef M_LN2l
#define M_LN2l 0.6931471805599453094172321214581766L
#endif
#ifndef M_LN10l
#define M_LN10l 2.3025850929940456840179914546843642L
#endif
#ifndef M_PIl
#define M_PIl 3.1415926535897932384626433832795029L
#endif
#ifndef M_PI_2l
#define M_PI_2l 1.5707963267948966192313216916397514L
#endif
#ifndef M_PI_4l
#define M_PI_4l 0.7853981633974483096156608458198757L
#endif
#ifndef M_SQRT2l
#define M_SQRT2l 1.4142135623730950488016887242096981L
#endif
#ifndef M_SQRT1_2l
#define M_SQRT1_2l 0.7071067811865475244008443621048490L
#endif
// The first three entries cann't be moved or it will break the code.
static const struct Mathconst Mtable[] = {
{"1_PI", M_1_PIl}, {"2_PI", M_2_PIl}, {"2_SQRTPI", M_2_SQRTPIl},
{"E", M_El}, {"LOG2E", M_LOG2El}, {"LOG10E", M_LOG10El},
{"LN2", M_LN2l}, {"PI", M_PIl}, {"PI_2", M_PI_2l},
{"PI_4", M_PI_4l}, {"SQRT2", M_SQRT2l}, {"SQRT1_2", M_SQRT1_2l},
{"", 0.0}};
static_fn Namval_t *scope(Namval_t *np, struct lval *lvalue, int assign) {
int flag = lvalue->flag;
char *sub = 0, *cp = (char *)np;
Namval_t *mp;
Shell_t *shp = lvalue->shp;
int c = 0, nosub = lvalue->nosub;
Dt_t *sdict = (shp->st.real_fun ? shp->st.real_fun->sdict : 0);
Dt_t *nsdict = (shp->namespace ? nv_dict(shp->namespace) : 0);
Dt_t *root = shp->var_tree;
nvflag_t nvflags = assign ? NV_ASSIGN : 0;
lvalue->nosub = 0;
if (nosub < 0 && lvalue->ovalue) return (Namval_t *)lvalue->ovalue;
lvalue->ovalue = NULL;
if (cp >= lvalue->expr && cp < lvalue->expr + lvalue->elen) {
int offset;
// Do binding to node now.
int d = cp[flag];
cp[flag] = 0;
np = nv_open(cp, root, nvflags | NV_VARNAME | NV_NOADD | NV_NOFAIL);
if ((!np || nv_isnull(np)) && sh_macfun(shp, cp, offset = stktell(shp->stk))) {
Fun = sh_arith(shp, sub = stkptr(shp->stk, offset));
STORE_VT(FunNode.nvalue, sfdoublep, &Fun);
FunNode.nvshell = shp;
nv_onattr(&FunNode, NV_NOFREE | NV_LDOUBLE | NV_RDONLY);
cp[flag] = d;
return &FunNode;
}
if (!np && assign) {
np = nv_open(cp, root, nvflags | NV_VARNAME);
}
cp[flag] = d;
if (!np) return 0;
root = shp->last_root;
if (cp[flag + 1] == '[') {
flag++;
} else {
flag = 0;
}
}
if ((lvalue->emode & ARITH_COMP) && dtvnext(root)) {
mp = nv_search_namval(np, sdict ? sdict : root, NV_NOSCOPE);
if (!mp && nsdict) mp = nv_search_namval(np, nsdict, 0);
if (mp) np = mp;
}
while (nv_isref(np)) {
sub = nv_refsub(np);
np = nv_refnode(np);
if (sub) nv_putsub(np, sub, 0, assign ? ARRAY_ADD : 0);
}
if (!nosub && flag) {
int hasdot = 0;
cp = (char *)&lvalue->expr[flag];
if (sub) goto skip;
sub = cp;
while (1) {
Namarr_t *ap;
Namval_t *nq;
cp = nv_endsubscript(np, cp, 0, shp);
if (c || *cp == '.') {
c = '.';
while (*cp == '.') {
hasdot = 1;
cp++;
while (c = mb1char(&cp), isaname(c)) {
; // empty body
}
}
if (c == '[') continue;
}
flag = *cp;
*cp = 0;
if (c || hasdot) {
sfprintf(shp->strbuf, "%s%s%c", nv_name(np), sub, 0);
sub = sfstruse(shp->strbuf);
}
if (strchr(sub, '$')) sub = sh_mactrim(shp, sub, 0);
*cp = flag;
if (c || hasdot) {
np = nv_open(sub, shp->var_tree, NV_VARNAME | nvflags);
return np;
}
cp = nv_endsubscript(np, sub, (assign ? NV_ADD : 0) | NV_SUBQUOTE, np->nvshell);
if (*cp != '[') break;
skip:
nq = nv_opensub(np);
if (nq) {
np = nq;
} else {
ap = nv_arrayptr(np);
if (ap && !ap->table) {
ap->table = dtopen(&_Nvdisc, Dtoset);
dtuserdata(ap->table, shp, 1);
}
if (ap && ap->table && (nq = nv_search(nv_getsub(np), ap->table, NV_ADD))) {
nq->nvenv = np;
}
if (nq && nv_isnull(nq)) np = nv_arraychild(np, nq, 0);
}
sub = cp;
}
} else if (nosub > 0) {
nv_putsub(np, NULL, nosub - 1, 0);
}
return np;
}
Math_f sh_mathstdfun(const char *fname, size_t fsize, short *nargs) {
const struct mathtab *tp;
char c = fname[0];
for (tp = shtab_math; *tp->fname; tp++) {
if (*tp->fname > c) break;
if (tp->fname[1] == c && tp->fname[fsize + 1] == 0 &&
strncmp(&tp->fname[1], fname, fsize) == 0) {
if (nargs) *nargs = *tp->fname;
return tp->fnptr;
}
}
return NULL;
}
int sh_mathstd(const char *name) { return sh_mathstdfun(name, strlen(name), NULL) != 0; }
static_fn Sfdouble_t number(const char *s, char **p, int b, struct lval *lvalue) {
Sfdouble_t r;
char *t;
int oerrno;
int c;
char base;
struct lval v;
oerrno = errno;
errno = 0;
base = b;
if (!lvalue) {
lvalue = &v;
} else if (lvalue->shp->bltindata.bnode == SYSLET && !sh_isoption(lvalue->shp, SH_LETOCTAL)) {
while (*s == '0' && isdigit(s[1])) s++;
}
lvalue->eflag = 0;
lvalue->isfloat = 0;
r = strton64(s, &t, &base, -1);
if (*t == '8' || *t == '9') {
base = 10;
errno = 0;
r = strton64(s, &t, &base, -1);
}
if (base <= 1) base = 10;
if (*t == '_') {
if ((r == 1 || r == 2) && strcmp(t, "_PI") == 0) {
t += 3;
r = Mtable[(int)r - 1].value;
} else if (r == 2 && strcmp(t, "_SQRTPI") == 0) {
t += 7;
r = Mtable[2].value;
}
}
c = r == LLONG_MAX && errno ? 'e' : *t;
if (c == getdecimal() || c == 'e' || c == 'E' || (base == 16 && (c == 'p' || c == 'P'))) {
r = strtold(s, &t);
lvalue->isfloat = TYPE_LD;
}
if (t > s) {
if (*t == 'f' || *t == 'F') {
t++;
lvalue->isfloat = TYPE_F;
r = (float)r;
} else if (*t == 'l' || *t == 'L') {
t++;
lvalue->isfloat = TYPE_LD;
} else if (*t == 'd' || *t == 'D') {
t++;
lvalue->isfloat = TYPE_LD;
r = (double)r;
}
}
errno = oerrno;
*p = t;
return r;
}
static_fn Sfdouble_t arith(const char **ptr, struct lval *lvalue, int type, Sfdouble_t n) {
Shell_t *shp = lvalue->shp;
Sfdouble_t r = 0;
char *str = (char *)*ptr;
char *cp;
switch (type) {
case ASSIGN: {
Namval_t *np = (Namval_t *)(lvalue->value);
np = scope(np, lvalue, 1);
nv_putval(np, (char *)&n, NV_LDOUBLE);
if (lvalue->eflag) lvalue->ptr = nv_hasdisc(np, &ENUM_disc);
lvalue->eflag = 0;
r = nv_getnum(np);
lvalue->value = (char *)np;
break;
}
case LOOKUP: {
int c = *str;
char *xp = str;
lvalue->value = NULL;
if (c == '.') str++;
c = mb1char(&str);
if (isaletter(c)) {
Namval_t *np = NULL;
int dot = 0;
while (1) {
xp = str;
while (c = mb1char(&str), isaname(c)) xp = str;
str = xp;
while (c == '[' && dot == NV_NOADD) {
str = nv_endsubscript(NULL, str, 0, shp);
c = *str;
}
if (c != '.') break;
dot = NV_NOADD;
c = *++str;
if (c != '[') continue;
str = nv_endsubscript(NULL, cp = str, NV_SUBQUOTE, shp) - 1;
if (sh_checkid(cp + 1, NULL)) str -= 2;
}
if (c == '(') {
int off = stktell(shp->stk);
int fsize = str - (char *)(*ptr);
const struct mathtab *tp;
Namval_t *nq;
lvalue->fun = NULL;
sfprintf(shp->stk, ".sh.math.%.*s%c", fsize, *ptr, 0);
stkseek(shp->stk, off);
nq = nv_search(stkptr(shp->stk, off), shp->fun_tree, 0);
if (nq) {
struct Ufunction *rp = FETCH_VT(nq->nvalue, rp);
lvalue->nargs = -rp->argc;
lvalue->fun = (Math_f)nq;
break;
}
if (fsize <= (sizeof(tp->fname) - 2)) {
lvalue->fun = (Math_f)sh_mathstdfun(*ptr, fsize, &lvalue->nargs);
}
if (lvalue->fun) break;
if (lvalue->emode & ARITH_COMP) {
lvalue->value = (char *)e_function;
} else {
lvalue->value = (char *)ERROR_dictionary(e_function);
}
return r;
}
if ((lvalue->emode & ARITH_COMP) && dot) {
lvalue->value = (char *)*ptr;
lvalue->flag = str - lvalue->value;
break;
}
*str = 0;
if (sh_isoption(shp, SH_NOEXEC)) {
np = VAR_underscore;
} else {
int offset = stktell(shp->stk);
char *saveptr = stkfreeze(shp->stk, 0);
Dt_t *root = (lvalue->emode & ARITH_COMP) ? shp->var_base : shp->var_tree;
*str = c;
cp = str;
while (c == '[' || c == '.') {
if (c == '[') {
str = nv_endsubscript(np, str, 0, shp);
c = *str;
if (c != '[' && c != '.') {
str = cp;
c = '[';
break;
}
} else {
dot = NV_NOADD | NV_NOFAIL;
str++;
xp = str;
while (c = mb1char(&str), isaname(c)) xp = str;
str = xp;
}
}
*str = 0;
cp = (char *)*ptr;
Varsubscript = false;
if ((cp[0] == 'i' || cp[0] == 'I') && (cp[1] == 'n' || cp[1] == 'N') &&
(cp[2] == 'f' || cp[2] == 'F') && cp[3] == 0) {
Inf = strtold("Inf", NULL);
STORE_VT(Infnod.nvalue, sfdoublep, &Inf);
np = &Infnod;
np->nvshell = shp;
nv_onattr(np, NV_NOFREE | NV_LDOUBLE | NV_RDONLY);
} else if ((cp[0] == 'n' || cp[0] == 'N') && (cp[1] == 'a' || cp[1] == 'A') &&
(cp[2] == 'n' || cp[2] == 'N') && cp[3] == 0) {
NaN = strtold("NaN", NULL);
STORE_VT(NaNnod.nvalue, sfdoublep, &NaN);
np = &NaNnod;
np->nvshell = shp;
nv_onattr(np, NV_NOFREE | NV_LDOUBLE | NV_RDONLY);
} else {
const struct Mathconst *mp = NULL;
np = NULL;
if (strchr("ELPS12", **ptr)) {
for (mp = Mtable; *mp->name; mp++) {
if (strcmp(mp->name, *ptr) == 0) break;
}
}
if (mp && *mp->name) {
r = mp->value;
lvalue->isfloat = TYPE_LD;
goto skip2;
}
if (shp->namref_root && !(lvalue->emode & ARITH_COMP)) {
np = nv_open(*ptr, shp->namref_root,
NV_NOREF | NV_VARNAME | NV_NOSCOPE | NV_NOADD | dot);
}
if (!np) {
np = nv_open(*ptr, root, NV_NOREF | NV_VARNAME | dot);
}
if (!np || Varsubscript) {
np = NULL;
lvalue->value = (char *)*ptr;
lvalue->flag = str - lvalue->value;
}
}
skip2:
if (saveptr != stkptr(shp->stk, 0)) {
stkset(shp->stk, saveptr, offset);
} else {
stkseek(shp->stk, offset);
}
}
*str = c;
if (lvalue->isfloat == TYPE_LD) break;
if (!np) break; // this used to also test `&& lvalue->value` but that's redundant
lvalue->value = (char *)np;
// Bind subscript later.
if (nv_isattr(np, NV_DOUBLE) == NV_DOUBLE) lvalue->isfloat = 1;
lvalue->flag = 0;
if (c == '[') {
lvalue->flag = (str - lvalue->expr);
do {
while (c == '.') {
str++;
while (xp = str, c = mb1char(&str), isaname(c)) {
; // empty body
}
c = *(str = xp);
}
if (c == '[') str = nv_endsubscript(np, str, 0, np->nvshell);
c = *str;
} while (c == '[' || c == '.');
break;
}
} else {
r = number(xp, &str, 0, lvalue);
}
break;
}
case VALUE: {
Namval_t *np = (Namval_t *)(lvalue->value);
Namarr_t *ap;
if (sh_isoption(shp, SH_NOEXEC)) return 0;
np = scope(np, lvalue, 0);
if (!np) {
if (sh_isoption(shp, SH_NOUNSET)) {
*ptr = lvalue->value;
goto skip;
}
return 0;
}
lvalue->ovalue = (char *)np;
if (lvalue->eflag) {
lvalue->ptr = nv_hasdisc(np, &ENUM_disc);
} else if ((Namfun_t *)lvalue->ptr && !nv_hasdisc(np, &ENUM_disc) &&
!nv_isattr(np, NV_INTEGER)) {
// TODO: The calloc() below should be considered a bandaid and may not be correct.
// See https://github.com/att/ast/issues/980. This dynamic allocation may leak some
// memory but that is preferable to referencing a stack var after this function
// returns. I think I have addressed this by removing the NV_NOFREE flag but I'm
// leaving this comment due to my low confidence.
Namval_t *mp = ((Namfun_t *)lvalue->ptr)->type;
Namval_t *node = calloc(1, sizeof(Namval_t));
nv_clone(mp, node, 0);
nv_offattr(node, NV_NOFREE);
nv_offattr(node, NV_RDONLY);
nv_putval(node, np->nvname, 0);
if (nv_isattr(node, NV_NOFREE)) return nv_getnum(node);
}
lvalue->eflag = 0;
if (((lvalue->emode & 2) || lvalue->level > 1 ||
(lvalue->nextop != A_STORE && sh_isoption(shp, SH_NOUNSET))) &&
nv_isnull(np) && !nv_isattr(np, NV_INTEGER)) {
*ptr = nv_name(np);
skip:
lvalue->value = (char *)ERROR_dictionary(e_notset);
lvalue->emode |= 010;
return 0;
}
if (lvalue->userfn) {
ap = nv_arrayptr(np);
if (ap && (ap->flags & ARRAY_UNDEF)) {
r = (Sfdouble_t)(uintptr_t)np;
lvalue->isfloat = 5;
return r;
}
}
r = nv_getnum(np);
if (nv_isattr(np, NV_INTEGER | NV_BINARY) == (NV_INTEGER | NV_BINARY)) {
lvalue->isfloat = (r != (Sflong_t)r) ? TYPE_LD : 0;
} else if (nv_isattr(np, (NV_DOUBLE | NV_SHORT)) == (NV_DOUBLE | NV_SHORT)) {
lvalue->isfloat = TYPE_F;
r = (float)r;
} else if (nv_isattr(np, (NV_DOUBLE | NV_LONG)) == (NV_DOUBLE | NV_LONG)) {
lvalue->isfloat = TYPE_LD;
} else if (nv_isattr(np, NV_DOUBLE) == NV_DOUBLE) {
lvalue->isfloat = TYPE_D;
r = (double)r;
}
if ((lvalue->emode & ARITH_ASSIGNOP) && nv_isarray(np)) {
lvalue->nosub = nv_aindex(np) + 1;
}
return r;
}
case MESSAGE: {
sfsync(NULL);
if (lvalue->emode & ARITH_COMP) return -1;
errormsg(SH_DICT, ERROR_exit((lvalue->emode & 3) != 0), lvalue->value, *ptr);
}
}
*ptr = str;
return r;
}
Sfdouble_t sh_arith(Shell_t *shp, const char *str) { return sh_strnum(shp, str, NULL, 1); }
void *sh_arithcomp(Shell_t *shp, char *str) {
const char *ptr = str;
Arith_t *ep;
ep = arith_compile(shp, str, (char **)&ptr, arith, ARITH_COMP | 1);
if (*ptr) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *ptr, str);
return ep;
}
// Convert number defined by string to a Sfdouble_t.
// Ptr is set to the last character processed.
// If mode>0, an error will be fatal with value <mode>.
Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {
Sfdouble_t d;
char *last;
if (*str == 0) {
if (ptr) *ptr = (char *)str;
return 0;
}
errno = 0;
d = number(str, &last, shp->inarith ? 0 : 10, NULL);
if (*last) {
if (*last != '.' || last[1] != '.') {
d = strval(shp, str, &last, arith, mode);
Varsubscript = true;
}
if (!ptr && *last && mode > 0) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);
} else if (!d && *str == '-') {
d = -0.0;
}
if (ptr) *ptr = last;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1003_1 |
crossvul-cpp_data_bad_4400_1 | /*
* Copyright (c) 2009, Natacha Porté
* Copyright (c) 2015, Vicent Marti
*
* 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 "markdown.h"
#include "html.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "houdini.h"
#define USE_XHTML(opt) (opt->flags & HTML_USE_XHTML)
int
sdhtml_is_tag(const uint8_t *tag_data, size_t tag_size, const char *tagname)
{
size_t i;
int closed = 0;
if (tag_size < 3 || tag_data[0] != '<')
return HTML_TAG_NONE;
i = 1;
if (tag_data[i] == '/') {
closed = 1;
i++;
}
for (; i < tag_size; ++i, ++tagname) {
if (*tagname == 0)
break;
if (tag_data[i] != *tagname)
return HTML_TAG_NONE;
}
if (i == tag_size)
return HTML_TAG_NONE;
if (isspace(tag_data[i]) || tag_data[i] == '>')
return closed ? HTML_TAG_CLOSE : HTML_TAG_OPEN;
return HTML_TAG_NONE;
}
static inline void escape_html(struct buf *ob, const uint8_t *source, size_t length)
{
houdini_escape_html0(ob, source, length, 0);
}
static inline void escape_href(struct buf *ob, const uint8_t *source, size_t length)
{
houdini_escape_href(ob, source, length);
}
/********************
* GENERIC RENDERER *
********************/
static int
rndr_autolink(struct buf *ob, const struct buf *link, enum mkd_autolink type, void *opaque)
{
struct html_renderopt *options = opaque;
if (!link || !link->size)
return 0;
if ((options->flags & HTML_SAFELINK) != 0 &&
!sd_autolink_issafe(link->data, link->size) &&
type != MKDA_EMAIL)
return 0;
BUFPUTSL(ob, "<a href=\"");
if (type == MKDA_EMAIL)
BUFPUTSL(ob, "mailto:");
escape_href(ob, link->data, link->size);
if (options->link_attributes) {
bufputc(ob, '\"');
options->link_attributes(ob, link, opaque);
bufputc(ob, '>');
} else {
BUFPUTSL(ob, "\">");
}
/*
* Pretty printing: if we get an email address as
* an actual URI, e.g. `mailto:foo@bar.com`, we don't
* want to print the `mailto:` prefix
*/
if (bufprefix(link, "mailto:") == 0) {
escape_html(ob, link->data + 7, link->size - 7);
} else {
escape_html(ob, link->data, link->size);
}
BUFPUTSL(ob, "</a>");
return 1;
}
static void
rndr_blockcode(struct buf *ob, const struct buf *text, const struct buf *lang, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size) bufputc(ob, '\n');
if (lang && lang->size) {
size_t i, cls;
if (options->flags & HTML_PRETTIFY) {
BUFPUTSL(ob, "<pre><code class=\"prettyprint lang-");
cls++;
} else {
BUFPUTSL(ob, "<pre><code class=\"");
}
for (i = 0, cls = 0; i < lang->size; ++i, ++cls) {
while (i < lang->size && isspace(lang->data[i]))
i++;
if (i < lang->size) {
size_t org = i;
while (i < lang->size && !isspace(lang->data[i]))
i++;
if (lang->data[org] == '.')
org++;
if (cls) bufputc(ob, ' ');
escape_html(ob, lang->data + org, i - org);
}
}
BUFPUTSL(ob, "\">");
} else if (options->flags & HTML_PRETTIFY) {
BUFPUTSL(ob, "<pre><code class=\"prettyprint\">");
} else {
BUFPUTSL(ob, "<pre><code>");
}
if (text)
escape_html(ob, text->data, text->size);
BUFPUTSL(ob, "</code></pre>\n");
}
static void
rndr_blockquote(struct buf *ob, const struct buf *text, void *opaque)
{
if (ob->size) bufputc(ob, '\n');
BUFPUTSL(ob, "<blockquote>\n");
if (text) bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</blockquote>\n");
}
static int
rndr_codespan(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
if (options->flags & HTML_PRETTIFY)
BUFPUTSL(ob, "<code class=\"prettyprint\">");
else
BUFPUTSL(ob, "<code>");
if (text) escape_html(ob, text->data, text->size);
BUFPUTSL(ob, "</code>");
return 1;
}
static int
rndr_strikethrough(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<del>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</del>");
return 1;
}
static int
rndr_double_emphasis(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<strong>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</strong>");
return 1;
}
static int
rndr_emphasis(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size) return 0;
BUFPUTSL(ob, "<em>");
if (text) bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</em>");
return 1;
}
static int
rndr_underline(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<u>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</u>");
return 1;
}
static int
rndr_highlight(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<mark>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</mark>");
return 1;
}
static int
rndr_quote(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size)
return 0;
BUFPUTSL(ob, "<q>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</q>");
return 1;
}
static int
rndr_linebreak(struct buf *ob, void *opaque)
{
struct html_renderopt *options = opaque;
bufputs(ob, USE_XHTML(options) ? "<br/>\n" : "<br>\n");
return 1;
}
static void
rndr_header_anchor(struct buf *out, const struct buf *anchor)
{
static const char *STRIPPED = " -&+$,/:;=?@\"#{}|^~[]`\\*()%.!'";
const uint8_t *a = anchor->data;
const size_t size = anchor->size;
size_t i = 0;
int stripped = 0, inserted = 0;
for (; i < size; ++i) {
// skip html tags
if (a[i] == '<') {
while (i < size && a[i] != '>')
i++;
// skip html entities
} else if (a[i] == '&') {
while (i < size && a[i] != ';')
i++;
}
// replace non-ascii or invalid characters with dashes
else if (!isascii(a[i]) || strchr(STRIPPED, a[i])) {
if (inserted && !stripped)
bufputc(out, '-');
// and do it only once
stripped = 1;
}
else {
bufputc(out, tolower(a[i]));
stripped = 0;
inserted++;
}
}
// replace the last dash if there was anything added
if (stripped && inserted)
out->size--;
// if anchor found empty, use djb2 hash for it
if (!inserted && anchor->size) {
unsigned long hash = 5381;
for (i = 0; i < size; ++i) {
hash = ((hash << 5) + hash) + a[i]; /* h * 33 + c */
}
bufprintf(out, "part-%lx", hash);
}
}
static void
rndr_header(struct buf *ob, const struct buf *text, int level, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size)
bufputc(ob, '\n');
if ((options->flags & HTML_TOC) && level >= options->toc_data.nesting_bounds[0] &&
level <= options->toc_data.nesting_bounds[1]) {
bufprintf(ob, "<h%d id=\"", level);
rndr_header_anchor(ob, text);
BUFPUTSL(ob, "\">");
}
else
bufprintf(ob, "<h%d>", level);
if (text) bufput(ob, text->data, text->size);
bufprintf(ob, "</h%d>\n", level);
}
static int
rndr_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)
{
struct html_renderopt *options = opaque;
if (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))
return 0;
BUFPUTSL(ob, "<a href=\"");
if (link && link->size)
escape_href(ob, link->data, link->size);
if (title && title->size) {
BUFPUTSL(ob, "\" title=\"");
escape_html(ob, title->data, title->size);
}
if (options->link_attributes) {
bufputc(ob, '\"');
options->link_attributes(ob, link, opaque);
bufputc(ob, '>');
} else {
BUFPUTSL(ob, "\">");
}
if (content && content->size) bufput(ob, content->data, content->size);
BUFPUTSL(ob, "</a>");
return 1;
}
static void
rndr_list(struct buf *ob, const struct buf *text, int flags, void *opaque)
{
if (ob->size) bufputc(ob, '\n');
bufput(ob, flags & MKD_LIST_ORDERED ? "<ol>\n" : "<ul>\n", 5);
if (text) bufput(ob, text->data, text->size);
bufput(ob, flags & MKD_LIST_ORDERED ? "</ol>\n" : "</ul>\n", 6);
}
static void
rndr_listitem(struct buf *ob, const struct buf *text, int flags, void *opaque)
{
BUFPUTSL(ob, "<li>");
if (text) {
size_t size = text->size;
while (size && text->data[size - 1] == '\n')
size--;
bufput(ob, text->data, size);
}
BUFPUTSL(ob, "</li>\n");
}
static void
rndr_paragraph(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
size_t i = 0;
if (ob->size) bufputc(ob, '\n');
if (!text || !text->size)
return;
while (i < text->size && isspace(text->data[i])) i++;
if (i == text->size)
return;
BUFPUTSL(ob, "<p>");
if (options->flags & HTML_HARD_WRAP) {
size_t org;
while (i < text->size) {
org = i;
while (i < text->size && text->data[i] != '\n')
i++;
if (i > org)
bufput(ob, text->data + org, i - org);
/*
* do not insert a line break if this newline
* is the last character on the paragraph
*/
if (i >= text->size - 1)
break;
rndr_linebreak(ob, opaque);
i++;
}
} else {
bufput(ob, &text->data[i], text->size - i);
}
BUFPUTSL(ob, "</p>\n");
}
static void
rndr_raw_block(struct buf *ob, const struct buf *text, void *opaque)
{
size_t org, size;
struct html_renderopt *options = opaque;
if (!text)
return;
size = text->size;
while (size > 0 && text->data[size - 1] == '\n')
size--;
for (org = 0; org < size && text->data[org] == '\n'; ++org)
if (org >= size)
return;
/* Remove style tags if the `:no_styles` option is enabled */
if ((options->flags & HTML_SKIP_STYLE) != 0 &&
sdhtml_is_tag(text->data, size, "style"))
return;
if (ob->size)
bufputc(ob, '\n');
bufput(ob, text->data + org, size - org);
bufputc(ob, '\n');
}
static int
rndr_triple_emphasis(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size) return 0;
BUFPUTSL(ob, "<strong><em>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</em></strong>");
return 1;
}
static void
rndr_hrule(struct buf *ob, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size) bufputc(ob, '\n');
bufputs(ob, USE_XHTML(options) ? "<hr/>\n" : "<hr>\n");
}
static int
rndr_image(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *alt, void *opaque)
{
struct html_renderopt *options = opaque;
if (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))
return 0;
BUFPUTSL(ob, "<img src=\"");
if (link && link->size)
escape_href(ob, link->data, link->size);
BUFPUTSL(ob, "\" alt=\"");
if (alt && alt->size)
escape_html(ob, alt->data, alt->size);
if (title && title->size) {
BUFPUTSL(ob, "\" title=\"");
escape_html(ob, title->data, title->size);
}
bufputs(ob, USE_XHTML(options) ? "\"/>" : "\">");
return 1;
}
static int
rndr_raw_html(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
/* HTML_ESCAPE overrides SKIP_HTML, SKIP_STYLE, SKIP_LINKS and SKIP_IMAGES
It doesn't see if there are any valid tags, just escape all of them. */
if((options->flags & HTML_ESCAPE) != 0) {
escape_html(ob, text->data, text->size);
return 1;
}
if ((options->flags & HTML_SKIP_HTML) != 0)
return 1;
if ((options->flags & HTML_SKIP_STYLE) != 0 &&
sdhtml_is_tag(text->data, text->size, "style"))
return 1;
if ((options->flags & HTML_SKIP_LINKS) != 0 &&
sdhtml_is_tag(text->data, text->size, "a"))
return 1;
if ((options->flags & HTML_SKIP_IMAGES) != 0 &&
sdhtml_is_tag(text->data, text->size, "img"))
return 1;
bufput(ob, text->data, text->size);
return 1;
}
static void
rndr_table(struct buf *ob, const struct buf *header, const struct buf *body, void *opaque)
{
if (ob->size) bufputc(ob, '\n');
BUFPUTSL(ob, "<table><thead>\n");
if (header)
bufput(ob, header->data, header->size);
BUFPUTSL(ob, "</thead><tbody>\n");
if (body)
bufput(ob, body->data, body->size);
BUFPUTSL(ob, "</tbody></table>\n");
}
static void
rndr_tablerow(struct buf *ob, const struct buf *text, void *opaque)
{
BUFPUTSL(ob, "<tr>\n");
if (text)
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</tr>\n");
}
static void
rndr_tablecell(struct buf *ob, const struct buf *text, int flags, void *opaque)
{
if (flags & MKD_TABLE_HEADER) {
BUFPUTSL(ob, "<th");
} else {
BUFPUTSL(ob, "<td");
}
switch (flags & MKD_TABLE_ALIGNMASK) {
case MKD_TABLE_ALIGN_CENTER:
BUFPUTSL(ob, " style=\"text-align: center\">");
break;
case MKD_TABLE_ALIGN_L:
BUFPUTSL(ob, " style=\"text-align: left\">");
break;
case MKD_TABLE_ALIGN_R:
BUFPUTSL(ob, " style=\"text-align: right\">");
break;
default:
BUFPUTSL(ob, ">");
}
if (text)
bufput(ob, text->data, text->size);
if (flags & MKD_TABLE_HEADER) {
BUFPUTSL(ob, "</th>\n");
} else {
BUFPUTSL(ob, "</td>\n");
}
}
static int
rndr_superscript(struct buf *ob, const struct buf *text, void *opaque)
{
if (!text || !text->size) return 0;
BUFPUTSL(ob, "<sup>");
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "</sup>");
return 1;
}
static void
rndr_normal_text(struct buf *ob, const struct buf *text, void *opaque)
{
if (text)
escape_html(ob, text->data, text->size);
}
static void
rndr_footnotes(struct buf *ob, const struct buf *text, void *opaque)
{
struct html_renderopt *options = opaque;
if (ob->size) bufputc(ob, '\n');
BUFPUTSL(ob, "<div class=\"footnotes\">\n");
bufputs(ob, USE_XHTML(options) ? "<hr/>\n" : "<hr>\n");
BUFPUTSL(ob, "<ol>\n");
if (text)
bufput(ob, text->data, text->size);
BUFPUTSL(ob, "\n</ol>\n</div>\n");
}
static void
rndr_footnote_def(struct buf *ob, const struct buf *text, unsigned int num, void *opaque)
{
size_t i = 0;
int pfound = 0;
/* insert anchor at the end of first paragraph block */
if (text) {
while ((i+3) < text->size) {
if (text->data[i++] != '<') continue;
if (text->data[i++] != '/') continue;
if (text->data[i++] != 'p' && text->data[i] != 'P') continue;
if (text->data[i] != '>') continue;
i -= 3;
pfound = 1;
break;
}
}
bufprintf(ob, "\n<li id=\"fn%d\">\n", num);
if (pfound) {
bufput(ob, text->data, i);
bufprintf(ob, " <a href=\"#fnref%d\">↩</a>", num);
bufput(ob, text->data + i, text->size - i);
} else if (text) {
bufput(ob, text->data, text->size);
}
BUFPUTSL(ob, "</li>\n");
}
static int
rndr_footnote_ref(struct buf *ob, unsigned int num, void *opaque)
{
bufprintf(ob, "<sup id=\"fnref%d\"><a href=\"#fn%d\">%d</a></sup>", num, num, num);
return 1;
}
static void
toc_header(struct buf *ob, const struct buf *text, int level, void *opaque)
{
struct html_renderopt *options = opaque;
if (level >= options->toc_data.nesting_bounds[0] &&
level <= options->toc_data.nesting_bounds[1]) {
/* set the level offset if this is the first header
* we're parsing for the document */
if (options->toc_data.current_level == 0)
options->toc_data.level_offset = level - 1;
level -= options->toc_data.level_offset;
if (level > options->toc_data.current_level) {
while (level > options->toc_data.current_level) {
BUFPUTSL(ob, "<ul>\n<li>\n");
options->toc_data.current_level++;
}
} else if (level < options->toc_data.current_level) {
BUFPUTSL(ob, "</li>\n");
while (level < options->toc_data.current_level) {
BUFPUTSL(ob, "</ul>\n</li>\n");
options->toc_data.current_level--;
}
BUFPUTSL(ob,"<li>\n");
} else {
BUFPUTSL(ob,"</li>\n<li>\n");
}
bufprintf(ob, "<a href=\"#");
rndr_header_anchor(ob, text);
BUFPUTSL(ob, "\">");
if (text) {
if (options->flags & HTML_ESCAPE)
escape_html(ob, text->data, text->size);
else
bufput(ob, text->data, text->size);
}
BUFPUTSL(ob, "</a>\n");
}
}
static int
toc_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)
{
if (content && content->size)
bufput(ob, content->data, content->size);
return 1;
}
static void
toc_finalize(struct buf *ob, void *opaque)
{
struct html_renderopt *options = opaque;
while (options->toc_data.current_level > 0) {
BUFPUTSL(ob, "</li>\n</ul>\n");
options->toc_data.current_level--;
}
}
void
sdhtml_toc_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)
{
static const struct sd_callbacks cb_default = {
NULL,
NULL,
NULL,
toc_header,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
rndr_footnotes,
rndr_footnote_def,
NULL,
rndr_codespan,
rndr_double_emphasis,
rndr_emphasis,
rndr_underline,
rndr_highlight,
rndr_quote,
NULL,
NULL,
toc_link,
NULL,
rndr_triple_emphasis,
rndr_strikethrough,
rndr_superscript,
rndr_footnote_ref,
NULL,
NULL,
NULL,
toc_finalize,
};
memset(options, 0x0, sizeof(struct html_renderopt));
options->flags = render_flags;
memcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));
}
void
sdhtml_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)
{
static const struct sd_callbacks cb_default = {
rndr_blockcode,
rndr_blockquote,
rndr_raw_block,
rndr_header,
rndr_hrule,
rndr_list,
rndr_listitem,
rndr_paragraph,
rndr_table,
rndr_tablerow,
rndr_tablecell,
rndr_footnotes,
rndr_footnote_def,
rndr_autolink,
rndr_codespan,
rndr_double_emphasis,
rndr_emphasis,
rndr_underline,
rndr_highlight,
rndr_quote,
rndr_image,
rndr_linebreak,
rndr_link,
rndr_raw_html,
rndr_triple_emphasis,
rndr_strikethrough,
rndr_superscript,
rndr_footnote_ref,
NULL,
rndr_normal_text,
NULL,
NULL,
};
/* Prepare the options pointer */
memset(options, 0x0, sizeof(struct html_renderopt));
options->flags = render_flags;
options->toc_data.nesting_bounds[0] = 1;
options->toc_data.nesting_bounds[1] = 6;
/* Prepare the callbacks */
memcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));
if (render_flags & HTML_SKIP_IMAGES)
callbacks->image = NULL;
if (render_flags & HTML_SKIP_LINKS) {
callbacks->link = NULL;
callbacks->autolink = NULL;
}
if (render_flags & HTML_SKIP_HTML || render_flags & HTML_ESCAPE)
callbacks->blockhtml = NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_4400_1 |
crossvul-cpp_data_bad_1204_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* reverse packet and flow */
SCLogDebug("reversing flow and packet");
PacketSwap(p);
FlowSwap(p->flow);
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permitted on SYN packet", ssn);
}
if (TCP_HAS_TFO(p)) {
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
if (p->payload_len) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
SCLogDebug("ssn: %p (TFO) [len: %d] isn %u base_seq %u next_seq %u payload len %u",
ssn, p->tcpvars.tfo.len, ssn->client.isn, ssn->client.base_seq, ssn->client.next_seq, p->payload_len);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
}
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
if (!(TCP_HAS_TFO(p) || (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN))) {
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
} else {
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: (TFO) ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
return -1;
}
SCLogDebug("ssn %p: (TFO) ACK match, packet ACK %" PRIu32 " == "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else if (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN) {
SCLogDebug("ssn %p: ACK received on TFO session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if ((ack_indicates_missed_3whs_ack_packet ||
(ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
if (ack_indicates_missed_3whs_ack_packet) {
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
} else {
SCLogDebug("ssn %p: (TFO) expected packet fits perfectly after SYN/ACK", ssn);
}
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
static inline void HandleThreadId(ThreadVars *tv, Packet *p, StreamTcpThread *stt)
{
const int idx = (!(PKT_IS_TOSERVER(p)));
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id[idx] == 0)) {
p->flow->thread_id[idx] = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id[idx])) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id[idx], tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
HandleThreadId(tv, p, stt);
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
if (p->flow->flags & FLOW_WRONG_THREAD ||
ssn->client.flags & STREAMTCP_STREAM_FLAG_GAP ||
ssn->server.flags & STREAMTCP_STREAM_FLAG_GAP)
{
/* Stream and/or session in known bad condition. Block events
* from being set. */
p->flags |= PKT_STREAM_NO_EVENTS;
}
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadExpand(ssn_pool);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
np->vlan_id[0] = f->vlan_id[0];
np->vlan_id[1] = f->vlan_id[1];
np->vlan_idx = f->vlan_idx;
np->livedev = (struct LiveDevice_ *)f->livedev;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_1204_0 |
crossvul-cpp_data_bad_5014_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-74/c/bad_5014_0 |
crossvul-cpp_data_good_4069_3 | /**
* @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 (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "private.h"
#include "mutt/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "gui/lib.h"
#include "mutt.h"
#include "lib.h"
#include "auth.h"
#include "commands.h"
#include "globals.h"
#include "hook.h"
#include "init.h"
#include "message.h"
#include "mutt_logging.h"
#include "mutt_socket.h"
#include "muttlib.h"
#include "mx.h"
#include "pattern.h"
#include "progress.h"
#include "sort.h"
#ifdef ENABLE_NLS
#include <libintl.h>
#endif
struct stat;
/* These Config Variables are only used in imap/imap.c */
#ifdef USE_ZLIB
bool C_ImapDeflate; ///< Config: (imap) Compress network traffic
#endif
bool C_ImapIdle; ///< Config: (imap) Use the IMAP IDLE extension to check for new mail
bool C_ImapRfc5161; ///< Config: (imap) Use the IMAP ENABLE extension to select capabilities
/**
* check_capabilities - Make sure we can log in to this server
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*/
static int check_capabilities(struct ImapAccountData *adata)
{
if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
imap_error("check_capabilities", adata->buf);
return -1;
}
if (!((adata->capabilities & IMAP_CAP_IMAP4) || (adata->capabilities & IMAP_CAP_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 NULL Failure
*
* return stream following FLAGS response
*/
static char *get_flags(struct ListHead *hflags, char *s)
{
/* sanity-check string */
const size_t plen = mutt_str_startswith(s, "FLAGS", CASE_IGNORE);
if (plen == 0)
{
mutt_debug(LL_DEBUG1, "not a FLAGS response: %s\n", s);
return NULL;
}
s += plen;
SKIPWS(s);
if (*s != '(')
{
mutt_debug(LL_DEBUG1, "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 != ')') && !IS_SPACE(*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(LL_DEBUG1, "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 aclflag
* @param[in] m Selected Imap Mailbox
* @param[in] aclflag Permissions, see #AclFlags
* @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 Mailbox *m, AclFlags aclflag, int flag,
const char *str, char *flags, size_t flsize)
{
if (m->rights & aclflag)
if (flag && imap_has_flag(&imap_mdata_get(m)->flags, str))
mutt_str_strcat(flags, flsize, str);
}
/**
* make_msg_set - Make a message set
* @param[in] m Selected Imap Mailbox
* @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 Mailbox *m, 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 ImapAccountData *adata = imap_adata_get(m);
if (!adata || (adata->mailbox != m))
return -1;
for (n = *pos; (n < m->msg_count) && (mutt_buffer_len(buf) < IMAP_MAX_CMDLEN); n++)
{
struct Email *e = m->emails[n];
if (!e)
break;
bool match = false; /* whether current message matches flag condition */
/* don't include pending expunged messages.
*
* TODO: can we unset active in cmd_parse_expunge() and
* cmd_parse_vanished() instead of checking for index != INT_MAX. */
if (e->active && (e->index != INT_MAX))
{
switch (flag)
{
case MUTT_DELETED:
if (e->deleted != imap_edata_get(e)->deleted)
match = invert ^ e->deleted;
break;
case MUTT_FLAG:
if (e->flagged != imap_edata_get(e)->flagged)
match = invert ^ e->flagged;
break;
case MUTT_OLD:
if (e->old != imap_edata_get(e)->old)
match = invert ^ e->old;
break;
case MUTT_READ:
if (e->read != imap_edata_get(e)->read)
match = invert ^ e->read;
break;
case MUTT_REPLIED:
if (e->replied != imap_edata_get(e)->replied)
match = invert ^ e->replied;
break;
case MUTT_TAG:
if (e->tagged)
match = true;
break;
case MUTT_TRASH:
if (e->deleted && !e->purge)
match = true;
break;
}
}
if (match && (!changed || e->changed))
{
count++;
if (setstart == 0)
{
setstart = imap_edata_get(e)->uid;
if (started)
{
mutt_buffer_add_printf(buf, ",%u", imap_edata_get(e)->uid);
}
else
{
mutt_buffer_add_printf(buf, "%u", imap_edata_get(e)->uid);
started = true;
}
}
/* tie up if the last message also matches */
else if (n == (m->msg_count - 1))
mutt_buffer_add_printf(buf, ":%u", imap_edata_get(e)->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 && (e->active || (n == adata->mailbox->msg_count - 1)))
{
if (imap_edata_get(m->emails[n - 1])->uid > setstart)
mutt_buffer_add_printf(buf, ":%u", imap_edata_get(m->emails[n - 1])->uid);
setstart = 0;
}
}
*pos = n;
return count;
}
/**
* compare_flags_for_copy - Compare local flags against the server
* @param e 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 Email *e)
{
struct ImapEmailData *edata = e->edata;
if (e->read != edata->read)
return true;
if (e->old != edata->old)
return true;
if (e->flagged != edata->flagged)
return true;
if (e->replied != edata->replied)
return true;
return false;
}
/**
* sync_helper - Sync flag changes to the server
* @param m Selected Imap Mailbox
* @param right ACL, see #AclFlags
* @param flag NeoMutt 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 Mailbox *m, AclFlags right, int flag, const char *name)
{
int count = 0;
int rc;
char buf[1024];
if (!m)
return -1;
if ((m->rights & right) == 0)
return 0;
if ((right == MUTT_ACL_WRITE) && !imap_has_flag(&imap_mdata_get(m)->flags, name))
return 0;
snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name);
rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, false);
if (rc < 0)
return rc;
count += rc;
buf[0] = '-';
rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, true);
if (rc < 0)
return rc;
count += rc;
return count;
}
/**
* 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 Connection *conn = NULL;
int rc = -1;
size_t matchlen;
matchlen = mutt_str_strlen(buf);
struct MailboxList ml = STAILQ_HEAD_INITIALIZER(ml);
neomutt_mailboxlist_get_all(&ml, NeoMutt, MUTT_MAILBOX_ANY);
struct MailboxNode *np = NULL;
STAILQ_FOREACH(np, &ml, entries)
{
if (!mutt_str_startswith(mailbox_path(np->mailbox), buf, CASE_MATCH))
continue;
if (rc)
{
mutt_str_strfcpy(buf, mailbox_path(np->mailbox), buflen);
rc = 0;
}
else
longest_common_prefix(buf, mailbox_path(np->mailbox), matchlen, buflen);
}
neomutt_mailboxlist_clear(&ml);
#if 0
TAILQ_FOREACH(conn, mutt_socket_head(), entries)
{
struct Url url = { 0 };
char urlstr[1024];
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);
}
}
#endif
return rc;
}
/**
* imap_create_mailbox - Create a new mailbox
* @param adata Imap Account data
* @param mailbox Mailbox to create
* @retval 0 Success
* @retval -1 Failure
*/
int imap_create_mailbox(struct ImapAccountData *adata, char *mailbox)
{
char buf[2048], mbox[1024];
imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), mailbox);
snprintf(buf, sizeof(buf), "CREATE %s", mbox);
if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(adata));
return -1;
}
return 0;
}
/**
* imap_access - Check permissions on an IMAP mailbox with a new connection
* @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.
* TODO: This method should take a Mailbox as parameter to be able to reuse the
* existing connection.
*/
int imap_access(const char *path)
{
if (imap_path_status(path, false) >= 0)
return 0;
return -1;
}
/**
* imap_rename_mailbox - Rename a mailbox
* @param adata Imap Account data
* @param oldname Existing mailbox
* @param newname New name for mailbox
* @retval 0 Success
* @retval -1 Failure
*/
int imap_rename_mailbox(struct ImapAccountData *adata, char *oldname, const char *newname)
{
char oldmbox[1024];
char newmbox[1024];
int rc = 0;
imap_munge_mbox_name(adata->unicode, oldmbox, sizeof(oldmbox), oldname);
imap_munge_mbox_name(adata->unicode, newmbox, sizeof(newmbox), newname);
struct Buffer *buf = mutt_buffer_pool_get();
mutt_buffer_printf(buf, "RENAME %s %s", oldmbox, newmbox);
if (imap_exec(adata, mutt_b2s(buf), IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
rc = -1;
mutt_buffer_pool_release(&buf);
return rc;
}
/**
* imap_delete_mailbox - Delete a mailbox
* @param m Mailbox
* @param path name of the mailbox to delete
* @retval 0 Success
* @retval -1 Failure
*/
int imap_delete_mailbox(struct Mailbox *m, char *path)
{
char buf[PATH_MAX + 7];
char mbox[PATH_MAX];
struct Url *url = url_parse(path);
struct ImapAccountData *adata = imap_adata_get(m);
imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), url->path);
url_free(&url);
snprintf(buf, sizeof(buf), "DELETE %s", mbox);
if (imap_exec(m->account->adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
return -1;
return 0;
}
/**
* imap_logout - Gracefully log out of server
* @param adata Imap Account data
*/
static void imap_logout(struct ImapAccountData *adata)
{
/* 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) */
if (adata->state == IMAP_DISCONNECTED)
{
return;
}
adata->status = IMAP_BYE;
imap_cmd_start(adata, "LOGOUT");
if ((C_ImapPollTimeout <= 0) || (mutt_socket_poll(adata->conn, C_ImapPollTimeout) != 0))
{
while (imap_cmd_step(adata) == IMAP_RES_CONTINUE)
; // do nothing
}
mutt_socket_close(adata->conn);
adata->state = IMAP_DISCONNECTED;
}
/**
* 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 Account *np = NULL;
TAILQ_FOREACH(np, &NeoMutt->accounts, entries)
{
if (np->type != MUTT_IMAP)
continue;
struct ImapAccountData *adata = np->adata;
if (!adata)
continue;
struct Connection *conn = adata->conn;
if (!conn || (conn->fd < 0))
continue;
mutt_message(_("Closing connection to %s..."), conn->account.host);
imap_logout(np->adata);
mutt_clear_error();
}
}
/**
* imap_read_literal - Read bytes bytes from server into file
* @param fp File handle for email file
* @param adata Imap Account 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 ImapAccountData *adata,
unsigned long bytes, struct Progress *pbar)
{
char c;
bool r = false;
struct Buffer buf = { 0 }; // Do not allocate, maybe it won't be used
if (C_DebugLevel >= IMAP_LOG_LTRL)
mutt_buffer_alloc(&buf, bytes + 10);
mutt_debug(LL_DEBUG2, "reading %ld bytes\n", bytes);
for (unsigned long pos = 0; pos < bytes; pos++)
{
if (mutt_socket_readchar(adata->conn, &c) != 1)
{
mutt_debug(LL_DEBUG1, "error during read, %ld bytes read\n", pos);
adata->status = IMAP_FATAL;
mutt_buffer_dealloc(&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 (C_DebugLevel >= IMAP_LOG_LTRL)
mutt_buffer_addch(&buf, c);
}
if (C_DebugLevel >= IMAP_LOG_LTRL)
{
mutt_debug(IMAP_LOG_LTRL, "\n%s", buf.data);
mutt_buffer_dealloc(&buf);
}
return 0;
}
/**
* imap_expunge_mailbox - Purge messages from the server
* @param m Mailbox
*
* 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 Mailbox *m)
{
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!adata || !mdata)
return;
struct Email *e = NULL;
#ifdef USE_HCACHE
mdata->hcache = imap_hcache_open(adata, mdata);
#endif
for (int i = 0; i < m->msg_count; i++)
{
e = m->emails[i];
if (!e)
break;
if (e->index == INT_MAX)
{
mutt_debug(LL_DEBUG2, "Expunging message UID %u\n", imap_edata_get(e)->uid);
e->deleted = true;
imap_cache_del(m, e);
#ifdef USE_HCACHE
imap_hcache_del(mdata, imap_edata_get(e)->uid);
#endif
mutt_hash_int_delete(mdata->uid_hash, imap_edata_get(e)->uid, e);
imap_edata_free((void **) &e->edata);
}
else
{
e->index = i;
/* NeoMutt has several places where it turns off e->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 ctx_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. */
e->active = true;
}
}
#ifdef USE_HCACHE
imap_hcache_close(mdata);
#endif
mailbox_changed(m, NT_MAILBOX_UPDATE);
mailbox_changed(m, NT_MAILBOX_RESORT);
}
/**
* imap_open_connection - Open an IMAP connection
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*/
int imap_open_connection(struct ImapAccountData *adata)
{
if (mutt_socket_open(adata->conn) < 0)
return -1;
adata->state = IMAP_CONNECTED;
if (imap_cmd_step(adata) != IMAP_RES_OK)
{
imap_close_connection(adata);
return -1;
}
if (mutt_str_startswith(adata->buf, "* OK", CASE_IGNORE))
{
if (!mutt_str_startswith(adata->buf, "* OK [CAPABILITY", CASE_IGNORE) &&
check_capabilities(adata))
{
goto bail;
}
#ifdef USE_SSL
/* Attempt STARTTLS if available and desired. */
if (!adata->conn->ssf && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS)))
{
enum QuadOption ans;
if (C_SslForceTls)
ans = MUTT_YES;
else if ((ans = query_quadoption(C_SslStarttls,
_("Secure connection with TLS?"))) == MUTT_ABORT)
{
goto err_close_conn;
}
if (ans == MUTT_YES)
{
enum ImapExecResult rc = imap_exec(adata, "STARTTLS", IMAP_CMD_SINGLE);
// Clear any data after the STARTTLS acknowledgement
mutt_socket_empty(adata->conn);
if (rc == IMAP_EXEC_FATAL)
goto bail;
if (rc != IMAP_EXEC_ERROR)
{
if (mutt_ssl_starttls(adata->conn))
{
mutt_error(_("Could not negotiate TLS connection"));
goto err_close_conn;
}
else
{
/* RFC2595 demands we recheck CAPABILITY after TLS completes. */
if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS))
goto bail;
}
}
}
}
if (C_SslForceTls && !adata->conn->ssf)
{
mutt_error(_("Encrypted connection unavailable"));
goto err_close_conn;
}
#endif
}
else if (mutt_str_startswith(adata->buf, "* PREAUTH", CASE_IGNORE))
{
#ifdef USE_SSL
/* An unencrypted PREAUTH response is most likely a MITM attack.
* Require a confirmation. */
if (adata->conn->ssf == 0)
{
bool proceed = true;
if (C_SslForceTls)
{
proceed = false;
}
else if (C_SslStarttls != MUTT_NO)
{
proceed = mutt_yesorno(_("Abort unencrypted PREAUTH connection?"),
C_SslStarttls) != MUTT_NO;
}
if (!proceed)
{
mutt_error(_("Encrypted connection unavailable"));
goto err_close_conn;
}
}
#endif
adata->state = IMAP_AUTHENTICATED;
if (check_capabilities(adata) != 0)
goto bail;
FREE(&adata->capstr);
}
else
{
imap_error("imap_open_connection()", adata->buf);
goto bail;
}
return 0;
#ifdef USE_SSL
err_close_conn:
imap_close_connection(adata);
#endif
bail:
FREE(&adata->capstr);
return -1;
}
/**
* imap_close_connection - Close an IMAP connection
* @param adata Imap Account data
*/
void imap_close_connection(struct ImapAccountData *adata)
{
if (adata->state != IMAP_DISCONNECTED)
{
mutt_socket_close(adata->conn);
adata->state = IMAP_DISCONNECTED;
}
adata->seqno = 0;
adata->nextcmd = 0;
adata->lastcmd = 0;
adata->status = 0;
memset(adata->cmds, 0, sizeof(struct ImapCommand) * adata->cmdslots);
}
/**
* 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 '\*'. Note that "flag" might contain additional
* whitespace at the end, so we really need to compare up to the length of each
* element in "flag_list".
*/
bool imap_has_flag(struct ListHead *flag_list, const char *flag)
{
if (STAILQ_EMPTY(flag_list))
return false;
const size_t flaglen = mutt_str_strlen(flag);
struct ListNode *np = NULL;
STAILQ_FOREACH(np, flag_list, entries)
{
const size_t nplen = strlen(np->data);
if ((flaglen >= nplen) && ((flag[nplen] == '\0') || (flag[nplen] == ' ')) &&
(mutt_str_strncasecmp(np->data, flag, nplen) == 0))
{
return true;
}
if (mutt_str_strcmp(np->data, "\\*") == 0)
return true;
}
return false;
}
/**
* compare_uid - Compare two Emails by UID - Implements ::sort_t
*/
static int compare_uid(const void *a, const void *b)
{
const struct Email *ea = *(struct Email const *const *) a;
const struct Email *eb = *(struct Email const *const *) b;
return imap_edata_get((struct Email *) ea)->uid -
imap_edata_get((struct Email *) eb)->uid;
}
/**
* imap_exec_msgset - Prepare commands for all messages matching conditions
* @param m Selected Imap Mailbox
* @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 Mailbox *m, const char *pre, const char *post,
int flag, bool changed, bool invert)
{
struct ImapAccountData *adata = imap_adata_get(m);
if (!adata || (adata->mailbox != m))
return -1;
struct Email **emails = NULL;
short oldsort;
int pos;
int rc;
int count = 0;
struct Buffer cmd = mutt_buffer_make(0);
/* 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 = C_Sort;
if (C_Sort != SORT_ORDER)
{
emails = m->emails;
// We overcommit here, just in case new mail arrives whilst we're sync-ing
m->emails = mutt_mem_malloc(m->email_max * sizeof(struct Email *));
memcpy(m->emails, emails, m->email_max * sizeof(struct Email *));
C_Sort = SORT_ORDER;
qsort(m->emails, m->msg_count, sizeof(struct Email *), compare_uid);
}
pos = 0;
do
{
mutt_buffer_reset(&cmd);
mutt_buffer_add_printf(&cmd, "%s ", pre);
rc = make_msg_set(m, &cmd, flag, changed, invert, &pos);
if (rc > 0)
{
mutt_buffer_add_printf(&cmd, " %s", post);
if (imap_exec(adata, cmd.data, IMAP_CMD_QUEUE) != IMAP_EXEC_SUCCESS)
{
rc = -1;
goto out;
}
count += rc;
}
} while (rc > 0);
rc = count;
out:
mutt_buffer_dealloc(&cmd);
if (oldsort != C_Sort)
{
C_Sort = oldsort;
FREE(&m->emails);
m->emails = emails;
}
return rc;
}
/**
* imap_sync_message_for_copy - Update server to reflect the flags of a single message
* @param[in] m Mailbox
* @param[in] e 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 Mailbox *m, struct Email *e,
struct Buffer *cmd, enum QuadOption *err_continue)
{
struct ImapAccountData *adata = imap_adata_get(m);
if (!adata || (adata->mailbox != m))
return -1;
char flags[1024];
char *tags = NULL;
char uid[11];
if (!compare_flags_for_copy(e))
{
if (e->deleted == imap_edata_get(e)->deleted)
e->changed = false;
return 0;
}
snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid);
mutt_buffer_reset(cmd);
mutt_buffer_addstr(cmd, "UID STORE ");
mutt_buffer_addstr(cmd, uid);
flags[0] = '\0';
set_flag(m, MUTT_ACL_SEEN, e->read, "\\Seen ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, e->old, "Old ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, e->flagged, "\\Flagged ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, e->replied, "\\Answered ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_DELETE, imap_edata_get(e)->deleted, "\\Deleted ", flags,
sizeof(flags));
if (m->rights & MUTT_ACL_WRITE)
{
/* restore system flags */
if (imap_edata_get(e)->flags_system)
mutt_str_strcat(flags, sizeof(flags), imap_edata_get(e)->flags_system);
/* set custom flags */
tags = driver_tags_get_with_hidden(&e->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 == '\0')
{
set_flag(m, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags));
set_flag(m, MUTT_ACL_DELETE, !imap_edata_get(e)->deleted, "\\Deleted ",
flags, sizeof(flags));
/* erase custom flags */
if ((m->rights & MUTT_ACL_WRITE) && imap_edata_get(e)->flags_remote)
mutt_str_strcat(flags, sizeof(flags), imap_edata_get(e)->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, ")");
/* after all this it's still possible to have no flags, if you
* have no ACL rights */
if (*flags && (imap_exec(adata, cmd->data, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) &&
err_continue && (*err_continue != MUTT_YES))
{
*err_continue = imap_continue("imap_sync_message: STORE failed", adata->buf);
if (*err_continue != MUTT_YES)
return -1;
}
/* server have now the updated flags */
FREE(&imap_edata_get(e)->flags_remote);
imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags);
if (e->deleted == imap_edata_get(e)->deleted)
e->changed = false;
return 0;
}
/**
* imap_check_mailbox - use the NOOP or IDLE command to poll for new mail
* @param m Mailbox
* @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 Mailbox *m, bool force)
{
if (!m || !m->account)
return -1;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
/* 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 rc = 0;
/* try IDLE first, unless force is set */
if (!force && C_ImapIdle && (adata->capabilities & IMAP_CAP_IDLE) &&
((adata->state != IMAP_IDLE) || (mutt_date_epoch() >= adata->lastread + C_ImapKeepalive)))
{
if (imap_cmd_idle(adata) < 0)
return -1;
}
if (adata->state == IMAP_IDLE)
{
while ((rc = mutt_socket_poll(adata->conn, 0)) > 0)
{
if (imap_cmd_step(adata) != IMAP_RES_CONTINUE)
{
mutt_debug(LL_DEBUG1, "Error reading IDLE response\n");
return -1;
}
}
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "Poll failed, disabling IDLE\n");
adata->capabilities &= ~IMAP_CAP_IDLE; // Clear the flag
}
}
if ((force || ((adata->state != IMAP_IDLE) &&
(mutt_date_epoch() >= adata->lastread + C_Timeout))) &&
(imap_exec(adata, "NOOP", IMAP_CMD_POLL) != IMAP_EXEC_SUCCESS))
{
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(adata);
if (mdata->check_status & IMAP_EXPUNGE_PENDING)
rc = MUTT_REOPENED;
else if (mdata->check_status & IMAP_NEWMAIL_PENDING)
rc = MUTT_NEW_MAIL;
else if (mdata->check_status & IMAP_FLAGS_PENDING)
rc = MUTT_FLAGS;
mdata->check_status = IMAP_OPEN_NO_FLAGS;
return rc;
}
/**
* imap_status - Refresh the number of total and new messages
* @param adata IMAP Account data
* @param mdata IMAP Mailbox data
* @param queue Queue the STATUS command
* @retval num Total number of messages
*/
static int imap_status(struct ImapAccountData *adata, struct ImapMboxData *mdata, bool queue)
{
char *uidvalidity_flag = NULL;
char cmd[2048];
if (!adata || !mdata)
return -1;
/* Don't issue STATUS on the selected mailbox, it will be NOOPed or
* IDLEd elsewhere.
* adata->mailbox may be NULL for connections other than the current
* mailbox's. */
if (adata->mailbox && (adata->mailbox->mdata == mdata))
{
adata->mailbox->has_new = false;
return mdata->messages;
}
if (adata->capabilities & IMAP_CAP_IMAP4REV1)
uidvalidity_flag = "UIDVALIDITY";
else if (adata->capabilities & IMAP_CAP_STATUS)
uidvalidity_flag = "UID-VALIDITY";
else
{
mutt_debug(LL_DEBUG2, "Server doesn't support STATUS\n");
return -1;
}
snprintf(cmd, sizeof(cmd), "STATUS %s (UIDNEXT %s UNSEEN RECENT MESSAGES)",
mdata->munge_name, uidvalidity_flag);
int rc = imap_exec(adata, cmd, queue ? IMAP_CMD_QUEUE : IMAP_CMD_NO_FLAGS | IMAP_CMD_POLL);
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "Error queueing command\n");
return rc;
}
return mdata->messages;
}
/**
* imap_mbox_check_stats - Check the Mailbox statistics - Implements MxOps::mbox_check_stats()
*/
static int imap_mbox_check_stats(struct Mailbox *m, int flags)
{
return imap_mailbox_status(m, true);
}
/**
* imap_path_status - Refresh the number of total and new messages
* @param path Mailbox path
* @param queue Queue the STATUS command
* @retval num Total number of messages
*/
int imap_path_status(const char *path, bool queue)
{
struct Mailbox *m = mx_mbox_find2(path);
if (m)
return imap_mailbox_status(m, queue);
// FIXME(sileht): Is that case possible ?
struct ImapAccountData *adata = NULL;
struct ImapMboxData *mdata = NULL;
if (imap_adata_find(path, &adata, &mdata) < 0)
return -1;
int rc = imap_status(adata, mdata, queue);
imap_mdata_free((void *) &mdata);
return rc;
}
/**
* imap_mailbox_status - Refresh the number of total and new messages
* @param m Mailbox
* @param queue Queue the STATUS command
* @retval num Total number of messages
* @retval -1 Error
*
* @note Prepare the mailbox if we are not connected
*/
int imap_mailbox_status(struct Mailbox *m, bool queue)
{
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!adata || !mdata)
return -1;
return imap_status(adata, mdata, queue);
}
/**
* 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 ImapAccountData *adata = NULL;
struct ImapMboxData *mdata = NULL;
char buf[2048];
struct Buffer err;
if (imap_adata_find(path, &adata, &mdata) < 0)
return -1;
if (C_ImapCheckSubscribed)
{
char mbox[1024];
mutt_buffer_init(&err);
err.dsize = 256;
err.data = mutt_mem_malloc(err.dsize);
size_t len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un");
imap_quote_string(mbox + len, sizeof(mbox) - len, path, true);
if (mutt_parse_rc_line(mbox, &err))
mutt_debug(LL_DEBUG1, "Error adding subscribed mailbox: %s\n", err.data);
FREE(&err.data);
}
if (subscribe)
mutt_message(_("Subscribing to %s..."), mdata->name);
else
mutt_message(_("Unsubscribing from %s..."), mdata->name);
snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mdata->munge_name);
if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
imap_mdata_free((void *) &mdata);
return -1;
}
if (subscribe)
mutt_message(_("Subscribed to %s"), mdata->name);
else
mutt_message(_("Unsubscribed from %s"), mdata->name);
imap_mdata_free((void *) &mdata);
return 0;
}
/**
* 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, const char *path)
{
struct ImapAccountData *adata = NULL;
struct ImapMboxData *mdata = NULL;
char tmp[2048];
struct ImapList listresp = { 0 };
char completion[1024];
int clen;
size_t matchlen = 0;
int completions = 0;
int rc;
if (imap_adata_find(path, &adata, &mdata) < 0)
{
mutt_str_strfcpy(buf, path, buflen);
return complete_hosts(buf, buflen);
}
/* fire off command */
snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"",
C_ImapListSubscribed ? "LSUB" : "LIST", mdata->real_name);
imap_cmd_start(adata, tmp);
/* and see what the results are */
mutt_str_strfcpy(completion, mdata->name, sizeof(completion));
imap_mdata_free((void *) &mdata);
adata->cmdresult = &listresp;
do
{
listresp.name = NULL;
rc = imap_cmd_step(adata);
if ((rc == IMAP_RES_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_RES_CONTINUE);
adata->cmdresult = NULL;
if (completions)
{
/* reformat output */
imap_qualify_path(buf, buflen, &adata->conn->account, completion);
mutt_pretty_mailbox(buf, buflen);
return 0;
}
return -1;
}
/**
* imap_fast_trash - Use server COPY command to copy deleted messages to trash
* @param m Mailbox
* @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 Mailbox *m, char *dest)
{
char prompt[1024];
int rc = -1;
bool triedcreate = false;
enum QuadOption err_continue = MUTT_NO;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapAccountData *dest_adata = NULL;
struct ImapMboxData *dest_mdata = NULL;
if (imap_adata_find(dest, &dest_adata, &dest_mdata) < 0)
return -1;
struct Buffer sync_cmd = mutt_buffer_make(0);
/* check that the save-to folder is in the same account */
if (!imap_account_match(&(adata->conn->account), &(dest_adata->conn->account)))
{
mutt_debug(LL_DEBUG3, "%s not same server as %s\n", dest, mailbox_path(m));
goto out;
}
for (int i = 0; i < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
if (e->active && e->changed && e->deleted && !e->purge)
{
rc = imap_sync_message_for_copy(m, e, &sync_cmd, &err_continue);
if (rc < 0)
{
mutt_debug(LL_DEBUG1, "could not sync\n");
goto out;
}
}
}
/* loop in case of TRYCREATE */
do
{
rc = imap_exec_msgset(m, "UID COPY", dest_mdata->munge_name, MUTT_TRASH, false, false);
if (rc == 0)
{
mutt_debug(LL_DEBUG1, "No messages to trash\n");
rc = -1;
goto out;
}
else if (rc < 0)
{
mutt_debug(LL_DEBUG1, "could not queue copy\n");
goto out;
}
else if (m->verbose)
{
mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc),
rc, dest_mdata->name);
}
/* let's get it on */
rc = imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS);
if (rc == IMAP_EXEC_ERROR)
{
if (triedcreate)
{
mutt_debug(LL_DEBUG1, "Already tried to create mailbox %s\n", dest_mdata->name);
break;
}
/* bail out if command failed for reasons other than nonexistent target */
if (!mutt_str_startswith(imap_get_qualifier(adata->buf), "[TRYCREATE]", CASE_IGNORE))
break;
mutt_debug(LL_DEBUG3, "server suggests TRYCREATE\n");
snprintf(prompt, sizeof(prompt), _("Create %s?"), dest_mdata->name);
if (C_Confirmcreate && (mutt_yesorno(prompt, MUTT_YES) != MUTT_YES))
{
mutt_clear_error();
goto out;
}
if (imap_create_mailbox(adata, dest_mdata->name) < 0)
break;
triedcreate = true;
}
} while (rc == IMAP_EXEC_ERROR);
if (rc != IMAP_EXEC_SUCCESS)
{
imap_error("imap_fast_trash", adata->buf);
goto out;
}
rc = IMAP_EXEC_SUCCESS;
out:
mutt_buffer_dealloc(&sync_cmd);
imap_mdata_free((void *) &dest_mdata);
return ((rc == IMAP_EXEC_SUCCESS) ? 0 : -1);
}
/**
* imap_sync_mailbox - Sync all the changes to the server
* @param m Mailbox
* @param expunge if true do expunge
* @param close if true we move imap state to CLOSE
* @retval #MUTT_REOPENED mailbox has been externally modified
* @retval #MUTT_NEW_MAIL new mail has arrived
* @retval 0 Success
* @retval -1 Error
*
* @note The flag retvals come from a call to imap_check_mailbox()
*/
int imap_sync_mailbox(struct Mailbox *m, bool expunge, bool close)
{
if (!m)
return -1;
struct Email **emails = NULL;
int oldsort;
int rc;
int check;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (adata->state < IMAP_SELECTED)
{
mutt_debug(LL_DEBUG2, "no mailbox selected\n");
return -1;
}
/* This function is only called when the calling code expects the context
* to be changed. */
imap_allow_reopen(m);
check = imap_check_mailbox(m, false);
if (check < 0)
return check;
/* if we are expunging anyway, we can do deleted messages very quickly... */
if (expunge && (m->rights & MUTT_ACL_DELETE))
{
rc = imap_exec_msgset(m, "UID STORE", "+FLAGS.SILENT (\\Deleted)",
MUTT_DELETED, true, false);
if (rc < 0)
{
mutt_error(_("Expunge failed"));
return rc;
}
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 < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
if (e->deleted && e->changed)
e->active = false;
}
if (m->verbose)
{
mutt_message(ngettext("Marking %d message deleted...",
"Marking %d messages deleted...", rc),
rc);
}
}
}
#ifdef USE_HCACHE
mdata->hcache = imap_hcache_open(adata, mdata);
#endif
/* save messages with real (non-flag) changes */
for (int i = 0; i < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
if (e->deleted)
{
imap_cache_del(m, e);
#ifdef USE_HCACHE
imap_hcache_del(mdata, imap_edata_get(e)->uid);
#endif
}
if (e->active && e->changed)
{
#ifdef USE_HCACHE
imap_hcache_put(mdata, e);
#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. */
/* TODO: why the e->env check? */
if ((e->env && e->env->changed) || e->attach_del)
{
/* L10N: The plural is chosen by the last %d, i.e. the total number */
if (m->verbose)
{
mutt_message(ngettext("Saving changed message... [%d/%d]",
"Saving changed messages... [%d/%d]", m->msg_count),
i + 1, m->msg_count);
}
bool save_append = m->append;
m->append = true;
mutt_save_message_ctx(e, true, false, false, m);
m->append = save_append;
/* TODO: why the check for h->env? Is this possible? */
if (e->env)
e->env->changed = 0;
}
}
}
#ifdef USE_HCACHE
imap_hcache_close(mdata);
#endif
/* presort here to avoid doing 10 resorts in imap_exec_msgset */
oldsort = C_Sort;
if (C_Sort != SORT_ORDER)
{
emails = m->emails;
m->emails = mutt_mem_malloc(m->msg_count * sizeof(struct Email *));
memcpy(m->emails, emails, m->msg_count * sizeof(struct Email *));
C_Sort = SORT_ORDER;
qsort(m->emails, m->msg_count, sizeof(struct Email *), mutt_get_sort_func(SORT_ORDER));
}
rc = sync_helper(m, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_OLD, "Old");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_SEEN, MUTT_READ, "\\Seen");
if (rc >= 0)
rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered");
if (oldsort != C_Sort)
{
C_Sort = oldsort;
FREE(&m->emails);
m->emails = emails;
}
/* Flush the queued flags if any were changed in sync_helper. */
if (rc > 0)
if (imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
rc = -1;
if (rc < 0)
{
if (close)
{
if (mutt_yesorno(_("Error saving flags. Close anyway?"), MUTT_NO) == MUTT_YES)
{
adata->state = IMAP_AUTHENTICATED;
return 0;
}
}
else
mutt_error(_("Error saving flags"));
return -1;
}
/* 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 < m->msg_count; i++)
{
struct Email *e = m->emails[i];
if (!e)
break;
struct ImapEmailData *edata = imap_edata_get(e);
edata->deleted = e->deleted;
edata->flagged = e->flagged;
edata->old = e->old;
edata->read = e->read;
edata->replied = e->replied;
e->changed = false;
}
m->changed = false;
/* We must send an EXPUNGE command if we're not closing. */
if (expunge && !close && (m->rights & MUTT_ACL_DELETE))
{
if (m->verbose)
mutt_message(_("Expunging messages from server..."));
/* Set expunge bit so we don't get spurious reopened messages */
mdata->reopen |= IMAP_EXPUNGE_EXPECTED;
if (imap_exec(adata, "EXPUNGE", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS)
{
mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
imap_error(_("imap_sync_mailbox: EXPUNGE failed"), adata->buf);
return -1;
}
mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED;
}
if (expunge && close)
{
adata->closing = true;
imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE);
adata->state = IMAP_AUTHENTICATED;
}
if (C_MessageCacheClean)
imap_cache_clean(m);
return check;
}
/**
* imap_ac_find - Find an Account that matches a Mailbox path - Implements MxOps::ac_find()
*/
static struct Account *imap_ac_find(struct Account *a, const char *path)
{
if (!a || (a->type != MUTT_IMAP) || !path)
return NULL;
struct Url *url = url_parse(path);
if (!url)
return NULL;
struct ImapAccountData *adata = a->adata;
struct ConnAccount *cac = &adata->conn->account;
if (mutt_str_strcasecmp(url->host, cac->host) != 0)
a = NULL;
else if (url->user && (mutt_str_strcasecmp(url->user, cac->user) != 0))
a = NULL;
url_free(&url);
return a;
}
/**
* imap_ac_add - Add a Mailbox to an Account - Implements MxOps::ac_add()
*/
static int imap_ac_add(struct Account *a, struct Mailbox *m)
{
if (!a || !m || (m->type != MUTT_IMAP))
return -1;
struct ImapAccountData *adata = a->adata;
if (!adata)
{
struct ConnAccount cac = { { 0 } };
char mailbox[PATH_MAX];
if (imap_parse_path(mailbox_path(m), &cac, mailbox, sizeof(mailbox)) < 0)
return -1;
adata = imap_adata_new(a);
adata->conn = mutt_conn_new(&cac);
if (!adata->conn)
{
imap_adata_free((void **) &adata);
return -1;
}
mutt_account_hook(m->realpath);
if (imap_login(adata) < 0)
{
imap_adata_free((void **) &adata);
return -1;
}
a->adata = adata;
a->adata_free = imap_adata_free;
}
if (!m->mdata)
{
struct Url *url = url_parse(mailbox_path(m));
struct ImapMboxData *mdata = imap_mdata_new(adata, url->path);
/* fixup path and realpath, mainly to replace / by /INBOX */
char buf[1024];
imap_qualify_path(buf, sizeof(buf), &adata->conn->account, mdata->name);
mutt_buffer_strcpy(&m->pathbuf, buf);
mutt_str_replace(&m->realpath, mailbox_path(m));
m->mdata = mdata;
m->mdata_free = imap_mdata_free;
url_free(&url);
}
return 0;
}
/**
* imap_mbox_select - Select a Mailbox
* @param m Mailbox
*/
static void imap_mbox_select(struct Mailbox *m)
{
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!adata || !mdata)
return;
const char *condstore = NULL;
#ifdef USE_HCACHE
if ((adata->capabilities & IMAP_CAP_CONDSTORE) && C_ImapCondstore)
condstore = " (CONDSTORE)";
else
#endif
condstore = "";
char buf[PATH_MAX];
snprintf(buf, sizeof(buf), "%s %s%s", m->readonly ? "EXAMINE" : "SELECT",
mdata->munge_name, condstore);
adata->state = IMAP_SELECTED;
imap_cmd_start(adata, buf);
}
/**
* imap_login - Open an IMAP connection
* @param adata Imap Account data
* @retval 0 Success
* @retval -1 Failure
*
* Ensure ImapAccountData is connected and logged into the imap server.
*/
int imap_login(struct ImapAccountData *adata)
{
if (!adata)
return -1;
if (adata->state == IMAP_DISCONNECTED)
{
mutt_buffer_reset(&adata->cmdbuf); // purge outstanding queued commands
imap_open_connection(adata);
}
if (adata->state == IMAP_CONNECTED)
{
if (imap_authenticate(adata) == IMAP_AUTH_SUCCESS)
{
adata->state = IMAP_AUTHENTICATED;
FREE(&adata->capstr);
if (adata->conn->ssf)
{
mutt_debug(LL_DEBUG2, "Communication encrypted at %d bits\n",
adata->conn->ssf);
}
}
else
mutt_account_unsetpass(&adata->conn->account);
}
if (adata->state == IMAP_AUTHENTICATED)
{
/* capabilities may have changed */
imap_exec(adata, "CAPABILITY", IMAP_CMD_PASS);
#ifdef USE_ZLIB
/* RFC4978 */
if ((adata->capabilities & IMAP_CAP_COMPRESS) && C_ImapDeflate &&
(imap_exec(adata, "COMPRESS DEFLATE", IMAP_CMD_PASS) == IMAP_EXEC_SUCCESS))
{
mutt_debug(LL_DEBUG2, "IMAP compression is enabled on connection to %s\n",
adata->conn->account.host);
mutt_zstrm_wrap_conn(adata->conn);
}
#endif
/* enable RFC6855, if the server supports that */
if (C_ImapRfc5161 && (adata->capabilities & IMAP_CAP_ENABLE))
imap_exec(adata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE);
/* enable QRESYNC. Advertising QRESYNC also means CONDSTORE
* is supported (even if not advertised), so flip that bit. */
if (adata->capabilities & IMAP_CAP_QRESYNC)
{
adata->capabilities |= IMAP_CAP_CONDSTORE;
if (C_ImapRfc5161 && C_ImapQresync)
imap_exec(adata, "ENABLE QRESYNC", IMAP_CMD_QUEUE);
}
/* get root delimiter, '/' as default */
adata->delim = '/';
imap_exec(adata, "LIST \"\" \"\"", IMAP_CMD_QUEUE);
/* we may need the root delimiter before we open a mailbox */
imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS);
/* select the mailbox that used to be open before disconnect */
if (adata->mailbox)
{
imap_mbox_select(adata->mailbox);
}
}
if (adata->state < IMAP_AUTHENTICATED)
return -1;
return 0;
}
/**
* imap_mbox_open - Open a mailbox - Implements MxOps::mbox_open()
*/
static int imap_mbox_open(struct Mailbox *m)
{
if (!m || !m->account || !m->mdata)
return -1;
char buf[PATH_MAX];
int count = 0;
int rc;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
mutt_debug(LL_DEBUG3, "opening %s, saving %s\n", m->pathbuf.data,
(adata->mailbox ? adata->mailbox->pathbuf.data : "(none)"));
adata->prev_mailbox = adata->mailbox;
adata->mailbox = m;
/* clear mailbox status */
adata->status = 0;
m->rights = 0;
mdata->new_mail_count = 0;
if (m->verbose)
mutt_message(_("Selecting %s..."), mdata->name);
/* pipeline ACL test */
if (adata->capabilities & IMAP_CAP_ACL)
{
snprintf(buf, sizeof(buf), "MYRIGHTS %s", mdata->munge_name);
imap_exec(adata, buf, IMAP_CMD_QUEUE);
}
/* assume we have all rights if ACL is unavailable */
else
{
m->rights |= MUTT_ACL_LOOKUP | MUTT_ACL_READ | MUTT_ACL_SEEN | MUTT_ACL_WRITE |
MUTT_ACL_INSERT | MUTT_ACL_POST | MUTT_ACL_CREATE | MUTT_ACL_DELETE;
}
/* pipeline the postponed count if possible */
struct Mailbox *m_postponed = mx_mbox_find2(C_Postponed);
struct ImapAccountData *postponed_adata = imap_adata_get(m_postponed);
if (postponed_adata &&
imap_account_match(&postponed_adata->conn->account, &adata->conn->account))
{
imap_mailbox_status(m_postponed, true);
}
if (C_ImapCheckSubscribed)
imap_exec(adata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE);
imap_mbox_select(m);
do
{
char *pc = NULL;
rc = imap_cmd_step(adata);
if (rc != IMAP_RES_CONTINUE)
break;
pc = adata->buf + 2;
/* Obtain list of available flags here, may be overridden by a
* PERMANENTFLAGS tag in the OK response */
if (mutt_str_startswith(pc, "FLAGS", CASE_IGNORE))
{
/* don't override PERMANENTFLAGS */
if (STAILQ_EMPTY(&mdata->flags))
{
mutt_debug(LL_DEBUG3, "Getting mailbox FLAGS\n");
pc = get_flags(&mdata->flags, pc);
if (!pc)
goto fail;
}
}
/* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */
else if (mutt_str_startswith(pc, "OK [PERMANENTFLAGS", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox PERMANENTFLAGS\n");
/* safe to call on NULL */
mutt_list_free(&mdata->flags);
/* skip "OK [PERMANENT" so syntax is the same as FLAGS */
pc += 13;
pc = get_flags(&(mdata->flags), pc);
if (!pc)
goto fail;
}
/* save UIDVALIDITY for the header cache */
else if (mutt_str_startswith(pc, "OK [UIDVALIDITY", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox UIDVALIDITY\n");
pc += 3;
pc = imap_next_word(pc);
if (mutt_str_atoui(pc, &mdata->uidvalidity) < 0)
goto fail;
}
else if (mutt_str_startswith(pc, "OK [UIDNEXT", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox UIDNEXT\n");
pc += 3;
pc = imap_next_word(pc);
if (mutt_str_atoui(pc, &mdata->uid_next) < 0)
goto fail;
}
else if (mutt_str_startswith(pc, "OK [HIGHESTMODSEQ", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Getting mailbox HIGHESTMODSEQ\n");
pc += 3;
pc = imap_next_word(pc);
if (mutt_str_atoull(pc, &mdata->modseq) < 0)
goto fail;
}
else if (mutt_str_startswith(pc, "OK [NOMODSEQ", CASE_IGNORE))
{
mutt_debug(LL_DEBUG3, "Mailbox has NOMODSEQ set\n");
mdata->modseq = 0;
}
else
{
pc = imap_next_word(pc);
if (mutt_str_startswith(pc, "EXISTS", CASE_IGNORE))
{
count = mdata->new_mail_count;
mdata->new_mail_count = 0;
}
}
} while (rc == IMAP_RES_CONTINUE);
if (rc == IMAP_RES_NO)
{
char *s = imap_next_word(adata->buf); /* skip seq */
s = imap_next_word(s); /* Skip response */
mutt_error("%s", s);
goto fail;
}
if (rc != IMAP_RES_OK)
goto fail;
/* check for READ-ONLY notification */
if (mutt_str_startswith(imap_get_qualifier(adata->buf), "[READ-ONLY]", CASE_IGNORE) &&
!(adata->capabilities & IMAP_CAP_ACL))
{
mutt_debug(LL_DEBUG2, "Mailbox is read-only\n");
m->readonly = true;
}
/* dump the mailbox flags we've found */
if (C_DebugLevel > LL_DEBUG2)
{
if (STAILQ_EMPTY(&mdata->flags))
mutt_debug(LL_DEBUG3, "No folder flags found\n");
else
{
struct ListNode *np = NULL;
struct Buffer flag_buffer;
mutt_buffer_init(&flag_buffer);
mutt_buffer_printf(&flag_buffer, "Mailbox flags: ");
STAILQ_FOREACH(np, &mdata->flags, entries)
{
mutt_buffer_add_printf(&flag_buffer, "[%s] ", np->data);
}
mutt_debug(LL_DEBUG3, "%s\n", flag_buffer.data);
FREE(&flag_buffer.data);
}
}
if (!((m->rights & MUTT_ACL_DELETE) || (m->rights & MUTT_ACL_SEEN) ||
(m->rights & MUTT_ACL_WRITE) || (m->rights & MUTT_ACL_INSERT)))
{
m->readonly = true;
}
while (m->email_max < count)
mx_alloc_memory(m);
m->msg_count = 0;
m->msg_unread = 0;
m->msg_flagged = 0;
m->msg_new = 0;
m->msg_deleted = 0;
m->size = 0;
m->vcount = 0;
if (count && (imap_read_headers(m, 1, count, true) < 0))
{
mutt_error(_("Error opening mailbox"));
goto fail;
}
mutt_debug(LL_DEBUG2, "msg_count is %d\n", m->msg_count);
return 0;
fail:
if (adata->state == IMAP_SELECTED)
adata->state = IMAP_AUTHENTICATED;
return -1;
}
/**
* imap_mbox_open_append - Open a Mailbox for appending - Implements MxOps::mbox_open_append()
*/
static int imap_mbox_open_append(struct Mailbox *m, OpenMailboxFlags flags)
{
if (!m || !m->account)
return -1;
/* in APPEND mode, we appear to hijack an existing IMAP connection -
* ctx is brand new and mostly empty */
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
int rc = imap_mailbox_status(m, false);
if (rc >= 0)
return 0;
if (rc == -1)
return -1;
char buf[PATH_MAX + 64];
snprintf(buf, sizeof(buf), _("Create %s?"), mdata->name);
if (C_Confirmcreate && (mutt_yesorno(buf, MUTT_YES) != MUTT_YES))
return -1;
if (imap_create_mailbox(adata, mdata->name) < 0)
return -1;
return 0;
}
/**
* imap_mbox_check - Check for new mail - Implements MxOps::mbox_check()
* @param m Mailbox
* @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 Mailbox *m, int *index_hint)
{
if (!m)
return -1;
imap_allow_reopen(m);
int rc = imap_check_mailbox(m, false);
/* NOTE - ctx might have been changed at this point. In particular,
* m could be NULL. Beware. */
imap_disallow_reopen(m);
return rc;
}
/**
* imap_mbox_close - Close a Mailbox - Implements MxOps::mbox_close()
*/
static int imap_mbox_close(struct Mailbox *m)
{
if (!m)
return -1;
struct ImapAccountData *adata = imap_adata_get(m);
struct ImapMboxData *mdata = imap_mdata_get(m);
/* Check to see if the mailbox is actually open */
if (!adata || !mdata)
return 0;
/* imap_mbox_open_append() borrows the struct ImapAccountData temporarily,
* just for the connection.
*
* So when these are equal, it means we are actually closing the
* mailbox and should clean up adata. Otherwise, we don't want to
* touch adata - it's still being used. */
if (m == adata->mailbox)
{
if ((adata->status != IMAP_FATAL) && (adata->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 (m->msg_deleted == 0)
{
adata->closing = true;
imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE);
}
adata->state = IMAP_AUTHENTICATED;
}
mutt_debug(LL_DEBUG3, "closing %s, restoring %s\n", m->pathbuf.data,
(adata->prev_mailbox ? adata->prev_mailbox->pathbuf.data : "(none)"));
adata->mailbox = adata->prev_mailbox;
imap_mbox_select(adata->prev_mailbox);
imap_mdata_cache_reset(m->mdata);
}
return 0;
}
/**
* imap_msg_open_new - Open a new message in a Mailbox - Implements MxOps::msg_open_new()
*/
static int imap_msg_open_new(struct Mailbox *m, struct Message *msg, struct Email *e)
{
int rc = -1;
struct Buffer *tmp = mutt_buffer_pool_get();
mutt_buffer_mktemp(tmp);
msg->fp = mutt_file_fopen(mutt_b2s(tmp), "w");
if (!msg->fp)
{
mutt_perror(mutt_b2s(tmp));
goto cleanup;
}
msg->path = mutt_buffer_strdup(tmp);
rc = 0;
cleanup:
mutt_buffer_pool_release(&tmp);
return rc;
}
/**
* imap_tags_edit - Prompt and validate new messages tags - Implements MxOps::tags_edit()
*/
static int imap_tags_edit(struct Mailbox *m, const char *tags, char *buf, size_t buflen)
{
struct ImapMboxData *mdata = imap_mdata_get(m);
if (!mdata)
return -1;
char *new_tag = NULL;
char *checker = NULL;
/* Check for \* flags capability */
if (!imap_has_flag(&mdata->flags, NULL))
{
mutt_error(_("IMAP server doesn't support custom flags"));
return -1;
}
*buf = '\0';
if (tags)
mutt_str_strfcpy(buf, tags, buflen);
if (mutt_get_field("Tags: ", buf, buflen, MUTT_COMP_NO_FLAGS) != 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_tag = 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[0] == ' ') && (checker[1] == ' '))
checker++;
/* copy char to new_tag and go the next one */
*new_tag++ = *checker++;
}
*new_tag = '\0';
new_tag = buf; /* rewind */
mutt_str_remove_trailing_ws(new_tag);
if (mutt_str_strcmp(tags, buf) == 0)
return 0;
return 1;
}
/**
* imap_tags_commit - Save the tags to a message - 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 Mailbox *m, struct Email *e, char *buf)
{
if (!m)
return -1;
char uid[11];
struct ImapAccountData *adata = imap_adata_get(m);
if (*buf == '\0')
buf = NULL;
if (!(adata->mailbox->rights & MUTT_ACL_WRITE))
return 0;
snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid);
/* Remove old custom flags */
if (imap_edata_get(e)->flags_remote)
{
struct Buffer cmd = mutt_buffer_make(128); // just a guess
mutt_buffer_addstr(&cmd, "UID STORE ");
mutt_buffer_addstr(&cmd, uid);
mutt_buffer_addstr(&cmd, " -FLAGS.SILENT (");
mutt_buffer_addstr(&cmd, imap_edata_get(e)->flags_remote);
mutt_buffer_addstr(&cmd, ")");
/* Should we return here, or we are fine and we could
* continue to add new flags */
int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS);
mutt_buffer_dealloc(&cmd);
if (rc != IMAP_EXEC_SUCCESS)
{
return -1;
}
}
/* Add new custom flags */
if (buf)
{
struct Buffer cmd = mutt_buffer_make(128); // just a guess
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, ")");
int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS);
mutt_buffer_dealloc(&cmd);
if (rc != IMAP_EXEC_SUCCESS)
{
mutt_debug(LL_DEBUG1, "fail to add new flags\n");
return -1;
}
}
/* We are good sync them */
mutt_debug(LL_DEBUG1, "NEW TAGS: %s\n", buf);
driver_tags_replace(&e->tags, buf);
FREE(&imap_edata_get(e)->flags_remote);
imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags);
return 0;
}
/**
* imap_path_probe - Is this an IMAP Mailbox? - Implements MxOps::path_probe()
*/
enum MailboxType imap_path_probe(const char *path, const struct stat *st)
{
if (!path)
return MUTT_UNKNOWN;
if (mutt_str_startswith(path, "imap://", CASE_IGNORE))
return MUTT_IMAP;
if (mutt_str_startswith(path, "imaps://", CASE_IGNORE))
return MUTT_IMAP;
return MUTT_UNKNOWN;
}
/**
* imap_path_canon - Canonicalise a Mailbox path - Implements MxOps::path_canon()
*/
int imap_path_canon(char *buf, size_t buflen)
{
if (!buf)
return -1;
struct Url *url = url_parse(buf);
if (!url)
return 0;
char tmp[PATH_MAX];
char tmp2[PATH_MAX];
imap_fix_path('\0', url->path, tmp, sizeof(tmp));
url->path = tmp;
url_tostring(url, tmp2, sizeof(tmp2), 0);
mutt_str_strfcpy(buf, tmp2, buflen);
url_free(&url);
return 0;
}
/**
* imap_expand_path - Buffer wrapper around imap_path_canon()
* @param buf Path to expand
* @retval 0 Success
* @retval -1 Failure
*
* @note The path is expanded in place
*/
int imap_expand_path(struct Buffer *buf)
{
mutt_buffer_alloc(buf, PATH_MAX);
return imap_path_canon(buf->data, PATH_MAX);
}
/**
* imap_path_pretty - Abbreviate a Mailbox path - Implements MxOps::path_pretty()
*/
static int imap_path_pretty(char *buf, size_t buflen, const char *folder)
{
if (!buf || !folder)
return -1;
imap_pretty_mailbox(buf, buflen, folder);
return 0;
}
/**
* imap_path_parent - Find the parent of a Mailbox path - Implements MxOps::path_parent()
*/
static int imap_path_parent(char *buf, size_t buflen)
{
char tmp[PATH_MAX] = { 0 };
imap_get_parent_path(buf, tmp, sizeof(tmp));
mutt_str_strfcpy(buf, tmp, buflen);
return 0;
}
// clang-format off
/**
* MxImapOps - IMAP Mailbox - Implements ::MxOps
*/
struct MxOps MxImapOps = {
.type = MUTT_IMAP,
.name = "imap",
.is_local = false,
.ac_find = imap_ac_find,
.ac_add = imap_ac_add,
.mbox_open = imap_mbox_open,
.mbox_open_append = imap_mbox_open_append,
.mbox_check = imap_mbox_check,
.mbox_check_stats = imap_mbox_check_stats,
.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,
.msg_padding_size = NULL,
.msg_save_hcache = imap_msg_save_hcache,
.tags_edit = imap_tags_edit,
.tags_commit = imap_tags_commit,
.path_probe = imap_path_probe,
.path_canon = imap_path_canon,
.path_pretty = imap_path_pretty,
.path_parent = imap_path_parent,
};
// clang-format on
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_4069_3 |
crossvul-cpp_data_bad_4069_6 | /**
* @file
* POP helper routines
*
* @authors
* Copyright (C) 2000-2003 Vsevolod Volkov <vvv@mutt.org.ua>
* Copyright (C) 2018 Richard Russon <rich@flatcap.org>
*
* @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 pop_lib POP helper routines
*
* POP helper routines
*/
#include "config.h"
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "private.h"
#include "mutt/lib.h"
#include "config/lib.h"
#include "email/lib.h"
#include "core/lib.h"
#include "conn/lib.h"
#include "init.h"
#include "mutt_account.h"
#include "mutt_logging.h"
#include "mutt_socket.h"
#include "progress.h"
#ifdef USE_SSL
#include "globals.h"
#endif
/* These Config Variables are only used in pop/pop_lib.c */
char *C_PopOauthRefreshCommand; ///< Config: (pop) External command to generate OAUTH refresh token
char *C_PopPass; ///< Config: (pop) Password of the POP server
unsigned char C_PopReconnect; ///< Config: (pop) Reconnect to the server is the connection is lost
char *C_PopUser; ///< Config: (pop) Username of the POP server
/**
* pop_get_field - Get connection login credentials - Implements ConnAccount::get_field()
*/
const char *pop_get_field(enum ConnAccountField field)
{
switch (field)
{
case MUTT_CA_LOGIN:
case MUTT_CA_USER:
return C_PopUser;
case MUTT_CA_PASS:
return C_PopPass;
case MUTT_CA_OAUTH_CMD:
return C_PopOauthRefreshCommand;
case MUTT_CA_HOST:
default:
return NULL;
}
}
/**
* pop_parse_path - Parse a POP mailbox name
* @param path Path to parse
* @param cac Account to store details
* @retval 0 success
* @retval -1 error
*
* Split a POP path into host, port, username and password
*/
int pop_parse_path(const char *path, struct ConnAccount *cac)
{
/* Defaults */
cac->flags = 0;
cac->type = MUTT_ACCT_TYPE_POP;
cac->port = 0;
cac->service = "pop";
cac->get_field = pop_get_field;
struct Url *url = url_parse(path);
if (!url || ((url->scheme != U_POP) && (url->scheme != U_POPS)) ||
!url->host || (mutt_account_fromurl(cac, url) < 0))
{
url_free(&url);
mutt_error(_("Invalid POP URL: %s"), path);
return -1;
}
if (url->scheme == U_POPS)
cac->flags |= MUTT_ACCT_SSL;
struct servent *service =
getservbyname((url->scheme == U_POP) ? "pop3" : "pop3s", "tcp");
if (cac->port == 0)
{
if (service)
cac->port = ntohs(service->s_port);
else
cac->port = (url->scheme == U_POP) ? POP_PORT : POP_SSL_PORT;
}
url_free(&url);
return 0;
}
/**
* pop_error - Copy error message to err_msg buffer
* @param adata POP Account data
* @param msg Error message to save
*/
static void pop_error(struct PopAccountData *adata, char *msg)
{
char *t = strchr(adata->err_msg, '\0');
char *c = msg;
size_t plen = mutt_str_startswith(msg, "-ERR ", CASE_MATCH);
if (plen != 0)
{
char *c2 = mutt_str_skip_email_wsp(msg + plen);
if (*c2)
c = c2;
}
mutt_str_strfcpy(t, c, sizeof(adata->err_msg) - strlen(adata->err_msg));
mutt_str_remove_trailing_ws(adata->err_msg);
}
/**
* fetch_capa - Parse CAPA output - Implements ::pop_fetch_t
* @param line List of capabilities
* @param data POP data
* @retval 0 (always)
*/
static int fetch_capa(const char *line, void *data)
{
struct PopAccountData *adata = data;
if (mutt_str_startswith(line, "SASL", CASE_IGNORE))
{
const char *c = mutt_str_skip_email_wsp(line + 4);
mutt_buffer_strcpy(&adata->auth_list, c);
}
else if (mutt_str_startswith(line, "STLS", CASE_IGNORE))
adata->cmd_stls = true;
else if (mutt_str_startswith(line, "USER", CASE_IGNORE))
adata->cmd_user = 1;
else if (mutt_str_startswith(line, "UIDL", CASE_IGNORE))
adata->cmd_uidl = 1;
else if (mutt_str_startswith(line, "TOP", CASE_IGNORE))
adata->cmd_top = 1;
return 0;
}
/**
* fetch_auth - Fetch list of the authentication mechanisms - Implements ::pop_fetch_t
* @param line List of authentication methods
* @param data POP data
* @retval 0 (always)
*/
static int fetch_auth(const char *line, void *data)
{
struct PopAccountData *adata = data;
if (!mutt_buffer_is_empty(&adata->auth_list))
{
mutt_buffer_addstr(&adata->auth_list, " ");
}
mutt_buffer_addstr(&adata->auth_list, line);
return 0;
}
/**
* pop_capabilities - Get capabilities from a POP server
* @param adata POP Account data
* @param mode Initial capabilities
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Execution error
*/
static int pop_capabilities(struct PopAccountData *adata, int mode)
{
char buf[1024];
/* don't check capabilities on reconnect */
if (adata->capabilities)
return 0;
/* init capabilities */
if (mode == 0)
{
adata->cmd_capa = false;
adata->cmd_stls = false;
adata->cmd_user = 0;
adata->cmd_uidl = 0;
adata->cmd_top = 0;
adata->resp_codes = false;
adata->expire = true;
adata->login_delay = 0;
mutt_buffer_init(&adata->auth_list);
}
/* Execute CAPA command */
if ((mode == 0) || adata->cmd_capa)
{
mutt_str_strfcpy(buf, "CAPA\r\n", sizeof(buf));
switch (pop_fetch_data(adata, buf, NULL, fetch_capa, adata))
{
case 0:
{
adata->cmd_capa = true;
break;
}
case -1:
return -1;
}
}
/* CAPA not supported, use defaults */
if ((mode == 0) && !adata->cmd_capa)
{
adata->cmd_user = 2;
adata->cmd_uidl = 2;
adata->cmd_top = 2;
mutt_str_strfcpy(buf, "AUTH\r\n", sizeof(buf));
if (pop_fetch_data(adata, buf, NULL, fetch_auth, adata) == -1)
return -1;
}
/* Check capabilities */
if (mode == 2)
{
char *msg = NULL;
if (!adata->expire)
msg = _("Unable to leave messages on server");
if (adata->cmd_top == 0)
msg = _("Command TOP is not supported by server");
if (adata->cmd_uidl == 0)
msg = _("Command UIDL is not supported by server");
if (msg && adata->cmd_capa)
{
mutt_error(msg);
return -2;
}
adata->capabilities = true;
}
return 0;
}
/**
* pop_edata_get - Get the private data for this Email
* @param e Email
* @retval ptr Private Email data
*/
struct PopEmailData *pop_edata_get(struct Email *e)
{
if (!e)
return NULL;
return e->edata;
}
/**
* pop_connect - Open connection
* @param adata POP Account data
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid response
*/
int pop_connect(struct PopAccountData *adata)
{
char buf[1024];
adata->status = POP_NONE;
if ((mutt_socket_open(adata->conn) < 0) ||
(mutt_socket_readln(buf, sizeof(buf), adata->conn) < 0))
{
mutt_error(_("Error connecting to server: %s"), adata->conn->account.host);
return -1;
}
adata->status = POP_CONNECTED;
if (!mutt_str_startswith(buf, "+OK", CASE_MATCH))
{
*adata->err_msg = '\0';
pop_error(adata, buf);
mutt_error("%s", adata->err_msg);
return -2;
}
pop_apop_timestamp(adata, buf);
return 0;
}
/**
* pop_open_connection - Open connection and authenticate
* @param adata POP Account data
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
* @retval -3 Authentication cancelled
*/
int pop_open_connection(struct PopAccountData *adata)
{
char buf[1024];
int rc = pop_connect(adata);
if (rc < 0)
return rc;
rc = pop_capabilities(adata, 0);
if (rc == -1)
goto err_conn;
if (rc == -2)
return -2;
#ifdef USE_SSL
/* Attempt STLS if available and desired. */
if (!adata->conn->ssf && (adata->cmd_stls || C_SslForceTls))
{
if (C_SslForceTls)
adata->use_stls = 2;
if (adata->use_stls == 0)
{
enum QuadOption ans =
query_quadoption(C_SslStarttls, _("Secure connection with TLS?"));
if (ans == MUTT_ABORT)
return -2;
adata->use_stls = 1;
if (ans == MUTT_YES)
adata->use_stls = 2;
}
if (adata->use_stls == 2)
{
mutt_str_strfcpy(buf, "STLS\r\n", sizeof(buf));
rc = pop_query(adata, buf, sizeof(buf));
if (rc == -1)
goto err_conn;
if (rc != 0)
{
mutt_error("%s", adata->err_msg);
}
else if (mutt_ssl_starttls(adata->conn))
{
mutt_error(_("Could not negotiate TLS connection"));
return -2;
}
else
{
/* recheck capabilities after STLS completes */
rc = pop_capabilities(adata, 1);
if (rc == -1)
goto err_conn;
if (rc == -2)
return -2;
}
}
}
if (C_SslForceTls && !adata->conn->ssf)
{
mutt_error(_("Encrypted connection unavailable"));
return -2;
}
#endif
rc = pop_authenticate(adata);
if (rc == -1)
goto err_conn;
if (rc == -3)
mutt_clear_error();
if (rc != 0)
return rc;
/* recheck capabilities after authentication */
rc = pop_capabilities(adata, 2);
if (rc == -1)
goto err_conn;
if (rc == -2)
return -2;
/* get total size of mailbox */
mutt_str_strfcpy(buf, "STAT\r\n", sizeof(buf));
rc = pop_query(adata, buf, sizeof(buf));
if (rc == -1)
goto err_conn;
if (rc == -2)
{
mutt_error("%s", adata->err_msg);
return rc;
}
unsigned int n = 0, size = 0;
sscanf(buf, "+OK %u %u", &n, &size);
adata->size = size;
return 0;
err_conn:
adata->status = POP_DISCONNECTED;
mutt_error(_("Server closed connection"));
return -1;
}
/**
* pop_logout - logout from a POP server
* @param m Mailbox
*/
void pop_logout(struct Mailbox *m)
{
struct PopAccountData *adata = pop_adata_get(m);
if (adata->status == POP_CONNECTED)
{
int ret = 0;
char buf[1024];
mutt_message(_("Closing connection to POP server..."));
if (m->readonly)
{
mutt_str_strfcpy(buf, "RSET\r\n", sizeof(buf));
ret = pop_query(adata, buf, sizeof(buf));
}
if (ret != -1)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(adata, buf, sizeof(buf));
}
if (ret < 0)
mutt_debug(LL_DEBUG1, "Error closing POP connection\n");
mutt_clear_error();
}
adata->status = POP_DISCONNECTED;
}
/**
* pop_query_d - Send data from buffer and receive answer to the same buffer
* @param adata POP Account data
* @param buf Buffer to send/store data
* @param buflen Buffer length
* @param msg Progress message
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
*/
int pop_query_d(struct PopAccountData *adata, char *buf, size_t buflen, char *msg)
{
if (adata->status != POP_CONNECTED)
return -1;
/* print msg instead of real command */
if (msg)
{
mutt_debug(MUTT_SOCK_LOG_CMD, "> %s", msg);
}
mutt_socket_send_d(adata->conn, buf, MUTT_SOCK_LOG_FULL);
char *c = strpbrk(buf, " \r\n");
if (c)
*c = '\0';
snprintf(adata->err_msg, sizeof(adata->err_msg), "%s: ", buf);
if (mutt_socket_readln_d(buf, buflen, adata->conn, MUTT_SOCK_LOG_FULL) < 0)
{
adata->status = POP_DISCONNECTED;
return -1;
}
if (mutt_str_startswith(buf, "+OK", CASE_MATCH))
return 0;
pop_error(adata, buf);
return -2;
}
/**
* pop_fetch_data - Read Headers with callback function
* @param adata POP Account data
* @param query POP query to send to server
* @param progress Progress bar
* @param callback Function called for each header read
* @param data Data to pass to the callback
* @retval 0 Successful
* @retval -1 Connection lost
* @retval -2 Invalid command or execution error
* @retval -3 Error in callback(*line, *data)
*
* This function calls callback(*line, *data) for each received line,
* callback(NULL, *data) if rewind(*data) needs, exits when fail or done.
*/
int pop_fetch_data(struct PopAccountData *adata, const char *query,
struct Progress *progress, pop_fetch_t callback, void *data)
{
char buf[1024];
long pos = 0;
size_t lenbuf = 0;
mutt_str_strfcpy(buf, query, sizeof(buf));
int rc = pop_query(adata, buf, sizeof(buf));
if (rc < 0)
return rc;
char *inbuf = mutt_mem_malloc(sizeof(buf));
while (true)
{
const int chunk =
mutt_socket_readln_d(buf, sizeof(buf), adata->conn, MUTT_SOCK_LOG_FULL);
if (chunk < 0)
{
adata->status = POP_DISCONNECTED;
rc = -1;
break;
}
char *p = buf;
if (!lenbuf && (buf[0] == '.'))
{
if (buf[1] != '.')
break;
p++;
}
mutt_str_strfcpy(inbuf + lenbuf, p, sizeof(buf));
pos += chunk;
/* cast is safe since we break out of the loop when chunk<=0 */
if ((size_t) chunk >= sizeof(buf))
{
lenbuf += strlen(p);
}
else
{
if (progress)
mutt_progress_update(progress, pos, -1);
if ((rc == 0) && (callback(inbuf, data) < 0))
rc = -3;
lenbuf = 0;
}
mutt_mem_realloc(&inbuf, lenbuf + sizeof(buf));
}
FREE(&inbuf);
return rc;
}
/**
* check_uidl - find message with this UIDL and set refno - Implements ::pop_fetch_t
* @param line String containing UIDL
* @param data POP data
* @retval 0 Success
* @retval -1 Error
*/
static int check_uidl(const char *line, void *data)
{
if (!line || !data)
return -1;
char *endp = NULL;
errno = 0;
unsigned int index = strtoul(line, &endp, 10);
if (errno != 0)
return -1;
while (*endp == ' ')
endp++;
struct Mailbox *m = data;
for (int i = 0; i < m->msg_count; i++)
{
struct PopEmailData *edata = pop_edata_get(m->emails[i]);
if (mutt_str_strcmp(edata->uid, endp) == 0)
{
edata->refno = index;
break;
}
}
return 0;
}
/**
* pop_reconnect - reconnect and verify indexes if connection was lost
* @param m Mailbox
* @retval 0 Success
* @retval -1 Error
*/
int pop_reconnect(struct Mailbox *m)
{
struct PopAccountData *adata = pop_adata_get(m);
if (adata->status == POP_CONNECTED)
return 0;
while (true)
{
mutt_socket_close(adata->conn);
int ret = pop_open_connection(adata);
if (ret == 0)
{
struct Progress progress;
mutt_progress_init(&progress, _("Verifying message indexes..."), MUTT_PROGRESS_NET, 0);
for (int i = 0; i < m->msg_count; i++)
{
struct PopEmailData *edata = pop_edata_get(m->emails[i]);
edata->refno = -1;
}
ret = pop_fetch_data(adata, "UIDL\r\n", &progress, check_uidl, m);
if (ret == -2)
{
mutt_error("%s", adata->err_msg);
}
}
if (ret == 0)
return 0;
pop_logout(m);
if (ret < -1)
return -1;
if (query_quadoption(C_PopReconnect,
_("Connection lost. Reconnect to POP server?")) != MUTT_YES)
{
return -1;
}
}
}
/**
* pop_adata_get - Get the Account data for this mailbox
* @param m Mailbox
* @retval ptr PopAccountData
*/
struct PopAccountData *pop_adata_get(struct Mailbox *m)
{
if (!m || (m->type != MUTT_POP))
return NULL;
struct Account *a = m->account;
if (!a)
return NULL;
return a->adata;
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/bad_4069_6 |
crossvul-cpp_data_good_1205_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
/* packet thinks it is in the wrong direction, flip it */
StreamTcpPacketSwitchDir(ssn, p);
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permited on SYN packet", ssn);
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/** \internal
* \brief detect timestamp anomalies when processing responses to the
* SYN packet.
* \retval true packet is ok
* \retval false packet is bad
*/
static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)
{
/* we only care about evil server here, so skip TS packets */
if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {
return true;
}
TcpStream *receiver_stream = &ssn->client;
uint32_t ts_echo = TCP_GET_TSECR(p);
if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {
if (receiver_stream->last_ts != 0 && ts_echo != 0 &&
ts_echo != receiver_stream->last_ts)
{
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
} else {
if (receiver_stream->last_ts == 0 && ts_echo != 0) {
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
}
return true;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* check for bad responses */
if (StateSynSentValidateTimestamp(ssn, p) == false)
return -1;
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if (ack_indicates_missed_3whs_ack_packet &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadGrow(ssn_pool,
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-74/c/good_1205_0 |
crossvul-cpp_data_good_762_0 | #include "stdafx.h"
#include "WebServer.h"
#include "WebServerHelper.h"
#include <boost/bind.hpp>
#include <iostream>
#include <fstream>
#include "mainworker.h"
#include "Helper.h"
#include "localtime_r.h"
#include "EventSystem.h"
#include "dzVents.h"
#include "../httpclient/HTTPClient.h"
#include "../hardware/hardwaretypes.h"
#include "../hardware/1Wire.h"
#include "../hardware/OTGWBase.h"
#ifdef WITH_OPENZWAVE
#include "../hardware/OpenZWave.h"
#endif
#include "../hardware/EnOceanESP2.h"
#include "../hardware/EnOceanESP3.h"
#include "../hardware/Wunderground.h"
#include "../hardware/DarkSky.h"
#include "../hardware/AccuWeather.h"
#include "../hardware/OpenWeatherMap.h"
#include "../hardware/Kodi.h"
#include "../hardware/Limitless.h"
#include "../hardware/LogitechMediaServer.h"
#include "../hardware/MySensorsBase.h"
#include "../hardware/RFXBase.h"
#include "../hardware/RFLinkBase.h"
#include "../hardware/SysfsGpio.h"
#include "../hardware/HEOS.h"
#include "../hardware/eHouseTCP.h"
#include "../hardware/USBtin.h"
#include "../hardware/USBtin_MultiblocV8.h"
#ifdef WITH_GPIO
#include "../hardware/Gpio.h"
#include "../hardware/GpioPin.h"
#endif // WITH_GPIO
#include "../hardware/Tellstick.h"
#include "../webserver/Base64.h"
#include "../smtpclient/SMTPClient.h"
#include "../json/json.h"
#include "Logger.h"
#include "SQLHelper.h"
#include "../push/BasePush.h"
#include <algorithm>
#ifdef ENABLE_PYTHON
#include "../hardware/plugins/Plugins.h"
#endif
#ifndef WIN32
#include <sys/utsname.h>
#include <dirent.h>
#else
#include "../msbuild/WindowsHelper.h"
#include "dirent_windows.h"
#endif
#include "../notifications/NotificationHelper.h"
#include "../main/LuaHandler.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#define round(a) ( int ) ( a + .5 )
extern std::string szUserDataFolder;
extern std::string szWWWFolder;
extern std::string szAppVersion;
extern std::string szAppHash;
extern std::string szAppDate;
extern std::string szPyVersion;
extern bool g_bUseUpdater;
extern time_t m_StartTime;
extern bool g_bDontCacheWWW;
struct _tGuiLanguage {
const char* szShort;
const char* szLong;
};
static const _tGuiLanguage guiLanguage[] =
{
{ "en", "English" },
{ "sq", "Albanian" },
{ "ar", "Arabic" },
{ "bs", "Bosnian" },
{ "bg", "Bulgarian" },
{ "ca", "Catalan" },
{ "zh", "Chinese" },
{ "cs", "Czech" },
{ "da", "Danish" },
{ "nl", "Dutch" },
{ "et", "Estonian" },
{ "de", "German" },
{ "el", "Greek" },
{ "fr", "French" },
{ "fi", "Finnish" },
{ "he", "Hebrew" },
{ "hu", "Hungarian" },
{ "is", "Icelandic" },
{ "it", "Italian" },
{ "lt", "Lithuanian" },
{ "lv", "Latvian" },
{ "mk", "Macedonian" },
{ "no", "Norwegian" },
{ "fa", "Persian" },
{ "pl", "Polish" },
{ "pt", "Portuguese" },
{ "ro", "Romanian" },
{ "ru", "Russian" },
{ "sr", "Serbian" },
{ "sk", "Slovak" },
{ "sl", "Slovenian" },
{ "es", "Spanish" },
{ "sv", "Swedish" },
{ "zh_TW", "Taiwanese" },
{ "tr", "Turkish" },
{ "uk", "Ukrainian" },
{ NULL, NULL }
};
extern http::server::CWebServerHelper m_webservers;
namespace http {
namespace server {
CWebServer::CWebServer(void) : session_store()
{
m_pWebEm = NULL;
m_bDoStop = false;
#ifdef WITH_OPENZWAVE
m_ZW_Hwidx = -1;
#endif
}
CWebServer::~CWebServer(void)
{
// RK, we call StopServer() instead of just deleting m_pWebEm. The Do_Work thread might still be accessing that object
StopServer();
}
void CWebServer::Do_Work()
{
bool exception_thrown = false;
while (!m_bDoStop)
{
exception_thrown = false;
try {
if (m_pWebEm) {
m_pWebEm->Run();
}
}
catch (std::exception& e) {
_log.Log(LOG_ERROR, "WebServer(%s) exception occurred : '%s'", m_server_alias.c_str(), e.what());
exception_thrown = true;
}
catch (...) {
_log.Log(LOG_ERROR, "WebServer(%s) unknown exception occurred", m_server_alias.c_str());
exception_thrown = true;
}
if (exception_thrown) {
_log.Log(LOG_STATUS, "WebServer(%s) restart server in 5 seconds", m_server_alias.c_str());
sleep_milliseconds(5000); // prevents from an exception flood
continue;
}
break;
}
_log.Log(LOG_STATUS, "WebServer(%s) stopped", m_server_alias.c_str());
}
void CWebServer::ReloadCustomSwitchIcons()
{
m_custom_light_icons.clear();
m_custom_light_icons_lookup.clear();
std::string sLine = "";
//First get them from the switch_icons.txt file
std::ifstream infile;
std::string switchlightsfile = szWWWFolder + "/switch_icons.txt";
infile.open(switchlightsfile.c_str());
if (infile.is_open())
{
int index = 0;
while (!infile.eof())
{
getline(infile, sLine);
if (sLine.size() != 0)
{
std::vector<std::string> results;
StringSplit(sLine, ";", results);
if (results.size() == 3)
{
_tCustomIcon cImage;
cImage.idx = index++;
cImage.RootFile = results[0];
cImage.Title = results[1];
cImage.Description = results[2];
m_custom_light_icons.push_back(cImage);
m_custom_light_icons_lookup[cImage.idx] = m_custom_light_icons.size() - 1;
}
}
}
infile.close();
}
//Now get them from the database (idx 100+)
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID,Base,Name,Description FROM CustomImages");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int ID = atoi(sd[0].c_str());
_tCustomIcon cImage;
cImage.idx = 100 + ID;
cImage.RootFile = sd[1];
cImage.Title = sd[2];
cImage.Description = sd[3];
std::string IconFile16 = cImage.RootFile + ".png";
std::string IconFile48On = cImage.RootFile + "48_On.png";
std::string IconFile48Off = cImage.RootFile + "48_Off.png";
std::map<std::string, std::string> _dbImageFiles;
_dbImageFiles["IconSmall"] = szWWWFolder + "/images/" + IconFile16;
_dbImageFiles["IconOn"] = szWWWFolder + "/images/" + IconFile48On;
_dbImageFiles["IconOff"] = szWWWFolder + "/images/" + IconFile48Off;
//Check if files are on disk, else add them
for (const auto & iItt : _dbImageFiles)
{
std::string TableField = iItt.first;
std::string IconFile = iItt.second;
if (!file_exist(IconFile.c_str()))
{
//Does not exists, extract it from the database and add it
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_queryBlob("SELECT %s FROM CustomImages WHERE ID=%d", TableField.c_str(), ID);
if (!result2.empty())
{
std::ofstream file;
file.open(IconFile.c_str(), std::ios::out | std::ios::binary);
if (!file.is_open())
return;
file << result2[0][0];
file.close();
}
}
}
m_custom_light_icons.push_back(cImage);
m_custom_light_icons_lookup[cImage.idx] = m_custom_light_icons.size() - 1;
ii++;
}
}
}
bool CWebServer::StartServer(server_settings & settings, const std::string & serverpath, const bool bIgnoreUsernamePassword)
{
m_server_alias = (settings.is_secure() == true) ? "SSL" : "HTTP";
if (!settings.is_enabled())
return true;
ReloadCustomSwitchIcons();
int tries = 0;
bool exception = false;
//_log.Log(LOG_STATUS, "CWebServer::StartServer() : settings : %s", settings.to_string().c_str());
do {
try {
exception = false;
m_pWebEm = new http::server::cWebem(settings, serverpath.c_str());
}
catch (std::exception& e) {
exception = true;
switch (tries) {
case 0:
settings.listening_address = "::";
break;
case 1:
settings.listening_address = "0.0.0.0";
break;
case 2:
_log.Log(LOG_ERROR, "WebServer(%s) startup failed on address %s with port: %s: %s", m_server_alias.c_str(), settings.listening_address.c_str(), settings.listening_port.c_str(), e.what());
if (atoi(settings.listening_port.c_str()) < 1024)
_log.Log(LOG_ERROR, "WebServer(%s) check privileges for opening ports below 1024", m_server_alias.c_str());
else
_log.Log(LOG_ERROR, "WebServer(%s) check if no other application is using port: %s", m_server_alias.c_str(), settings.listening_port.c_str());
return false;
}
tries++;
}
} while (exception);
_log.Log(LOG_STATUS, "WebServer(%s) started on address: %s with port %s", m_server_alias.c_str(), settings.listening_address.c_str(), settings.listening_port.c_str());
m_pWebEm->SetDigistRealm("Domoticz.com");
m_pWebEm->SetSessionStore(this);
if (!bIgnoreUsernamePassword)
{
LoadUsers();
std::string WebLocalNetworks;
int nValue;
if (m_sql.GetPreferencesVar("WebLocalNetworks", nValue, WebLocalNetworks))
{
std::vector<std::string> strarray;
StringSplit(WebLocalNetworks, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddLocalNetworks(itt);
//add local hostname
m_pWebEm->AddLocalNetworks("");
}
}
std::string WebRemoteProxyIPs;
int nValue;
if (m_sql.GetPreferencesVar("WebRemoteProxyIPs", nValue, WebRemoteProxyIPs))
{
std::vector<std::string> strarray;
StringSplit(WebRemoteProxyIPs, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddRemoteProxyIPs(itt);
}
//register callbacks
m_pWebEm->RegisterIncludeCode("switchtypes", boost::bind(&CWebServer::DisplaySwitchTypesCombo, this, _1));
m_pWebEm->RegisterIncludeCode("metertypes", boost::bind(&CWebServer::DisplayMeterTypesCombo, this, _1));
m_pWebEm->RegisterIncludeCode("timertypes", boost::bind(&CWebServer::DisplayTimerTypesCombo, this, _1));
m_pWebEm->RegisterIncludeCode("combolanguage", boost::bind(&CWebServer::DisplayLanguageCombo, this, _1));
m_pWebEm->RegisterPageCode("/json.htm", boost::bind(&CWebServer::GetJSonPage, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/uploadcustomicon", boost::bind(&CWebServer::Post_UploadCustomIcon, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/html5.appcache", boost::bind(&CWebServer::GetAppCache, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/camsnapshot.jpg", boost::bind(&CWebServer::GetCameraSnapshot, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/backupdatabase.php", boost::bind(&CWebServer::GetDatabaseBackup, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/raspberry.cgi", boost::bind(&CWebServer::GetInternalCameraSnapshot, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/uvccapture.cgi", boost::bind(&CWebServer::GetInternalCameraSnapshot, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/images/floorplans/plan", boost::bind(&CWebServer::GetFloorplanImage, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("storesettings", boost::bind(&CWebServer::PostSettings, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setrfxcommode", boost::bind(&CWebServer::SetRFXCOMMode, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("rfxupgradefirmware", boost::bind(&CWebServer::RFXComUpgradeFirmware, this, _1, _2, _3));
RegisterCommandCode("rfxfirmwaregetpercentage", boost::bind(&CWebServer::Cmd_RFXComGetFirmwarePercentage, this, _1, _2, _3), true);
m_pWebEm->RegisterActionCode("setrego6xxtype", boost::bind(&CWebServer::SetRego6XXType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("sets0metertype", boost::bind(&CWebServer::SetS0MeterType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setlimitlesstype", boost::bind(&CWebServer::SetLimitlessType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("uploadfloorplanimage", boost::bind(&CWebServer::UploadFloorplanImage, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setopenthermsettings", boost::bind(&CWebServer::SetOpenThermSettings, this, _1, _2, _3));
RegisterCommandCode("sendopenthermcommand", boost::bind(&CWebServer::Cmd_SendOpenThermCommand, this, _1, _2, _3), true);
m_pWebEm->RegisterActionCode("reloadpiface", boost::bind(&CWebServer::ReloadPiFace, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setcurrentcostmetertype", boost::bind(&CWebServer::SetCurrentCostUSBType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("restoredatabase", boost::bind(&CWebServer::RestoreDatabase, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("sbfspotimportolddata", boost::bind(&CWebServer::SBFSpotImportOldData, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("event_create", boost::bind(&CWebServer::EventCreate, this, _1, _2, _3));
RegisterCommandCode("getlanguage", boost::bind(&CWebServer::Cmd_GetLanguage, this, _1, _2, _3), true);
RegisterCommandCode("getthemes", boost::bind(&CWebServer::Cmd_GetThemes, this, _1, _2, _3), true);
RegisterCommandCode("gettitle", boost::bind(&CWebServer::Cmd_GetTitle, this, _1, _2, _3), true);
RegisterCommandCode("logincheck", boost::bind(&CWebServer::Cmd_LoginCheck, this, _1, _2, _3), true);
RegisterCommandCode("getversion", boost::bind(&CWebServer::Cmd_GetVersion, this, _1, _2, _3), true);
RegisterCommandCode("getlog", boost::bind(&CWebServer::Cmd_GetLog, this, _1, _2, _3));
RegisterCommandCode("clearlog", boost::bind(&CWebServer::Cmd_ClearLog, this, _1, _2, _3));
RegisterCommandCode("getauth", boost::bind(&CWebServer::Cmd_GetAuth, this, _1, _2, _3), true);
RegisterCommandCode("getuptime", boost::bind(&CWebServer::Cmd_GetUptime, this, _1, _2, _3), true);
RegisterCommandCode("gethardwaretypes", boost::bind(&CWebServer::Cmd_GetHardwareTypes, this, _1, _2, _3));
RegisterCommandCode("addhardware", boost::bind(&CWebServer::Cmd_AddHardware, this, _1, _2, _3));
RegisterCommandCode("updatehardware", boost::bind(&CWebServer::Cmd_UpdateHardware, this, _1, _2, _3));
RegisterCommandCode("deletehardware", boost::bind(&CWebServer::Cmd_DeleteHardware, this, _1, _2, _3));
RegisterCommandCode("addcamera", boost::bind(&CWebServer::Cmd_AddCamera, this, _1, _2, _3));
RegisterCommandCode("updatecamera", boost::bind(&CWebServer::Cmd_UpdateCamera, this, _1, _2, _3));
RegisterCommandCode("deletecamera", boost::bind(&CWebServer::Cmd_DeleteCamera, this, _1, _2, _3));
RegisterCommandCode("wolgetnodes", boost::bind(&CWebServer::Cmd_WOLGetNodes, this, _1, _2, _3));
RegisterCommandCode("woladdnode", boost::bind(&CWebServer::Cmd_WOLAddNode, this, _1, _2, _3));
RegisterCommandCode("wolupdatenode", boost::bind(&CWebServer::Cmd_WOLUpdateNode, this, _1, _2, _3));
RegisterCommandCode("wolremovenode", boost::bind(&CWebServer::Cmd_WOLRemoveNode, this, _1, _2, _3));
RegisterCommandCode("wolclearnodes", boost::bind(&CWebServer::Cmd_WOLClearNodes, this, _1, _2, _3));
RegisterCommandCode("mysensorsgetnodes", boost::bind(&CWebServer::Cmd_MySensorsGetNodes, this, _1, _2, _3));
RegisterCommandCode("mysensorsgetchilds", boost::bind(&CWebServer::Cmd_MySensorsGetChilds, this, _1, _2, _3));
RegisterCommandCode("mysensorsupdatenode", boost::bind(&CWebServer::Cmd_MySensorsUpdateNode, this, _1, _2, _3));
RegisterCommandCode("mysensorsremovenode", boost::bind(&CWebServer::Cmd_MySensorsRemoveNode, this, _1, _2, _3));
RegisterCommandCode("mysensorsremovechild", boost::bind(&CWebServer::Cmd_MySensorsRemoveChild, this, _1, _2, _3));
RegisterCommandCode("mysensorsupdatechild", boost::bind(&CWebServer::Cmd_MySensorsUpdateChild, this, _1, _2, _3));
RegisterCommandCode("pingersetmode", boost::bind(&CWebServer::Cmd_PingerSetMode, this, _1, _2, _3));
RegisterCommandCode("pingergetnodes", boost::bind(&CWebServer::Cmd_PingerGetNodes, this, _1, _2, _3));
RegisterCommandCode("pingeraddnode", boost::bind(&CWebServer::Cmd_PingerAddNode, this, _1, _2, _3));
RegisterCommandCode("pingerupdatenode", boost::bind(&CWebServer::Cmd_PingerUpdateNode, this, _1, _2, _3));
RegisterCommandCode("pingerremovenode", boost::bind(&CWebServer::Cmd_PingerRemoveNode, this, _1, _2, _3));
RegisterCommandCode("pingerclearnodes", boost::bind(&CWebServer::Cmd_PingerClearNodes, this, _1, _2, _3));
RegisterCommandCode("kodisetmode", boost::bind(&CWebServer::Cmd_KodiSetMode, this, _1, _2, _3));
RegisterCommandCode("kodigetnodes", boost::bind(&CWebServer::Cmd_KodiGetNodes, this, _1, _2, _3));
RegisterCommandCode("kodiaddnode", boost::bind(&CWebServer::Cmd_KodiAddNode, this, _1, _2, _3));
RegisterCommandCode("kodiupdatenode", boost::bind(&CWebServer::Cmd_KodiUpdateNode, this, _1, _2, _3));
RegisterCommandCode("kodiremovenode", boost::bind(&CWebServer::Cmd_KodiRemoveNode, this, _1, _2, _3));
RegisterCommandCode("kodiclearnodes", boost::bind(&CWebServer::Cmd_KodiClearNodes, this, _1, _2, _3));
RegisterCommandCode("kodimediacommand", boost::bind(&CWebServer::Cmd_KodiMediaCommand, this, _1, _2, _3));
RegisterCommandCode("panasonicsetmode", boost::bind(&CWebServer::Cmd_PanasonicSetMode, this, _1, _2, _3));
RegisterCommandCode("panasonicgetnodes", boost::bind(&CWebServer::Cmd_PanasonicGetNodes, this, _1, _2, _3));
RegisterCommandCode("panasonicaddnode", boost::bind(&CWebServer::Cmd_PanasonicAddNode, this, _1, _2, _3));
RegisterCommandCode("panasonicupdatenode", boost::bind(&CWebServer::Cmd_PanasonicUpdateNode, this, _1, _2, _3));
RegisterCommandCode("panasonicremovenode", boost::bind(&CWebServer::Cmd_PanasonicRemoveNode, this, _1, _2, _3));
RegisterCommandCode("panasonicclearnodes", boost::bind(&CWebServer::Cmd_PanasonicClearNodes, this, _1, _2, _3));
RegisterCommandCode("panasonicmediacommand", boost::bind(&CWebServer::Cmd_PanasonicMediaCommand, this, _1, _2, _3));
RegisterCommandCode("heossetmode", boost::bind(&CWebServer::Cmd_HEOSSetMode, this, _1, _2, _3));
RegisterCommandCode("heosmediacommand", boost::bind(&CWebServer::Cmd_HEOSMediaCommand, this, _1, _2, _3));
RegisterCommandCode("onkyoeiscpcommand", boost::bind(&CWebServer::Cmd_OnkyoEiscpCommand, this, _1, _2, _3));
RegisterCommandCode("bleboxsetmode", boost::bind(&CWebServer::Cmd_BleBoxSetMode, this, _1, _2, _3));
RegisterCommandCode("bleboxgetnodes", boost::bind(&CWebServer::Cmd_BleBoxGetNodes, this, _1, _2, _3));
RegisterCommandCode("bleboxaddnode", boost::bind(&CWebServer::Cmd_BleBoxAddNode, this, _1, _2, _3));
RegisterCommandCode("bleboxremovenode", boost::bind(&CWebServer::Cmd_BleBoxRemoveNode, this, _1, _2, _3));
RegisterCommandCode("bleboxclearnodes", boost::bind(&CWebServer::Cmd_BleBoxClearNodes, this, _1, _2, _3));
RegisterCommandCode("bleboxautosearchingnodes", boost::bind(&CWebServer::Cmd_BleBoxAutoSearchingNodes, this, _1, _2, _3));
RegisterCommandCode("bleboxupdatefirmware", boost::bind(&CWebServer::Cmd_BleBoxUpdateFirmware, this, _1, _2, _3));
RegisterCommandCode("lmssetmode", boost::bind(&CWebServer::Cmd_LMSSetMode, this, _1, _2, _3));
RegisterCommandCode("lmsgetnodes", boost::bind(&CWebServer::Cmd_LMSGetNodes, this, _1, _2, _3));
RegisterCommandCode("lmsgetplaylists", boost::bind(&CWebServer::Cmd_LMSGetPlaylists, this, _1, _2, _3));
RegisterCommandCode("lmsmediacommand", boost::bind(&CWebServer::Cmd_LMSMediaCommand, this, _1, _2, _3));
RegisterCommandCode("lmsdeleteunuseddevices", boost::bind(&CWebServer::Cmd_LMSDeleteUnusedDevices, this, _1, _2, _3));
RegisterCommandCode("savefibarolinkconfig", boost::bind(&CWebServer::Cmd_SaveFibaroLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getfibarolinkconfig", boost::bind(&CWebServer::Cmd_GetFibaroLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getfibarolinks", boost::bind(&CWebServer::Cmd_GetFibaroLinks, this, _1, _2, _3));
RegisterCommandCode("savefibarolink", boost::bind(&CWebServer::Cmd_SaveFibaroLink, this, _1, _2, _3));
RegisterCommandCode("deletefibarolink", boost::bind(&CWebServer::Cmd_DeleteFibaroLink, this, _1, _2, _3));
RegisterCommandCode("saveinfluxlinkconfig", boost::bind(&CWebServer::Cmd_SaveInfluxLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getinfluxlinkconfig", boost::bind(&CWebServer::Cmd_GetInfluxLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getinfluxlinks", boost::bind(&CWebServer::Cmd_GetInfluxLinks, this, _1, _2, _3));
RegisterCommandCode("saveinfluxlink", boost::bind(&CWebServer::Cmd_SaveInfluxLink, this, _1, _2, _3));
RegisterCommandCode("deleteinfluxlink", boost::bind(&CWebServer::Cmd_DeleteInfluxLink, this, _1, _2, _3));
RegisterCommandCode("savehttplinkconfig", boost::bind(&CWebServer::Cmd_SaveHttpLinkConfig, this, _1, _2, _3));
RegisterCommandCode("gethttplinkconfig", boost::bind(&CWebServer::Cmd_GetHttpLinkConfig, this, _1, _2, _3));
RegisterCommandCode("gethttplinks", boost::bind(&CWebServer::Cmd_GetHttpLinks, this, _1, _2, _3));
RegisterCommandCode("savehttplink", boost::bind(&CWebServer::Cmd_SaveHttpLink, this, _1, _2, _3));
RegisterCommandCode("deletehttplink", boost::bind(&CWebServer::Cmd_DeleteHttpLink, this, _1, _2, _3));
RegisterCommandCode("savegooglepubsublinkconfig", boost::bind(&CWebServer::Cmd_SaveGooglePubSubLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getgooglepubsublinkconfig", boost::bind(&CWebServer::Cmd_GetGooglePubSubLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getgooglepubsublinks", boost::bind(&CWebServer::Cmd_GetGooglePubSubLinks, this, _1, _2, _3));
RegisterCommandCode("savegooglepubsublink", boost::bind(&CWebServer::Cmd_SaveGooglePubSubLink, this, _1, _2, _3));
RegisterCommandCode("deletegooglepubsublink", boost::bind(&CWebServer::Cmd_DeleteGooglePubSubLink, this, _1, _2, _3));
RegisterCommandCode("getdevicevalueoptions", boost::bind(&CWebServer::Cmd_GetDeviceValueOptions, this, _1, _2, _3));
RegisterCommandCode("getdevicevalueoptionwording", boost::bind(&CWebServer::Cmd_GetDeviceValueOptionWording, this, _1, _2, _3));
RegisterCommandCode("adduservariable", boost::bind(&CWebServer::Cmd_AddUserVariable, this, _1, _2, _3));
RegisterCommandCode("updateuservariable", boost::bind(&CWebServer::Cmd_UpdateUserVariable, this, _1, _2, _3));
RegisterCommandCode("deleteuservariable", boost::bind(&CWebServer::Cmd_DeleteUserVariable, this, _1, _2, _3));
RegisterCommandCode("getuservariables", boost::bind(&CWebServer::Cmd_GetUserVariables, this, _1, _2, _3));
RegisterCommandCode("getuservariable", boost::bind(&CWebServer::Cmd_GetUserVariable, this, _1, _2, _3));
RegisterCommandCode("allownewhardware", boost::bind(&CWebServer::Cmd_AllowNewHardware, this, _1, _2, _3));
RegisterCommandCode("addplan", boost::bind(&CWebServer::Cmd_AddPlan, this, _1, _2, _3));
RegisterCommandCode("updateplan", boost::bind(&CWebServer::Cmd_UpdatePlan, this, _1, _2, _3));
RegisterCommandCode("deleteplan", boost::bind(&CWebServer::Cmd_DeletePlan, this, _1, _2, _3));
RegisterCommandCode("getunusedplandevices", boost::bind(&CWebServer::Cmd_GetUnusedPlanDevices, this, _1, _2, _3));
RegisterCommandCode("addplanactivedevice", boost::bind(&CWebServer::Cmd_AddPlanActiveDevice, this, _1, _2, _3));
RegisterCommandCode("getplandevices", boost::bind(&CWebServer::Cmd_GetPlanDevices, this, _1, _2, _3));
RegisterCommandCode("deleteplandevice", boost::bind(&CWebServer::Cmd_DeletePlanDevice, this, _1, _2, _3));
RegisterCommandCode("setplandevicecoords", boost::bind(&CWebServer::Cmd_SetPlanDeviceCoords, this, _1, _2, _3));
RegisterCommandCode("deleteallplandevices", boost::bind(&CWebServer::Cmd_DeleteAllPlanDevices, this, _1, _2, _3));
RegisterCommandCode("changeplanorder", boost::bind(&CWebServer::Cmd_ChangePlanOrder, this, _1, _2, _3));
RegisterCommandCode("changeplandeviceorder", boost::bind(&CWebServer::Cmd_ChangePlanDeviceOrder, this, _1, _2, _3));
RegisterCommandCode("gettimerplans", boost::bind(&CWebServer::Cmd_GetTimerPlans, this, _1, _2, _3));
RegisterCommandCode("addtimerplan", boost::bind(&CWebServer::Cmd_AddTimerPlan, this, _1, _2, _3));
RegisterCommandCode("updatetimerplan", boost::bind(&CWebServer::Cmd_UpdateTimerPlan, this, _1, _2, _3));
RegisterCommandCode("deletetimerplan", boost::bind(&CWebServer::Cmd_DeleteTimerPlan, this, _1, _2, _3));
RegisterCommandCode("duplicatetimerplan", boost::bind(&CWebServer::Cmd_DuplicateTimerPlan, this, _1, _2, _3));
RegisterCommandCode("getactualhistory", boost::bind(&CWebServer::Cmd_GetActualHistory, this, _1, _2, _3));
RegisterCommandCode("getnewhistory", boost::bind(&CWebServer::Cmd_GetNewHistory, this, _1, _2, _3));
RegisterCommandCode("getconfig", boost::bind(&CWebServer::Cmd_GetConfig, this, _1, _2, _3), true);
RegisterCommandCode("sendnotification", boost::bind(&CWebServer::Cmd_SendNotification, this, _1, _2, _3));
RegisterCommandCode("emailcamerasnapshot", boost::bind(&CWebServer::Cmd_EmailCameraSnapshot, this, _1, _2, _3));
RegisterCommandCode("udevice", boost::bind(&CWebServer::Cmd_UpdateDevice, this, _1, _2, _3));
RegisterCommandCode("udevices", boost::bind(&CWebServer::Cmd_UpdateDevices, this, _1, _2, _3));
RegisterCommandCode("thermostatstate", boost::bind(&CWebServer::Cmd_SetThermostatState, this, _1, _2, _3));
RegisterCommandCode("system_shutdown", boost::bind(&CWebServer::Cmd_SystemShutdown, this, _1, _2, _3));
RegisterCommandCode("system_reboot", boost::bind(&CWebServer::Cmd_SystemReboot, this, _1, _2, _3));
RegisterCommandCode("execute_script", boost::bind(&CWebServer::Cmd_ExcecuteScript, this, _1, _2, _3));
RegisterCommandCode("getcosts", boost::bind(&CWebServer::Cmd_GetCosts, this, _1, _2, _3));
RegisterCommandCode("checkforupdate", boost::bind(&CWebServer::Cmd_CheckForUpdate, this, _1, _2, _3));
RegisterCommandCode("downloadupdate", boost::bind(&CWebServer::Cmd_DownloadUpdate, this, _1, _2, _3));
RegisterCommandCode("downloadready", boost::bind(&CWebServer::Cmd_DownloadReady, this, _1, _2, _3));
RegisterCommandCode("deletedatapoint", boost::bind(&CWebServer::Cmd_DeleteDatePoint, this, _1, _2, _3));
RegisterCommandCode("setactivetimerplan", boost::bind(&CWebServer::Cmd_SetActiveTimerPlan, this, _1, _2, _3));
RegisterCommandCode("addtimer", boost::bind(&CWebServer::Cmd_AddTimer, this, _1, _2, _3));
RegisterCommandCode("updatetimer", boost::bind(&CWebServer::Cmd_UpdateTimer, this, _1, _2, _3));
RegisterCommandCode("deletetimer", boost::bind(&CWebServer::Cmd_DeleteTimer, this, _1, _2, _3));
RegisterCommandCode("enabletimer", boost::bind(&CWebServer::Cmd_EnableTimer, this, _1, _2, _3));
RegisterCommandCode("disabletimer", boost::bind(&CWebServer::Cmd_DisableTimer, this, _1, _2, _3));
RegisterCommandCode("cleartimers", boost::bind(&CWebServer::Cmd_ClearTimers, this, _1, _2, _3));
RegisterCommandCode("addscenetimer", boost::bind(&CWebServer::Cmd_AddSceneTimer, this, _1, _2, _3));
RegisterCommandCode("updatescenetimer", boost::bind(&CWebServer::Cmd_UpdateSceneTimer, this, _1, _2, _3));
RegisterCommandCode("deletescenetimer", boost::bind(&CWebServer::Cmd_DeleteSceneTimer, this, _1, _2, _3));
RegisterCommandCode("enablescenetimer", boost::bind(&CWebServer::Cmd_EnableSceneTimer, this, _1, _2, _3));
RegisterCommandCode("disablescenetimer", boost::bind(&CWebServer::Cmd_DisableSceneTimer, this, _1, _2, _3));
RegisterCommandCode("clearscenetimers", boost::bind(&CWebServer::Cmd_ClearSceneTimers, this, _1, _2, _3));
RegisterCommandCode("getsceneactivations", boost::bind(&CWebServer::Cmd_GetSceneActivations, this, _1, _2, _3));
RegisterCommandCode("addscenecode", boost::bind(&CWebServer::Cmd_AddSceneCode, this, _1, _2, _3));
RegisterCommandCode("removescenecode", boost::bind(&CWebServer::Cmd_RemoveSceneCode, this, _1, _2, _3));
RegisterCommandCode("clearscenecodes", boost::bind(&CWebServer::Cmd_ClearSceneCodes, this, _1, _2, _3));
RegisterCommandCode("renamescene", boost::bind(&CWebServer::Cmd_RenameScene, this, _1, _2, _3));
RegisterCommandCode("setsetpoint", boost::bind(&CWebServer::Cmd_SetSetpoint, this, _1, _2, _3));
RegisterCommandCode("addsetpointtimer", boost::bind(&CWebServer::Cmd_AddSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("updatesetpointtimer", boost::bind(&CWebServer::Cmd_UpdateSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("deletesetpointtimer", boost::bind(&CWebServer::Cmd_DeleteSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("enablesetpointtimer", boost::bind(&CWebServer::Cmd_EnableSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("disablesetpointtimer", boost::bind(&CWebServer::Cmd_DisableSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("clearsetpointtimers", boost::bind(&CWebServer::Cmd_ClearSetpointTimers, this, _1, _2, _3));
RegisterCommandCode("serial_devices", boost::bind(&CWebServer::Cmd_GetSerialDevices, this, _1, _2, _3));
RegisterCommandCode("devices_list", boost::bind(&CWebServer::Cmd_GetDevicesList, this, _1, _2, _3));
RegisterCommandCode("devices_list_onoff", boost::bind(&CWebServer::Cmd_GetDevicesListOnOff, this, _1, _2, _3));
RegisterCommandCode("registerhue", boost::bind(&CWebServer::Cmd_PhilipsHueRegister, this, _1, _2, _3));
RegisterCommandCode("getcustomiconset", boost::bind(&CWebServer::Cmd_GetCustomIconSet, this, _1, _2, _3));
RegisterCommandCode("deletecustomicon", boost::bind(&CWebServer::Cmd_DeleteCustomIcon, this, _1, _2, _3));
RegisterCommandCode("updatecustomicon", boost::bind(&CWebServer::Cmd_UpdateCustomIcon, this, _1, _2, _3));
RegisterCommandCode("renamedevice", boost::bind(&CWebServer::Cmd_RenameDevice, this, _1, _2, _3));
RegisterCommandCode("setunused", boost::bind(&CWebServer::Cmd_SetUnused, this, _1, _2, _3));
RegisterCommandCode("addlogmessage", boost::bind(&CWebServer::Cmd_AddLogMessage, this, _1, _2, _3));
RegisterCommandCode("clearshortlog", boost::bind(&CWebServer::Cmd_ClearShortLog, this, _1, _2, _3));
RegisterCommandCode("vacuumdatabase", boost::bind(&CWebServer::Cmd_VacuumDatabase, this, _1, _2, _3));
RegisterCommandCode("addmobiledevice", boost::bind(&CWebServer::Cmd_AddMobileDevice, this, _1, _2, _3));
RegisterCommandCode("updatemobiledevice", boost::bind(&CWebServer::Cmd_UpdateMobileDevice, this, _1, _2, _3));
RegisterCommandCode("deletemobiledevice", boost::bind(&CWebServer::Cmd_DeleteMobileDevice, this, _1, _2, _3));
RegisterCommandCode("addyeelight", boost::bind(&CWebServer::Cmd_AddYeeLight, this, _1, _2, _3));
RegisterCommandCode("addArilux", boost::bind(&CWebServer::Cmd_AddArilux, this, _1, _2, _3));
RegisterRType("graph", boost::bind(&CWebServer::RType_HandleGraph, this, _1, _2, _3));
RegisterRType("lightlog", boost::bind(&CWebServer::RType_LightLog, this, _1, _2, _3));
RegisterRType("textlog", boost::bind(&CWebServer::RType_TextLog, this, _1, _2, _3));
RegisterRType("scenelog", boost::bind(&CWebServer::RType_SceneLog, this, _1, _2, _3));
RegisterRType("settings", boost::bind(&CWebServer::RType_Settings, this, _1, _2, _3));
RegisterRType("events", boost::bind(&CWebServer::RType_Events, this, _1, _2, _3));
RegisterRType("hardware", boost::bind(&CWebServer::RType_Hardware, this, _1, _2, _3));
RegisterRType("devices", boost::bind(&CWebServer::RType_Devices, this, _1, _2, _3));
RegisterRType("deletedevice", boost::bind(&CWebServer::RType_DeleteDevice, this, _1, _2, _3));
RegisterRType("cameras", boost::bind(&CWebServer::RType_Cameras, this, _1, _2, _3));
RegisterRType("cameras_user", boost::bind(&CWebServer::RType_CamerasUser, this, _1, _2, _3));
RegisterRType("users", boost::bind(&CWebServer::RType_Users, this, _1, _2, _3));
RegisterRType("mobiles", boost::bind(&CWebServer::RType_Mobiles, this, _1, _2, _3));
RegisterRType("timers", boost::bind(&CWebServer::RType_Timers, this, _1, _2, _3));
RegisterRType("scenetimers", boost::bind(&CWebServer::RType_SceneTimers, this, _1, _2, _3));
RegisterRType("setpointtimers", boost::bind(&CWebServer::RType_SetpointTimers, this, _1, _2, _3));
RegisterRType("gettransfers", boost::bind(&CWebServer::RType_GetTransfers, this, _1, _2, _3));
RegisterRType("transferdevice", boost::bind(&CWebServer::RType_TransferDevice, this, _1, _2, _3));
RegisterRType("notifications", boost::bind(&CWebServer::RType_Notifications, this, _1, _2, _3));
RegisterRType("schedules", boost::bind(&CWebServer::RType_Schedules, this, _1, _2, _3));
RegisterRType("getshareduserdevices", boost::bind(&CWebServer::RType_GetSharedUserDevices, this, _1, _2, _3));
RegisterRType("setshareduserdevices", boost::bind(&CWebServer::RType_SetSharedUserDevices, this, _1, _2, _3));
RegisterRType("setused", boost::bind(&CWebServer::RType_SetUsed, this, _1, _2, _3));
RegisterRType("scenes", boost::bind(&CWebServer::RType_Scenes, this, _1, _2, _3));
RegisterRType("addscene", boost::bind(&CWebServer::RType_AddScene, this, _1, _2, _3));
RegisterRType("deletescene", boost::bind(&CWebServer::RType_DeleteScene, this, _1, _2, _3));
RegisterRType("updatescene", boost::bind(&CWebServer::RType_UpdateScene, this, _1, _2, _3));
RegisterRType("createvirtualsensor", boost::bind(&CWebServer::RType_CreateMappedSensor, this, _1, _2, _3));
RegisterRType("createdevice", boost::bind(&CWebServer::RType_CreateDevice, this, _1, _2, _3));
RegisterRType("createevohomesensor", boost::bind(&CWebServer::RType_CreateEvohomeSensor, this, _1, _2, _3));
RegisterRType("bindevohome", boost::bind(&CWebServer::RType_BindEvohome, this, _1, _2, _3));
RegisterRType("createrflinkdevice", boost::bind(&CWebServer::RType_CreateRFLinkDevice, this, _1, _2, _3));
RegisterRType("custom_light_icons", boost::bind(&CWebServer::RType_CustomLightIcons, this, _1, _2, _3));
RegisterRType("plans", boost::bind(&CWebServer::RType_Plans, this, _1, _2, _3));
RegisterRType("floorplans", boost::bind(&CWebServer::RType_FloorPlans, this, _1, _2, _3));
#ifdef WITH_OPENZWAVE
//ZWave
RegisterCommandCode("updatezwavenode", boost::bind(&CWebServer::Cmd_ZWaveUpdateNode, this, _1, _2, _3));
RegisterCommandCode("deletezwavenode", boost::bind(&CWebServer::Cmd_ZWaveDeleteNode, this, _1, _2, _3));
RegisterCommandCode("zwaveinclude", boost::bind(&CWebServer::Cmd_ZWaveInclude, this, _1, _2, _3));
RegisterCommandCode("zwaveexclude", boost::bind(&CWebServer::Cmd_ZWaveExclude, this, _1, _2, _3));
RegisterCommandCode("zwaveisnodeincluded", boost::bind(&CWebServer::Cmd_ZWaveIsNodeIncluded, this, _1, _2, _3));
RegisterCommandCode("zwaveisnodeexcluded", boost::bind(&CWebServer::Cmd_ZWaveIsNodeExcluded, this, _1, _2, _3));
RegisterCommandCode("zwavesoftreset", boost::bind(&CWebServer::Cmd_ZWaveSoftReset, this, _1, _2, _3));
RegisterCommandCode("zwavehardreset", boost::bind(&CWebServer::Cmd_ZWaveHardReset, this, _1, _2, _3));
RegisterCommandCode("zwavenetworkheal", boost::bind(&CWebServer::Cmd_ZWaveNetworkHeal, this, _1, _2, _3));
RegisterCommandCode("zwavenodeheal", boost::bind(&CWebServer::Cmd_ZWaveNodeHeal, this, _1, _2, _3));
RegisterCommandCode("zwavenetworkinfo", boost::bind(&CWebServer::Cmd_ZWaveNetworkInfo, this, _1, _2, _3));
RegisterCommandCode("zwaveremovegroupnode", boost::bind(&CWebServer::Cmd_ZWaveRemoveGroupNode, this, _1, _2, _3));
RegisterCommandCode("zwaveaddgroupnode", boost::bind(&CWebServer::Cmd_ZWaveAddGroupNode, this, _1, _2, _3));
RegisterCommandCode("zwavegroupinfo", boost::bind(&CWebServer::Cmd_ZWaveGroupInfo, this, _1, _2, _3));
RegisterCommandCode("zwavecancel", boost::bind(&CWebServer::Cmd_ZWaveCancel, this, _1, _2, _3));
RegisterCommandCode("applyzwavenodeconfig", boost::bind(&CWebServer::Cmd_ApplyZWaveNodeConfig, this, _1, _2, _3));
RegisterCommandCode("requestzwavenodeconfig", boost::bind(&CWebServer::Cmd_ZWaveRequestNodeConfig, this, _1, _2, _3));
RegisterCommandCode("zwavestatecheck", boost::bind(&CWebServer::Cmd_ZWaveStateCheck, this, _1, _2, _3));
RegisterCommandCode("zwavereceiveconfigurationfromothercontroller", boost::bind(&CWebServer::Cmd_ZWaveReceiveConfigurationFromOtherController, this, _1, _2, _3));
RegisterCommandCode("zwavesendconfigurationtosecondcontroller", boost::bind(&CWebServer::Cmd_ZWaveSendConfigurationToSecondaryController, this, _1, _2, _3));
RegisterCommandCode("zwavetransferprimaryrole", boost::bind(&CWebServer::Cmd_ZWaveTransferPrimaryRole, this, _1, _2, _3));
RegisterCommandCode("zwavestartusercodeenrollmentmode", boost::bind(&CWebServer::Cmd_ZWaveSetUserCodeEnrollmentMode, this, _1, _2, _3));
RegisterCommandCode("zwavegetusercodes", boost::bind(&CWebServer::Cmd_ZWaveGetNodeUserCodes, this, _1, _2, _3));
RegisterCommandCode("zwaveremoveusercode", boost::bind(&CWebServer::Cmd_ZWaveRemoveUserCode, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/zwavegetconfig.php", boost::bind(&CWebServer::ZWaveGetConfigFile, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/poll.xml", boost::bind(&CWebServer::ZWaveCPPollXml, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/cp.html", boost::bind(&CWebServer::ZWaveCPIndex, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/confparmpost.html", boost::bind(&CWebServer::ZWaveCPNodeGetConf, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/refreshpost.html", boost::bind(&CWebServer::ZWaveCPNodeGetValues, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/valuepost.html", boost::bind(&CWebServer::ZWaveCPNodeSetValue, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/buttonpost.html", boost::bind(&CWebServer::ZWaveCPNodeSetButton, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/admpost.html", boost::bind(&CWebServer::ZWaveCPAdminCommand, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/nodepost.html", boost::bind(&CWebServer::ZWaveCPNodeChange, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/savepost.html", boost::bind(&CWebServer::ZWaveCPSaveConfig, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/thpost.html", boost::bind(&CWebServer::ZWaveCPTestHeal, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/topopost.html", boost::bind(&CWebServer::ZWaveCPGetTopo, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/statpost.html", boost::bind(&CWebServer::ZWaveCPGetStats, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/grouppost.html", boost::bind(&CWebServer::ZWaveCPSetGroup, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/scenepost.html", boost::bind(&CWebServer::ZWaveCPSceneCommand, this, _1, _2, _3));
//
//pollpost.html
//scenepost.html
//thpost.html
RegisterRType("openzwavenodes", boost::bind(&CWebServer::RType_OpenZWaveNodes, this, _1, _2, _3));
#endif
RegisterCommandCode("tellstickApplySettings", boost::bind(&CWebServer::Cmd_TellstickApplySettings, this, _1, _2, _3));
m_pWebEm->RegisterWhitelistURLString("/html5.appcache");
m_pWebEm->RegisterWhitelistURLString("/images/floorplans/plan");
//Start normal worker thread
m_bDoStop = false;
m_thread = std::make_shared<std::thread>(&CWebServer::Do_Work, this);
std::string server_name = "WebServer_" + settings.listening_port;
SetThreadName(m_thread->native_handle(), server_name.c_str());
return (m_thread != nullptr);
}
void CWebServer::StopServer()
{
m_bDoStop = true;
try
{
if (m_pWebEm == NULL)
return;
m_pWebEm->Stop();
if (m_thread) {
m_thread->join();
m_thread.reset();
}
delete m_pWebEm;
m_pWebEm = NULL;
}
catch (...)
{
}
}
void CWebServer::SetWebCompressionMode(const _eWebCompressionMode gzmode)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetWebCompressionMode(gzmode);
}
void CWebServer::SetAuthenticationMethod(const _eAuthenticationMethod amethod)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetAuthenticationMethod(amethod);
}
void CWebServer::SetWebTheme(const std::string &themename)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetWebTheme(themename);
}
void CWebServer::SetWebRoot(const std::string &webRoot)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetWebRoot(webRoot);
}
void CWebServer::RegisterCommandCode(const char* idname, webserver_response_function ResponseFunction, bool bypassAuthentication)
{
m_webcommands.insert(std::pair<std::string, webserver_response_function >(std::string(idname), ResponseFunction));
if (bypassAuthentication)
{
m_pWebEm->RegisterWhitelistURLString(idname);
}
}
void CWebServer::RegisterRType(const char* idname, webserver_response_function ResponseFunction)
{
m_webrtypes.insert(std::pair<std::string, webserver_response_function >(std::string(idname), ResponseFunction));
}
void CWebServer::HandleRType(const std::string &rtype, WebEmSession & session, const request& req, Json::Value &root)
{
std::map < std::string, webserver_response_function >::iterator pf = m_webrtypes.find(rtype);
if (pf != m_webrtypes.end())
{
pf->second(session, req, root);
}
}
void CWebServer::GetAppCache(WebEmSession & session, const request& req, reply & rep)
{
std::string response = "";
if (g_bDontCacheWWW)
{
return;
}
//Return the appcache file (dynamically generated)
std::string sLine;
std::string filename = szWWWFolder + "/html5.appcache";
std::string sWebTheme = "default";
m_sql.GetPreferencesVar("WebTheme", sWebTheme);
//Get Dynamic Theme Files
std::map<std::string, int> _ThemeFiles;
GetDirFilesRecursive(szWWWFolder + "/styles/" + sWebTheme + "/", _ThemeFiles);
//Get Dynamic Floorplan Images from database
std::map<std::string, int> _FloorplanFiles;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM Floorplans ORDER BY [Order]");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ImageURL = "images/floorplans/plan?idx=" + sd[0];
_FloorplanFiles[ImageURL] = 1;
}
}
std::ifstream is(filename.c_str());
if (is)
{
while (!is.eof())
{
getline(is, sLine);
if (!sLine.empty())
{
if (sLine.find("#BuildHash") != std::string::npos)
{
stdreplace(sLine, "#BuildHash", szAppHash);
}
else if (sLine.find("#ThemeFiles") != std::string::npos)
{
response += "#Theme=" + sWebTheme + '\n';
//Add all theme files
for (const auto & itt : _ThemeFiles)
{
std::string tfname = itt.first.substr(szWWWFolder.size() + 1);
stdreplace(tfname, "styles/" + sWebTheme, "acttheme");
response += tfname + '\n';
}
continue;
}
else if (sLine.find("#Floorplans") != std::string::npos)
{
//Add all floorplans
for (const auto & itt : _FloorplanFiles)
{
std::string tfname = itt.first;
response += tfname + '\n';
}
continue;
}
else if (sLine.find("#SwitchIcons") != std::string::npos)
{
//Add database switch icons
for (const auto & itt : m_custom_light_icons)
{
if (itt.idx >= 100)
{
std::string IconFile16 = itt.RootFile + ".png";
std::string IconFile48On = itt.RootFile + "48_On.png";
std::string IconFile48Off = itt.RootFile + "48_Off.png";
response += "images/" + CURLEncode::URLEncode(IconFile16) + '\n';
response += "images/" + CURLEncode::URLEncode(IconFile48On) + '\n';
response += "images/" + CURLEncode::URLEncode(IconFile48Off) + '\n';
}
}
}
}
response += sLine + '\n';
}
}
reply::set_content(&rep, response);
}
void CWebServer::GetJSonPage(WebEmSession & session, const request& req, reply & rep)
{
Json::Value root;
root["status"] = "ERR";
std::string rtype = request::findValue(&req, "type");
if (rtype == "command")
{
std::string cparam = request::findValue(&req, "param");
if (cparam.empty())
{
cparam = request::findValue(&req, "dparam");
if (cparam.empty())
{
goto exitjson;
}
}
if (cparam == "dologout")
{
session.forcelogin = true;
root["status"] = "OK";
root["title"] = "Logout";
goto exitjson;
}
_log.Debug(DEBUG_WEBSERVER, "WEBS GetJSon :%s :%s ", cparam.c_str(), req.uri.c_str());
HandleCommand(cparam, session, req, root);
} //(rtype=="command")
else {
HandleRType(rtype, session, req, root);
}
exitjson:
std::string jcallback = request::findValue(&req, "jsoncallback");
if (jcallback.size() == 0) {
reply::set_content(&rep, root.toStyledString());
return;
}
reply::set_content(&rep, "var data=" + root.toStyledString() + '\n' + jcallback + "(data);");
}
void CWebServer::Cmd_GetLanguage(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sValue;
if (m_sql.GetPreferencesVar("Language", sValue))
{
root["status"] = "OK";
root["title"] = "GetLanguage";
root["language"] = sValue;
}
}
void CWebServer::Cmd_GetThemes(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetThemes";
m_mainworker.GetAvailableWebThemes();
int ii = 0;
for (const auto & itt : m_mainworker.m_webthemes)
{
root["result"][ii]["theme"] = itt;
ii++;
}
}
void CWebServer::Cmd_GetTitle(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sValue;
root["status"] = "OK";
root["title"] = "GetTitle";
if (m_sql.GetPreferencesVar("Title", sValue))
root["Title"] = sValue;
else
root["Title"] = "Domoticz";
}
void CWebServer::Cmd_LoginCheck(WebEmSession & session, const request& req, Json::Value &root)
{
std::string tmpusrname = request::findValue(&req, "username");
std::string tmpusrpass = request::findValue(&req, "password");
if (
(tmpusrname.empty()) ||
(tmpusrpass.empty())
)
return;
std::string rememberme = request::findValue(&req, "rememberme");
std::string usrname;
std::string usrpass;
if (request_handler::url_decode(tmpusrname, usrname))
{
if (request_handler::url_decode(tmpusrpass, usrpass))
{
usrname = base64_decode(usrname);
int iUser = FindUser(usrname.c_str());
if (iUser == -1) {
// log brute force attack
_log.Log(LOG_ERROR, "Failed login attempt from %s for user '%s' !", session.remote_host.c_str(), usrname.c_str());
return;
}
if (m_users[iUser].Password != usrpass) {
// log brute force attack
_log.Log(LOG_ERROR, "Failed login attempt from %s for '%s' !", session.remote_host.c_str(), m_users[iUser].Username.c_str());
return;
}
_log.Log(LOG_STATUS, "Login successful from %s for user '%s'", session.remote_host.c_str(), m_users[iUser].Username.c_str());
root["status"] = "OK";
root["version"] = szAppVersion;
root["title"] = "logincheck";
session.isnew = true;
session.username = m_users[iUser].Username;
session.rights = m_users[iUser].userrights;
session.rememberme = (rememberme == "true");
root["user"] = session.username;
root["rights"] = session.rights;
}
}
}
void CWebServer::Cmd_GetHardwareTypes(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "GetHardwareTypes";
std::map<std::string, int> _htypes;
for (int ii = 0; ii < HTYPE_END; ii++)
{
bool bDoAdd = true;
#ifndef _DEBUG
#ifdef WIN32
if (
(ii == HTYPE_RaspberryBMP085) ||
(ii == HTYPE_RaspberryHTU21D) ||
(ii == HTYPE_RaspberryTSL2561) ||
(ii == HTYPE_RaspberryPCF8574) ||
(ii == HTYPE_RaspberryBME280) ||
(ii == HTYPE_RaspberryMCP23017)
)
{
bDoAdd = false;
}
else
{
#ifndef WITH_LIBUSB
if (
(ii == HTYPE_VOLCRAFTCO20) ||
(ii == HTYPE_TE923)
)
{
bDoAdd = false;
}
#endif
}
#endif
#endif
#ifndef WITH_OPENZWAVE
if (ii == HTYPE_OpenZWave)
bDoAdd = false;
#endif
#ifndef WITH_GPIO
if (ii == HTYPE_RaspberryGPIO)
{
bDoAdd = false;
}
if (ii == HTYPE_SysfsGpio)
{
bDoAdd = false;
}
#endif
if (ii == HTYPE_PythonPlugin)
bDoAdd = false;
if (bDoAdd)
_htypes[Hardware_Type_Desc(ii)] = ii;
}
//return a sorted hardware list
int ii = 0;
for (const auto & itt : _htypes)
{
root["result"][ii]["idx"] = itt.second;
root["result"][ii]["name"] = itt.first;
ii++;
}
#ifdef ENABLE_PYTHON
// Append Plugin list as well
PluginList(root["result"]);
#endif
}
void CWebServer::Cmd_AddHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string name = CURLEncode::URLDecode(request::findValue(&req, "name"));
std::string senabled = request::findValue(&req, "enabled");
std::string shtype = request::findValue(&req, "htype");
std::string address = request::findValue(&req, "address");
std::string sport = request::findValue(&req, "port");
std::string username = CURLEncode::URLDecode(request::findValue(&req, "username"));
std::string password = CURLEncode::URLDecode(request::findValue(&req, "password"));
std::string extra = CURLEncode::URLDecode(request::findValue(&req, "extra"));
std::string sdatatimeout = request::findValue(&req, "datatimeout");
if (
(name.empty()) ||
(senabled.empty()) ||
(shtype.empty())
)
return;
_eHardwareTypes htype = (_eHardwareTypes)atoi(shtype.c_str());
int iDataTimeout = atoi(sdatatimeout.c_str());
int mode1 = 0;
int mode2 = 0;
int mode3 = 0;
int mode4 = 0;
int mode5 = 0;
int mode6 = 0;
int port = atoi(sport.c_str());
std::string mode1Str = request::findValue(&req, "Mode1");
if (!mode1Str.empty()) {
mode1 = atoi(mode1Str.c_str());
}
std::string mode2Str = request::findValue(&req, "Mode2");
if (!mode2Str.empty()) {
mode2 = atoi(mode2Str.c_str());
}
std::string mode3Str = request::findValue(&req, "Mode3");
if (!mode3Str.empty()) {
mode3 = atoi(mode3Str.c_str());
}
std::string mode4Str = request::findValue(&req, "Mode4");
if (!mode4Str.empty()) {
mode4 = atoi(mode4Str.c_str());
}
std::string mode5Str = request::findValue(&req, "Mode5");
if (!mode5Str.empty()) {
mode5 = atoi(mode5Str.c_str());
}
std::string mode6Str = request::findValue(&req, "Mode6");
if (!mode6Str.empty()) {
mode6 = atoi(mode6Str.c_str());
}
if (IsSerialDevice(htype))
{
//USB/System
if (sport.empty())
return; //need to have a serial port
if (htype == HTYPE_TeleinfoMeter) {
// Teleinfo always has decimals. Chances to have a P1 and a Teleinfo device on the same
// Domoticz instance are very low as both are national standards (NL and FR)
m_sql.UpdatePreferencesVar("SmartMeterType", 0);
}
}
else if (IsNetworkDevice(htype))
{
//Lan
if (address.empty() || port == 0)
return;
if (htype == HTYPE_MySensorsMQTT || htype == HTYPE_MQTT) {
std::string modeqStr = request::findValue(&req, "mode1");
if (!modeqStr.empty()) {
mode1 = atoi(modeqStr.c_str());
}
}
if (htype == HTYPE_ECODEVICES) {
// EcoDevices always have decimals. Chances to have a P1 and a EcoDevice/Teleinfo device on the same
// Domoticz instance are very low as both are national standards (NL and FR)
m_sql.UpdatePreferencesVar("SmartMeterType", 0);
}
}
else if (htype == HTYPE_DomoticzInternal) {
// DomoticzInternal cannot be added manually
return;
}
else if (htype == HTYPE_Domoticz) {
//Remote Domoticz
if (address.empty() || port == 0)
return;
}
else if (htype == HTYPE_TE923) {
//all fine here!
}
else if (htype == HTYPE_VOLCRAFTCO20) {
//all fine here!
}
else if (htype == HTYPE_System) {
//There should be only one
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM Hardware WHERE (Type==%d)", HTYPE_System);
if (!result.empty())
return;
}
else if (htype == HTYPE_1WIRE) {
//all fine here!
}
else if (htype == HTYPE_Rtl433) {
//all fine here!
}
else if (htype == HTYPE_Pinger) {
//all fine here!
}
else if (htype == HTYPE_Kodi) {
//all fine here!
}
else if (htype == HTYPE_PanasonicTV) {
// all fine here!
}
else if (htype == HTYPE_LogitechMediaServer) {
//all fine here!
}
else if (htype == HTYPE_RaspberryBMP085) {
//all fine here!
}
else if (htype == HTYPE_RaspberryHTU21D) {
//all fine here!
}
else if (htype == HTYPE_RaspberryTSL2561) {
//all fine here!
}
else if (htype == HTYPE_RaspberryBME280) {
//all fine here!
}
else if (htype == HTYPE_RaspberryMCP23017) {
//all fine here!
}
else if (htype == HTYPE_Dummy) {
//all fine here!
}
else if (htype == HTYPE_Tellstick) {
//all fine here!
}
else if (htype == HTYPE_EVOHOME_SCRIPT || htype == HTYPE_EVOHOME_SERIAL || htype == HTYPE_EVOHOME_WEB || htype == HTYPE_EVOHOME_TCP) {
//all fine here!
}
else if (htype == HTYPE_PiFace) {
//all fine here!
}
else if (htype == HTYPE_HTTPPOLLER) {
//all fine here!
}
else if (htype == HTYPE_BleBox) {
//all fine here!
}
else if (htype == HTYPE_HEOS) {
//all fine here!
}
else if (htype == HTYPE_Yeelight) {
//all fine here!
}
else if (htype == HTYPE_XiaomiGateway) {
//all fine here!
}
else if (htype == HTYPE_Arilux) {
//all fine here!
}
else if (htype == HTYPE_USBtinGateway) {
//All fine here
}
else if (
(htype == HTYPE_Wunderground) ||
(htype == HTYPE_DarkSky) ||
(htype == HTYPE_AccuWeather) ||
(htype == HTYPE_OpenWeatherMap) ||
(htype == HTYPE_ICYTHERMOSTAT) ||
(htype == HTYPE_TOONTHERMOSTAT) ||
(htype == HTYPE_AtagOne) ||
(htype == HTYPE_PVOUTPUT_INPUT) ||
(htype == HTYPE_NEST) ||
(htype == HTYPE_ANNATHERMOSTAT) ||
(htype == HTYPE_THERMOSMART) ||
(htype == HTYPE_Tado) ||
(htype == HTYPE_Netatmo)
)
{
if (
(username.empty()) ||
(password.empty())
)
return;
}
else if (htype == HTYPE_SolarEdgeAPI)
{
if (
(username.empty())
)
return;
}
else if (htype == HTYPE_Nest_OAuthAPI) {
if (
(username == "") &&
(extra == "||")
)
return;
}
else if (htype == HTYPE_SBFSpot) {
if (username.empty())
return;
}
else if (htype == HTYPE_HARMONY_HUB) {
if (
(address.empty() || port == 0)
)
return;
}
else if (htype == HTYPE_Philips_Hue) {
if (
(username.empty()) ||
(address.empty() || port == 0)
)
return;
if (port == 0)
port = 80;
}
else if (htype == HTYPE_WINDDELEN) {
std::string mill_id = request::findValue(&req, "Mode1");
if (
(mill_id.empty()) ||
(sport.empty())
)
return;
mode1 = atoi(mill_id.c_str());
}
else if (htype == HTYPE_Honeywell) {
//all fine here!
}
else if (htype == HTYPE_RaspberryGPIO) {
//all fine here!
}
else if (htype == HTYPE_SysfsGpio) {
//all fine here!
}
else if (htype == HTYPE_OpenWebNetTCP) {
//All fine here
}
else if (htype == HTYPE_Daikin) {
//All fine here
}
else if (htype == HTYPE_GoodweAPI) {
if (username.empty())
return;
}
else if (htype == HTYPE_PythonPlugin) {
//All fine here
}
else if (htype == HTYPE_RaspberryPCF8574) {
//All fine here
}
else if (htype == HTYPE_OpenWebNetUSB) {
//All fine here
}
else if (htype == HTYPE_IntergasInComfortLAN2RF) {
//All fine here
}
else if (htype == HTYPE_EnphaseAPI) {
//All fine here
}
else if (htype == HTYPE_EcoCompteur) {
//all fine here!
}
else
return;
root["status"] = "OK";
root["title"] = "AddHardware";
std::vector<std::vector<std::string> > result;
if (htype == HTYPE_Domoticz)
{
if (password.size() != 32)
{
password = GenerateMD5Hash(password);
}
}
else if ((htype == HTYPE_S0SmartMeterUSB) || (htype == HTYPE_S0SmartMeterTCP))
{
extra = "0;1000;0;1000;0;1000;0;1000;0;1000";
}
else if (htype == HTYPE_Pinger)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_Kodi)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_PanasonicTV)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_LogitechMediaServer)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_HEOS)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_Tellstick)
{
mode1 = 4;
mode2 = 500;
}
if (htype == HTYPE_HTTPPOLLER) {
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q','%q','%q','%q', '%q', '%q', '%q', '%q', %d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1Str.c_str(), mode2Str.c_str(), mode3Str.c_str(), mode4Str.c_str(), mode5Str.c_str(), mode6Str.c_str(),
iDataTimeout
);
}
else if (htype == HTYPE_PythonPlugin) {
sport = request::findValue(&req, "serialport");
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q','%q','%q','%q', '%q', '%q', '%q', '%q', %d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1Str.c_str(), mode2Str.c_str(), mode3Str.c_str(), mode4Str.c_str(), mode5Str.c_str(), mode6Str.c_str(),
iDataTimeout
);
}
else if (
(htype == HTYPE_RFXtrx433)||
(htype == HTYPE_RFXtrx868)
)
{
//No Extra field here, handled in CWebServer::SetRFXCOMMode
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q',%d,%d,%d,%d,%d,%d,%d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout
);
extra = "0";
}
else {
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q','%q',%d,%d,%d,%d,%d,%d,%d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout
);
}
//add the device for real in our system
result = m_sql.safe_query("SELECT MAX(ID) FROM Hardware");
if (!result.empty())
{
std::vector<std::string> sd = result[0];
int ID = atoi(sd[0].c_str());
root["idx"] = sd[0].c_str(); // OTO output the created ID for easier management on the caller side (if automated)
m_mainworker.AddHardwareFromParams(ID, name, (senabled == "true") ? true : false, htype, address, port, sport, username, password, extra, mode1, mode2, mode3, mode4, mode5, mode6, iDataTimeout, true);
}
}
void CWebServer::Cmd_UpdateHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string name = CURLEncode::URLDecode(request::findValue(&req, "name"));
std::string senabled = request::findValue(&req, "enabled");
std::string shtype = request::findValue(&req, "htype");
std::string address = request::findValue(&req, "address");
std::string sport = request::findValue(&req, "port");
std::string username = CURLEncode::URLDecode(request::findValue(&req, "username"));
std::string password = CURLEncode::URLDecode(request::findValue(&req, "password"));
std::string extra = CURLEncode::URLDecode(request::findValue(&req, "extra"));
std::string sdatatimeout = request::findValue(&req, "datatimeout");
if (
(name.empty()) ||
(senabled.empty()) ||
(shtype.empty())
)
return;
int mode1 = atoi(request::findValue(&req, "Mode1").c_str());
int mode2 = atoi(request::findValue(&req, "Mode2").c_str());
int mode3 = atoi(request::findValue(&req, "Mode3").c_str());
int mode4 = atoi(request::findValue(&req, "Mode4").c_str());
int mode5 = atoi(request::findValue(&req, "Mode5").c_str());
int mode6 = atoi(request::findValue(&req, "Mode6").c_str());
bool bEnabled = (senabled == "true") ? true : false;
_eHardwareTypes htype = (_eHardwareTypes)atoi(shtype.c_str());
int iDataTimeout = atoi(sdatatimeout.c_str());
int port = atoi(sport.c_str());
bool bIsSerial = false;
if (IsSerialDevice(htype))
{
//USB/System
bIsSerial = true;
if (bEnabled)
{
if (sport.empty())
return; //need to have a serial port
}
}
else if (
(htype == HTYPE_RFXLAN) || (htype == HTYPE_P1SmartMeterLAN) ||
(htype == HTYPE_YouLess) || (htype == HTYPE_OpenThermGatewayTCP) || (htype == HTYPE_LimitlessLights) ||
(htype == HTYPE_SolarEdgeTCP) || (htype == HTYPE_WOL) || (htype == HTYPE_S0SmartMeterTCP) || (htype == HTYPE_ECODEVICES) || (htype == HTYPE_Mochad) ||
(htype == HTYPE_MySensorsTCP) || (htype == HTYPE_MySensorsMQTT) || (htype == HTYPE_MQTT) || (htype == HTYPE_TTN_MQTT) || (htype == HTYPE_FRITZBOX) || (htype == HTYPE_ETH8020) || (htype == HTYPE_Sterbox) ||
(htype == HTYPE_KMTronicTCP) || (htype == HTYPE_KMTronicUDP) || (htype == HTYPE_SOLARMAXTCP) || (htype == HTYPE_RelayNet) || (htype == HTYPE_SatelIntegra) || (htype == HTYPE_eHouseTCP) || (htype == HTYPE_RFLINKTCP) ||
(htype == HTYPE_Comm5TCP || (htype == HTYPE_Comm5SMTCP) || (htype == HTYPE_CurrentCostMeterLAN)) ||
(htype == HTYPE_NefitEastLAN) || (htype == HTYPE_DenkoviHTTPDevices) || (htype == HTYPE_DenkoviTCPDevices) || (htype == HTYPE_Ec3kMeterTCP) || (htype == HTYPE_MultiFun) || (htype == HTYPE_ZIBLUETCP) || (htype == HTYPE_OnkyoAVTCP)
) {
//Lan
if (address.empty())
return;
}
else if (htype == HTYPE_DomoticzInternal) {
// DomoticzInternal cannot be updated
return;
}
else if (htype == HTYPE_Domoticz) {
//Remote Domoticz
if (address.empty())
return;
}
else if (htype == HTYPE_System) {
//There should be only one, and with this ID
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM Hardware WHERE (Type==%d)", HTYPE_System);
if (!result.empty())
{
int hID = atoi(result[0][0].c_str());
int aID = atoi(idx.c_str());
if (hID != aID)
return;
}
}
else if (htype == HTYPE_TE923) {
//All fine here
}
else if (htype == HTYPE_VOLCRAFTCO20) {
//All fine here
}
else if (htype == HTYPE_1WIRE) {
//All fine here
}
else if (htype == HTYPE_Pinger) {
//All fine here
}
else if (htype == HTYPE_Kodi) {
//All fine here
}
else if (htype == HTYPE_PanasonicTV) {
//All fine here
}
else if (htype == HTYPE_LogitechMediaServer) {
//All fine here
}
else if (htype == HTYPE_RaspberryBMP085) {
//All fine here
}
else if (htype == HTYPE_RaspberryHTU21D) {
//All fine here
}
else if (htype == HTYPE_RaspberryTSL2561) {
//All fine here
}
else if (htype == HTYPE_RaspberryBME280) {
//All fine here
}
else if (htype == HTYPE_RaspberryMCP23017) {
//all fine here!
}
else if (htype == HTYPE_Dummy) {
//All fine here
}
else if (htype == HTYPE_EVOHOME_SCRIPT || htype == HTYPE_EVOHOME_SERIAL || htype == HTYPE_EVOHOME_WEB || htype == HTYPE_EVOHOME_TCP) {
//All fine here
}
else if (htype == HTYPE_PiFace) {
//All fine here
}
else if (htype == HTYPE_HTTPPOLLER) {
//all fine here!
}
else if (htype == HTYPE_BleBox) {
//All fine here
}
else if (htype == HTYPE_HEOS) {
//All fine here
}
else if (htype == HTYPE_Yeelight) {
//All fine here
}
else if (htype == HTYPE_XiaomiGateway) {
//All fine here
}
else if (htype == HTYPE_Arilux) {
//All fine here
}
else if (htype == HTYPE_USBtinGateway) {
//All fine here
}
else if (
(htype == HTYPE_Wunderground) ||
(htype == HTYPE_DarkSky) ||
(htype == HTYPE_AccuWeather) ||
(htype == HTYPE_OpenWeatherMap) ||
(htype == HTYPE_ICYTHERMOSTAT) ||
(htype == HTYPE_TOONTHERMOSTAT) ||
(htype == HTYPE_AtagOne) ||
(htype == HTYPE_PVOUTPUT_INPUT) ||
(htype == HTYPE_NEST) ||
(htype == HTYPE_ANNATHERMOSTAT) ||
(htype == HTYPE_THERMOSMART) ||
(htype == HTYPE_Tado) ||
(htype == HTYPE_Netatmo)
)
{
if (
(username.empty()) ||
(password.empty())
)
return;
}
else if (htype == HTYPE_SolarEdgeAPI)
{
if (
(username.empty())
)
return;
}
else if (htype == HTYPE_Nest_OAuthAPI) {
if (
(username == "") &&
(extra == "||")
)
return;
}
else if (htype == HTYPE_HARMONY_HUB) {
if (
(address.empty())
)
return;
}
else if (htype == HTYPE_Philips_Hue) {
if (
(username.empty()) ||
(address.empty())
)
return;
if (port == 0)
port = 80;
}
else if (htype == HTYPE_RaspberryGPIO) {
//all fine here!
}
else if (htype == HTYPE_SysfsGpio) {
//all fine here!
}
else if (htype == HTYPE_Rtl433) {
//all fine here!
}
else if (htype == HTYPE_Daikin) {
//all fine here!
}
else if (htype == HTYPE_SBFSpot) {
if (username.empty())
return;
}
else if (htype == HTYPE_WINDDELEN) {
std::string mill_id = request::findValue(&req, "Mode1");
if (
(mill_id.empty()) ||
(sport.empty())
)
return;
}
else if (htype == HTYPE_Honeywell) {
//All fine here
}
else if (htype == HTYPE_OpenWebNetTCP) {
//All fine here
}
else if (htype == HTYPE_PythonPlugin) {
//All fine here
}
else if (htype == HTYPE_GoodweAPI) {
if (username.empty()) {
return;
}
}
else if (htype == HTYPE_RaspberryPCF8574) {
//All fine here
}
else if (htype == HTYPE_OpenWebNetUSB) {
//All fine here
}
else if (htype == HTYPE_IntergasInComfortLAN2RF) {
//All fine here
}
else if (htype == HTYPE_EnphaseAPI) {
//all fine here!
}
else
return;
std::string mode1Str;
std::string mode2Str;
std::string mode3Str;
std::string mode4Str;
std::string mode5Str;
std::string mode6Str;
root["status"] = "OK";
root["title"] = "UpdateHardware";
if (htype == HTYPE_Domoticz)
{
if (password.size() != 32)
{
password = GenerateMD5Hash(password);
}
}
if ((bIsSerial) && (!bEnabled) && (sport.empty()))
{
//just disable the device
m_sql.safe_query(
"UPDATE Hardware SET Enabled=%d WHERE (ID == '%q')",
(bEnabled == true) ? 1 : 0,
idx.c_str()
);
}
else
{
if (htype == HTYPE_HTTPPOLLER) {
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Extra='%q', DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
iDataTimeout,
idx.c_str()
);
}
else if (htype == HTYPE_PythonPlugin) {
mode1Str = request::findValue(&req, "Mode1");
mode2Str = request::findValue(&req, "Mode2");
mode3Str = request::findValue(&req, "Mode3");
mode4Str = request::findValue(&req, "Mode4");
mode5Str = request::findValue(&req, "Mode5");
mode6Str = request::findValue(&req, "Mode6");
sport = request::findValue(&req, "serialport");
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Extra='%q', Mode1='%q', Mode2='%q', Mode3='%q', Mode4='%q', Mode5='%q', Mode6='%q', DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1Str.c_str(), mode2Str.c_str(), mode3Str.c_str(), mode4Str.c_str(), mode5Str.c_str(), mode6Str.c_str(),
iDataTimeout,
idx.c_str()
);
}
else if (
(htype == HTYPE_RFXtrx433) ||
(htype == HTYPE_RFXtrx868)
)
{
//No Extra field here, handled in CWebServer::SetRFXCOMMode
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Mode1=%d, Mode2=%d, Mode3=%d, Mode4=%d, Mode5=%d, Mode6=%d, DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(bEnabled == true) ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout,
idx.c_str()
);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Extra FROM Hardware WHERE ID=%q", idx.c_str());
if (!result.empty())
extra = result[0][0];
}
else {
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Extra='%q', Mode1=%d, Mode2=%d, Mode3=%d, Mode4=%d, Mode5=%d, Mode6=%d, DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(bEnabled == true) ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout,
idx.c_str()
);
}
}
//re-add the device in our system
int ID = atoi(idx.c_str());
m_mainworker.AddHardwareFromParams(ID, name, bEnabled, htype, address, port, sport, username, password, extra, mode1, mode2, mode3, mode4, mode5, mode6, iDataTimeout, true);
}
void CWebServer::Cmd_GetDeviceValueOptions(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::vector<std::string> result;
result = CBasePush::DropdownOptions(atoi(idx.c_str()));
if ((result.size() == 1) && result[0] == "Status") {
root["result"][0]["Value"] = 0;
root["result"][0]["Wording"] = result[0];
}
else {
int ii = 0;
for (const auto & itt : result)
{
std::string ddOption = itt;
root["result"][ii]["Value"] = ii + 1;
root["result"][ii]["Wording"] = ddOption.c_str();
ii++;
}
}
root["status"] = "OK";
root["title"] = "GetDeviceValueOptions";
}
void CWebServer::Cmd_GetDeviceValueOptionWording(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string pos = request::findValue(&req, "pos");
if ((idx.empty()) || (pos.empty()))
return;
std::string wording;
wording = CBasePush::DropdownOptionsValue(atoi(idx.c_str()), atoi(pos.c_str()));
root["wording"] = wording;
root["status"] = "OK";
root["title"] = "GetDeviceValueOptions";
}
void CWebServer::Cmd_AddUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string variablename = request::findValue(&req, "vname");
std::string variablevalue = request::findValue(&req, "vvalue");
std::string variabletype = request::findValue(&req, "vtype");
if (
(variablename.empty()) ||
(variabletype.empty()) ||
((variablevalue.empty()) && (variabletype != "2"))
)
return;
root["title"] = "AddUserVariable";
std::string errorMessage;
if (!m_sql.AddUserVariable(variablename, (const _eUsrVariableType)atoi(variabletype.c_str()), variablevalue, errorMessage))
{
root["status"] = "ERR";
root["message"] = errorMessage;
}
else {
root["status"] = "OK";
}
}
void CWebServer::Cmd_DeleteUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
m_sql.DeleteUserVariable(idx);
root["status"] = "OK";
root["title"] = "DeleteUserVariable";
}
void CWebServer::Cmd_UpdateUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string variablename = request::findValue(&req, "vname");
std::string variablevalue = request::findValue(&req, "vvalue");
std::string variabletype = request::findValue(&req, "vtype");
if (
(variablename.empty()) ||
(variabletype.empty()) ||
((variablevalue.empty()) && (variabletype != "2"))
)
return;
std::vector<std::vector<std::string> > result;
if (idx.empty())
{
result = m_sql.safe_query("SELECT ID FROM UserVariables WHERE Name='%q'", variablename.c_str());
if (result.empty())
return;
idx = result[0][0];
}
result = m_sql.safe_query("SELECT Name, ValueType FROM UserVariables WHERE ID='%q'", idx.c_str());
if (result.empty())
return;
bool bTypeNameChanged = false;
if (variablename != result[0][0])
bTypeNameChanged = true; //new name
else if (variabletype != result[0][1])
bTypeNameChanged = true; //new type
root["title"] = "UpdateUserVariable";
std::string errorMessage;
if (!m_sql.UpdateUserVariable(idx, variablename, (const _eUsrVariableType)atoi(variabletype.c_str()), variablevalue, !bTypeNameChanged, errorMessage))
{
root["status"] = "ERR";
root["message"] = errorMessage;
}
else {
root["status"] = "OK";
if (bTypeNameChanged)
{
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentUserVariables();
}
}
}
void CWebServer::Cmd_GetUserVariables(WebEmSession & session, const request& req, Json::Value &root)
{
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, ValueType, Value, LastUpdate FROM UserVariables");
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Type"] = sd[2];
root["result"][ii]["Value"] = sd[3];
root["result"][ii]["LastUpdate"] = sd[4];
ii++;
}
root["status"] = "OK";
root["title"] = "GetUserVariables";
}
void CWebServer::Cmd_GetUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
int iVarID = atoi(idx.c_str());
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, ValueType, Value, LastUpdate FROM UserVariables WHERE (ID==%d)", iVarID);
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Type"] = sd[2];
root["result"][ii]["Value"] = sd[3];
root["result"][ii]["LastUpdate"] = sd[4];
ii++;
}
root["status"] = "OK";
root["title"] = "GetUserVariable";
}
void CWebServer::Cmd_AllowNewHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sTimeout = request::findValue(&req, "timeout");
if (sTimeout.empty())
return;
root["status"] = "OK";
root["title"] = "AllowNewHardware";
m_sql.AllowNewHardwareTimer(atoi(sTimeout.c_str()));
}
void CWebServer::Cmd_DeleteHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
int hwID = atoi(idx.c_str());
CDomoticzHardwareBase *pBaseHardware = m_mainworker.GetHardware(hwID);
if ((pBaseHardware != NULL) && (pBaseHardware->HwdType == HTYPE_DomoticzInternal)) {
// DomoticzInternal cannot be removed
return;
}
root["status"] = "OK";
root["title"] = "DeleteHardware";
m_mainworker.RemoveDomoticzHardware(hwID);
m_sql.DeleteHardware(idx);
}
void CWebServer::Cmd_GetLog(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetLog";
time_t lastlogtime = 0;
std::string slastlogtime = request::findValue(&req, "lastlogtime");
if (slastlogtime != "")
{
std::stringstream s_str(slastlogtime);
s_str >> lastlogtime;
}
_eLogLevel lLevel = LOG_NORM;
std::string sloglevel = request::findValue(&req, "loglevel");
if (!sloglevel.empty())
{
lLevel = (_eLogLevel)atoi(sloglevel.c_str());
}
std::list<CLogger::_tLogLineStruct> logmessages = _log.GetLog(lLevel);
int ii = 0;
for (const auto & itt : logmessages)
{
if (itt.logtime > lastlogtime)
{
std::stringstream szLogTime;
szLogTime << itt.logtime;
root["LastLogTime"] = szLogTime.str();
root["result"][ii]["level"] = static_cast<int>(itt.level);
root["result"][ii]["message"] = itt.logmessage;
ii++;
}
}
}
void CWebServer::Cmd_ClearLog(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "ClearLog";
_log.ClearLog();
}
//Plan Functions
void CWebServer::Cmd_AddPlan(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string name = request::findValue(&req, "name");
root["status"] = "OK";
root["title"] = "AddPlan";
m_sql.safe_query(
"INSERT INTO Plans (Name) VALUES ('%q')",
name.c_str()
);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT MAX(ID) FROM Plans");
if (!result.empty())
{
std::vector<std::string> sd = result[0];
int ID = atoi(sd[0].c_str());
root["idx"] = sd[0].c_str(); // OTO output the created ID for easier management on the caller side (if automated)
}
}
void CWebServer::Cmd_UpdatePlan(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string name = request::findValue(&req, "name");
if (
(name.empty())
)
return;
root["status"] = "OK";
root["title"] = "UpdatePlan";
m_sql.safe_query(
"UPDATE Plans SET Name='%q' WHERE (ID == '%q')",
name.c_str(),
idx.c_str()
);
}
void CWebServer::Cmd_DeletePlan(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeletePlan";
m_sql.safe_query(
"DELETE FROM DeviceToPlansMap WHERE (PlanID == '%q')",
idx.c_str()
);
m_sql.safe_query(
"DELETE FROM Plans WHERE (ID == '%q')",
idx.c_str()
);
}
void CWebServer::Cmd_GetUnusedPlanDevices(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetUnusedPlanDevices";
std::string sunique = request::findValue(&req, "unique");
if (sunique.empty())
return;
int iUnique = (sunique == "true") ? 1 : 0;
int ii = 0;
std::vector<std::vector<std::string> > result;
std::vector<std::vector<std::string> > result2;
result = m_sql.safe_query("SELECT T1.[ID], T1.[Name], T1.[Type], T1.[SubType], T2.[Name] AS HardwareName FROM DeviceStatus as T1, Hardware as T2 WHERE (T1.[Used]==1) AND (T2.[ID]==T1.[HardwareID]) ORDER BY T2.[Name], T1.[Name]");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
bool bDoAdd = true;
if (iUnique)
{
result2 = m_sql.safe_query("SELECT ID FROM DeviceToPlansMap WHERE (DeviceRowID=='%q') AND (DevSceneType==0)",
sd[0].c_str());
bDoAdd = (result2.size() == 0);
}
if (bDoAdd)
{
int _dtype = atoi(sd[2].c_str());
std::string Name = "[" + sd[4] + "] " + sd[1] + " (" + RFX_Type_Desc(_dtype, 1) + "/" + RFX_Type_SubType_Desc(_dtype, atoi(sd[3].c_str())) + ")";
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
//Add Scenes
result = m_sql.safe_query("SELECT ID, Name FROM Scenes ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
bool bDoAdd = true;
if (iUnique)
{
result2 = m_sql.safe_query("SELECT ID FROM DeviceToPlansMap WHERE (DeviceRowID=='%q') AND (DevSceneType==1)",
sd[0].c_str());
bDoAdd = (result2.size() == 0);
}
if (bDoAdd)
{
root["result"][ii]["type"] = 1;
root["result"][ii]["idx"] = sd[0];
std::string sname = "[Scene] " + sd[1];
root["result"][ii]["Name"] = sname;
ii++;
}
}
}
}
void CWebServer::Cmd_AddPlanActiveDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string sactivetype = request::findValue(&req, "activetype");
std::string activeidx = request::findValue(&req, "activeidx");
if (
(idx.empty()) ||
(sactivetype.empty()) ||
(activeidx.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddPlanActiveDevice";
int activetype = atoi(sactivetype.c_str());
//check if it is not already there
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM DeviceToPlansMap WHERE (DeviceRowID=='%q') AND (DevSceneType==%d) AND (PlanID=='%q')",
activeidx.c_str(), activetype, idx.c_str());
if (result.empty())
{
m_sql.safe_query(
"INSERT INTO DeviceToPlansMap (DevSceneType,DeviceRowID, PlanID) VALUES (%d,'%q','%q')",
activetype,
activeidx.c_str(),
idx.c_str()
);
}
}
void CWebServer::Cmd_GetPlanDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetPlanDevices";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, DevSceneType, DeviceRowID, [Order] FROM DeviceToPlansMap WHERE (PlanID=='%q') ORDER BY [Order]",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
int DevSceneType = atoi(sd[1].c_str());
std::string DevSceneRowID = sd[2];
std::string Name = "";
if (DevSceneType == 0)
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM DeviceStatus WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = result2[0][0];
}
}
else
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM Scenes WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = "[Scene] " + result2[0][0];
}
}
if (Name != "")
{
root["result"][ii]["idx"] = ID;
root["result"][ii]["devidx"] = DevSceneRowID;
root["result"][ii]["type"] = DevSceneType;
root["result"][ii]["DevSceneRowID"] = DevSceneRowID;
root["result"][ii]["order"] = sd[3];
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
}
void CWebServer::Cmd_DeletePlanDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeletePlanDevice";
m_sql.safe_query("DELETE FROM DeviceToPlansMap WHERE (ID == '%q')", idx.c_str());
}
void CWebServer::Cmd_SetPlanDeviceCoords(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
std::string planidx = request::findValue(&req, "planidx");
std::string xoffset = request::findValue(&req, "xoffset");
std::string yoffset = request::findValue(&req, "yoffset");
std::string type = request::findValue(&req, "DevSceneType");
if ((idx.empty()) || (planidx.empty()) || (xoffset.empty()) || (yoffset.empty()))
return;
if (type != "1") type = "0"; // 0 = Device, 1 = Scene/Group
root["status"] = "OK";
root["title"] = "SetPlanDeviceCoords";
m_sql.safe_query("UPDATE DeviceToPlansMap SET [XOffset] = '%q', [YOffset] = '%q' WHERE (DeviceRowID='%q') and (PlanID='%q') and (DevSceneType='%q')",
xoffset.c_str(), yoffset.c_str(), idx.c_str(), planidx.c_str(), type.c_str());
_log.Log(LOG_STATUS, "(Floorplan) Device '%s' coordinates set to '%s,%s' in plan '%s'.", idx.c_str(), xoffset.c_str(), yoffset.c_str(), planidx.c_str());
}
void CWebServer::Cmd_DeleteAllPlanDevices(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllPlanDevices";
m_sql.safe_query("DELETE FROM DeviceToPlansMap WHERE (PlanID == '%q')", idx.c_str());
}
void CWebServer::Cmd_ChangePlanOrder(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string sway = request::findValue(&req, "way");
if (sway.empty())
return;
bool bGoUp = (sway == "0");
std::string aOrder, oID, oOrder;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT [Order] FROM Plans WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
aOrder = result[0][0];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Plans WHERE ([Order]>'%q') ORDER BY [Order] ASC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Plans WHERE ([Order]<'%q') ORDER BY [Order] DESC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangePlanOrder";
m_sql.safe_query("UPDATE Plans SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
m_sql.safe_query("UPDATE Plans SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
void CWebServer::Cmd_ChangePlanDeviceOrder(WebEmSession & session, const request& req, Json::Value &root)
{
std::string planid = request::findValue(&req, "planid");
std::string idx = request::findValue(&req, "idx");
std::string sway = request::findValue(&req, "way");
if (
(planid.empty()) ||
(idx.empty()) ||
(sway.empty())
)
return;
bool bGoUp = (sway == "0");
std::string aOrder, oID, oOrder;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT [Order] FROM DeviceToPlansMap WHERE ((ID=='%q') AND (PlanID=='%q'))",
idx.c_str(), planid.c_str());
if (result.empty())
return;
aOrder = result[0][0];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM DeviceToPlansMap WHERE (([Order]>'%q') AND (PlanID=='%q')) ORDER BY [Order] ASC",
aOrder.c_str(), planid.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM DeviceToPlansMap WHERE (([Order]<'%q') AND (PlanID=='%q')) ORDER BY [Order] DESC",
aOrder.c_str(), planid.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangePlanOrder";
m_sql.safe_query("UPDATE DeviceToPlansMap SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
m_sql.safe_query("UPDATE DeviceToPlansMap SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
void CWebServer::Cmd_GetVersion(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetVersion";
root["version"] = szAppVersion;
root["hash"] = szAppHash;
root["build_time"] = szAppDate;
CdzVents* dzvents = CdzVents::GetInstance();
root["dzvents_version"] = dzvents->GetVersion();
root["python_version"] = szPyVersion;
if (session.rights != 2)
{
//only admin users will receive the update notification
root["UseUpdate"] = false;
root["HaveUpdate"] = false;
}
else
{
root["UseUpdate"] = g_bUseUpdater;
root["HaveUpdate"] = m_mainworker.IsUpdateAvailable(false);
root["DomoticzUpdateURL"] = m_mainworker.m_szDomoticzUpdateURL;
root["SystemName"] = m_mainworker.m_szSystemName;
root["Revision"] = m_mainworker.m_iRevision;
}
}
void CWebServer::Cmd_GetAuth(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetAuth";
if (session.rights != -1)
{
root["version"] = szAppVersion;
}
root["user"] = session.username;
root["rights"] = session.rights;
}
void CWebServer::Cmd_GetUptime(WebEmSession & session, const request& req, Json::Value &root)
{
//this is used in the about page, we are going to round the seconds a bit to display nicer
time_t atime = mytime(NULL);
time_t tuptime = atime - m_StartTime;
//round to 5 seconds (nicer in about page)
tuptime = ((tuptime / 5) * 5) + 5;
int days, hours, minutes, seconds;
days = (int)(tuptime / 86400);
tuptime -= (days * 86400);
hours = (int)(tuptime / 3600);
tuptime -= (hours * 3600);
minutes = (int)(tuptime / 60);
tuptime -= (minutes * 60);
seconds = (int)tuptime;
root["status"] = "OK";
root["title"] = "GetUptime";
root["days"] = days;
root["hours"] = hours;
root["minutes"] = minutes;
root["seconds"] = seconds;
}
void CWebServer::Cmd_GetActualHistory(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetActualHistory";
std::string historyfile = szUserDataFolder + "History.txt";
std::ifstream infile;
int ii = 0;
infile.open(historyfile.c_str());
std::string sLine;
if (infile.is_open())
{
while (!infile.eof())
{
getline(infile, sLine);
root["LastLogTime"] = "";
if (sLine.find("Version ") == 0)
root["result"][ii]["level"] = 1;
else
root["result"][ii]["level"] = 0;
root["result"][ii]["message"] = sLine;
ii++;
}
}
}
void CWebServer::Cmd_GetNewHistory(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetNewHistory";
std::string historyfile;
int nValue;
m_sql.GetPreferencesVar("ReleaseChannel", nValue);
bool bIsBetaChannel = (nValue != 0);
std::string szHistoryURL = "https://www.domoticz.com/download.php?channel=stable&type=history";
if (bIsBetaChannel)
{
utsname my_uname;
if (uname(&my_uname) < 0)
return;
std::string systemname = my_uname.sysname;
std::string machine = my_uname.machine;
std::transform(systemname.begin(), systemname.end(), systemname.begin(), ::tolower);
if (machine == "armv6l")
{
//Seems like old arm systems can also use the new arm build
machine = "armv7l";
}
if (((machine != "armv6l") && (machine != "armv7l") && (systemname != "windows") && (machine != "x86_64") && (machine != "aarch64")) || (strstr(my_uname.release, "ARCH+") != NULL))
szHistoryURL = "https://www.domoticz.com/download.php?channel=beta&type=history";
else
szHistoryURL = "https://www.domoticz.com/download.php?channel=beta&type=history&system=" + systemname + "&machine=" + machine;
}
if (!HTTPClient::GET(szHistoryURL, historyfile))
{
historyfile = "Unable to get Online History document !!";
}
std::istringstream stream(historyfile);
std::string sLine;
int ii = 0;
while (std::getline(stream, sLine))
{
root["LastLogTime"] = "";
if (sLine.find("Version ") == 0)
root["result"][ii]["level"] = 1;
else
root["result"][ii]["level"] = 0;
root["result"][ii]["message"] = sLine;
ii++;
}
}
void CWebServer::Cmd_GetConfig(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights == -1)
{
session.reply_status = reply::forbidden;
return;//Only auth user allowed
}
root["status"] = "OK";
root["title"] = "GetConfig";
bool bHaveUser = (session.username != "");
int urights = 3;
unsigned long UserID = 0;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
UserID = m_users[iUser].ID;
}
}
int nValue;
std::string sValue;
if (m_sql.GetPreferencesVar("Language", sValue))
{
root["language"] = sValue;
}
if (m_sql.GetPreferencesVar("DegreeDaysBaseTemperature", sValue))
{
root["DegreeDaysBaseTemperature"] = atof(sValue.c_str());
}
nValue = 0;
int iDashboardType = 0;
m_sql.GetPreferencesVar("DashboardType", iDashboardType);
root["DashboardType"] = iDashboardType;
m_sql.GetPreferencesVar("MobileType", nValue);
root["MobileType"] = nValue;
nValue = 1;
m_sql.GetPreferencesVar("5MinuteHistoryDays", nValue);
root["FiveMinuteHistoryDays"] = nValue;
nValue = 1;
m_sql.GetPreferencesVar("ShowUpdateEffect", nValue);
root["result"]["ShowUpdatedEffect"] = (nValue == 1);
root["AllowWidgetOrdering"] = m_sql.m_bAllowWidgetOrdering;
root["WindScale"] = m_sql.m_windscale*10.0f;
root["WindSign"] = m_sql.m_windsign;
root["TempScale"] = m_sql.m_tempscale;
root["TempSign"] = m_sql.m_tempsign;
std::string Latitude = "1";
std::string Longitude = "1";
if (m_sql.GetPreferencesVar("Location", nValue, sValue))
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
Latitude = strarray[0];
Longitude = strarray[1];
}
}
root["Latitude"] = Latitude;
root["Longitude"] = Longitude;
#ifndef NOCLOUD
bool bEnableTabProxy = request::get_req_header(&req, "X-From-MyDomoticz") != NULL;
#else
bool bEnableTabProxy = false;
#endif
int bEnableTabDashboard = 1;
int bEnableTabFloorplans = 1;
int bEnableTabLight = 1;
int bEnableTabScenes = 1;
int bEnableTabTemp = 1;
int bEnableTabWeather = 1;
int bEnableTabUtility = 1;
int bEnableTabCustom = 1;
std::vector<std::vector<std::string> > result;
if ((UserID != 0) && (UserID != 10000))
{
result = m_sql.safe_query("SELECT TabsEnabled FROM Users WHERE (ID==%lu)",
UserID);
if (!result.empty())
{
int TabsEnabled = atoi(result[0][0].c_str());
bEnableTabLight = (TabsEnabled&(1 << 0));
bEnableTabScenes = (TabsEnabled&(1 << 1));
bEnableTabTemp = (TabsEnabled&(1 << 2));
bEnableTabWeather = (TabsEnabled&(1 << 3));
bEnableTabUtility = (TabsEnabled&(1 << 4));
bEnableTabCustom = (TabsEnabled&(1 << 5));
bEnableTabFloorplans = (TabsEnabled&(1 << 6));
}
}
else
{
m_sql.GetPreferencesVar("EnableTabFloorplans", bEnableTabFloorplans);
m_sql.GetPreferencesVar("EnableTabLights", bEnableTabLight);
m_sql.GetPreferencesVar("EnableTabScenes", bEnableTabScenes);
m_sql.GetPreferencesVar("EnableTabTemp", bEnableTabTemp);
m_sql.GetPreferencesVar("EnableTabWeather", bEnableTabWeather);
m_sql.GetPreferencesVar("EnableTabUtility", bEnableTabUtility);
m_sql.GetPreferencesVar("EnableTabCustom", bEnableTabCustom);
}
if (iDashboardType == 3)
{
//Floorplan , no need to show a tab floorplan
bEnableTabFloorplans = 0;
}
root["result"]["EnableTabProxy"] = bEnableTabProxy;
root["result"]["EnableTabDashboard"] = bEnableTabDashboard != 0;
root["result"]["EnableTabFloorplans"] = bEnableTabFloorplans != 0;
root["result"]["EnableTabLights"] = bEnableTabLight != 0;
root["result"]["EnableTabScenes"] = bEnableTabScenes != 0;
root["result"]["EnableTabTemp"] = bEnableTabTemp != 0;
root["result"]["EnableTabWeather"] = bEnableTabWeather != 0;
root["result"]["EnableTabUtility"] = bEnableTabUtility != 0;
root["result"]["EnableTabCustom"] = bEnableTabCustom != 0;
if (bEnableTabCustom)
{
//Add custom templates
DIR *lDir;
struct dirent *ent;
std::string templatesFolder = szWWWFolder + "/templates";
int iFile = 0;
if ((lDir = opendir(templatesFolder.c_str())) != NULL)
{
while ((ent = readdir(lDir)) != NULL)
{
std::string filename = ent->d_name;
size_t pos = filename.find(".htm");
if (pos != std::string::npos)
{
std::string shortfile = filename.substr(0, pos);
root["result"]["templates"][iFile++] = shortfile;
}
}
closedir(lDir);
}
}
}
void CWebServer::Cmd_SendNotification(WebEmSession & session, const request& req, Json::Value &root)
{
std::string subject = request::findValue(&req, "subject");
std::string body = request::findValue(&req, "body");
std::string subsystem = request::findValue(&req, "subsystem");
if (
(subject.empty()) ||
(body.empty())
)
return;
if (subsystem.empty()) subsystem = NOTIFYALL;
//Add to queue
if (m_notifications.SendMessage(0, std::string(""), subsystem, subject, body, std::string(""), 1, std::string(""), false)) {
root["status"] = "OK";
}
root["title"] = "SendNotification";
}
void CWebServer::Cmd_EmailCameraSnapshot(WebEmSession & session, const request& req, Json::Value &root)
{
std::string camidx = request::findValue(&req, "camidx");
std::string subject = request::findValue(&req, "subject");
if (
(camidx.empty()) ||
(subject.empty())
)
return;
//Add to queue
m_sql.AddTaskItem(_tTaskItem::EmailCameraSnapshot(1, camidx, subject));
root["status"] = "OK";
root["title"] = "Email Camera Snapshot";
}
void CWebServer::Cmd_UpdateDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights < 1)
{
session.reply_status = reply::forbidden;
return; //only user or higher allowed
}
std::string idx = request::findValue(&req, "idx");
if (!IsIdxForUser(&session, atoi(idx.c_str())))
{
_log.Log(LOG_ERROR, "User: %s tried to update an Unauthorized device!", session.username.c_str());
session.reply_status = reply::forbidden;
return;
}
std::string hid = request::findValue(&req, "hid");
std::string did = request::findValue(&req, "did");
std::string dunit = request::findValue(&req, "dunit");
std::string dtype = request::findValue(&req, "dtype");
std::string dsubtype = request::findValue(&req, "dsubtype");
std::string nvalue = request::findValue(&req, "nvalue");
std::string svalue = request::findValue(&req, "svalue");
if ((nvalue.empty() && svalue.empty()))
{
return;
}
int signallevel = 12;
int batterylevel = 255;
if (idx.empty())
{
//No index supplied, check if raw parameters where supplied
if (
(hid.empty()) ||
(did.empty()) ||
(dunit.empty()) ||
(dtype.empty()) ||
(dsubtype.empty())
)
return;
}
else
{
//Get the raw device parameters
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType FROM DeviceStatus WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
hid = result[0][0];
did = result[0][1];
dunit = result[0][2];
dtype = result[0][3];
dsubtype = result[0][4];
}
int HardwareID = atoi(hid.c_str());
std::string DeviceID = did;
int unit = atoi(dunit.c_str());
int devType = atoi(dtype.c_str());
int subType = atoi(dsubtype.c_str());
uint64_t ulIdx = std::strtoull(idx.c_str(), nullptr, 10);
int invalue = atoi(nvalue.c_str());
std::string sSignalLevel = request::findValue(&req, "rssi");
if (sSignalLevel != "")
{
signallevel = atoi(sSignalLevel.c_str());
}
std::string sBatteryLevel = request::findValue(&req, "battery");
if (sBatteryLevel != "")
{
batterylevel = atoi(sBatteryLevel.c_str());
}
if (m_mainworker.UpdateDevice(HardwareID, DeviceID, unit, devType, subType, invalue, svalue, signallevel, batterylevel))
{
root["status"] = "OK";
root["title"] = "Update Device";
}
}
void CWebServer::Cmd_UpdateDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string script = request::findValue(&req, "script");
if (script.empty())
{
return;
}
std::string content = req.content;
std::vector<std::string> allParameters;
// Keep the url content on the right of the '?'
std::vector<std::string> allParts;
StringSplit(req.uri, "?", allParts);
if (!allParts.empty())
{
// Split all url parts separated by a '&'
StringSplit(allParts[1], "&", allParameters);
}
CLuaHandler luaScript;
bool ret = luaScript.executeLuaScript(script, content, allParameters);
if (ret)
{
root["status"] = "OK";
root["title"] = "Update Device";
}
}
void CWebServer::Cmd_SetThermostatState(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sstate = request::findValue(&req, "state");
std::string idx = request::findValue(&req, "idx");
std::string name = request::findValue(&req, "name");
if (
(idx.empty()) ||
(sstate.empty())
)
return;
int iState = atoi(sstate.c_str());
int urights = 3;
bool bHaveUser = (session.username != "");
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a Thermostat State change command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
root["status"] = "OK";
root["title"] = "Set Thermostat State";
_log.Log(LOG_NORM, "Setting Thermostat State....");
m_mainworker.SetThermostatState(idx, iState);
}
void CWebServer::Cmd_SystemShutdown(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
#ifdef WIN32
int ret = system("shutdown -s -f -t 1 -d up:125:1");
#else
int ret = system("sudo shutdown -h now");
#endif
if (ret != 0)
{
_log.Log(LOG_ERROR, "Error executing shutdown command. returned: %d", ret);
return;
}
root["title"] = "SystemShutdown";
root["status"] = "OK";
}
void CWebServer::Cmd_SystemReboot(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
#ifdef WIN32
int ret = system("shutdown -r -f -t 1 -d up:125:1");
#else
int ret = system("sudo shutdown -r now");
#endif
if (ret != 0)
{
_log.Log(LOG_ERROR, "Error executing reboot command. returned: %d", ret);
return;
}
root["title"] = "SystemReboot";
root["status"] = "OK";
}
void CWebServer::Cmd_ExcecuteScript(WebEmSession & session, const request& req, Json::Value &root)
{
std::string scriptname = request::findValue(&req, "scriptname");
if (scriptname.empty())
return;
if (scriptname.find("..") != std::string::npos)
return;
#ifdef WIN32
scriptname = szUserDataFolder + "scripts\\" + scriptname;
#else
scriptname = szUserDataFolder + "scripts/" + scriptname;
#endif
if (!file_exist(scriptname.c_str()))
return;
std::string script_params = request::findValue(&req, "scriptparams");
std::string strparm = szUserDataFolder;
if (!script_params.empty())
{
if (strparm.size() > 0)
strparm += " " + script_params;
else
strparm = script_params;
}
std::string sdirect = request::findValue(&req, "direct");
if (sdirect == "true")
{
_log.Log(LOG_STATUS, "Executing script: %s", scriptname.c_str());
#ifdef WIN32
ShellExecute(NULL, "open", scriptname.c_str(), strparm.c_str(), NULL, SW_SHOWNORMAL);
#else
std::string lscript = scriptname + " " + strparm;
int ret = system(lscript.c_str());
if (ret != 0)
{
_log.Log(LOG_ERROR, "Error executing script command (%s). returned: %d", lscript.c_str(), ret);
return;
}
#endif
}
else
{
//add script to background worker
m_sql.AddTaskItem(_tTaskItem::ExecuteScript(0.2f, scriptname, strparm));
}
root["title"] = "ExecuteScript";
root["status"] = "OK";
}
void CWebServer::Cmd_GetCosts(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
char szTmp[100];
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type, SubType, nValue, sValue FROM DeviceStatus WHERE (ID=='%q')",
idx.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
int nValue = 0;
root["status"] = "OK";
root["title"] = "GetElectraCosts";
m_sql.GetPreferencesVar("CostEnergy", nValue);
root["CostEnergy"] = nValue;
m_sql.GetPreferencesVar("CostEnergyT2", nValue);
root["CostEnergyT2"] = nValue;
m_sql.GetPreferencesVar("CostEnergyR1", nValue);
root["CostEnergyR1"] = nValue;
m_sql.GetPreferencesVar("CostEnergyR2", nValue);
root["CostEnergyR2"] = nValue;
m_sql.GetPreferencesVar("CostGas", nValue);
root["CostGas"] = nValue;
m_sql.GetPreferencesVar("CostWater", nValue);
root["CostWater"] = nValue;
int tValue = 1000;
if (m_sql.GetPreferencesVar("MeterDividerWater", tValue))
{
root["DividerWater"] = float(tValue);
}
unsigned char dType = atoi(sd[0].c_str());
//unsigned char subType = atoi(sd[1].c_str());
//nValue = (unsigned char)atoi(sd[2].c_str());
std::string sValue = sd[3];
if (dType == pTypeP1Power)
{
//also provide the counter values
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() != 6)
return;
float EnergyDivider = 1000.0f;
if (m_sql.GetPreferencesVar("MeterDividerEnergy", tValue))
{
EnergyDivider = float(tValue);
}
unsigned long long powerusage1 = std::strtoull(splitresults[0].c_str(), nullptr, 10);
unsigned long long powerusage2 = std::strtoull(splitresults[1].c_str(), nullptr, 10);
unsigned long long powerdeliv1 = std::strtoull(splitresults[2].c_str(), nullptr, 10);
unsigned long long powerdeliv2 = std::strtoull(splitresults[3].c_str(), nullptr, 10);
unsigned long long usagecurrent = std::strtoull(splitresults[4].c_str(), nullptr, 10);
unsigned long long delivcurrent = std::strtoull(splitresults[5].c_str(), nullptr, 10);
powerdeliv1 = (powerdeliv1 < 10) ? 0 : powerdeliv1;
powerdeliv2 = (powerdeliv2 < 10) ? 0 : powerdeliv2;
sprintf(szTmp, "%.03f", float(powerusage1) / EnergyDivider);
root["CounterT1"] = szTmp;
sprintf(szTmp, "%.03f", float(powerusage2) / EnergyDivider);
root["CounterT2"] = szTmp;
sprintf(szTmp, "%.03f", float(powerdeliv1) / EnergyDivider);
root["CounterR1"] = szTmp;
sprintf(szTmp, "%.03f", float(powerdeliv2) / EnergyDivider);
root["CounterR2"] = szTmp;
}
}
}
void CWebServer::Cmd_CheckForUpdate(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
urights = static_cast<int>(m_users[iUser].userrights);
}
root["statuscode"] = urights;
root["status"] = "OK";
root["title"] = "CheckForUpdate";
root["HaveUpdate"] = false;
root["Revision"] = m_mainworker.m_iRevision;
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin users may update
}
bool bIsForced = (request::findValue(&req, "forced") == "true");
if (!bIsForced)
{
int nValue = 0;
m_sql.GetPreferencesVar("UseAutoUpdate", nValue);
if (nValue != 1)
{
return;
}
}
root["HaveUpdate"] = m_mainworker.IsUpdateAvailable(bIsForced);
root["DomoticzUpdateURL"] = m_mainworker.m_szDomoticzUpdateURL;
root["SystemName"] = m_mainworker.m_szSystemName;
root["Revision"] = m_mainworker.m_iRevision;
}
void CWebServer::Cmd_DownloadUpdate(WebEmSession & session, const request& req, Json::Value &root)
{
if (!m_mainworker.StartDownloadUpdate())
return;
root["status"] = "OK";
root["title"] = "DownloadUpdate";
}
void CWebServer::Cmd_DownloadReady(WebEmSession & session, const request& req, Json::Value &root)
{
if (!m_mainworker.m_bHaveDownloadedDomoticzUpdate)
return;
root["status"] = "OK";
root["title"] = "DownloadReady";
root["downloadok"] = (m_mainworker.m_bHaveDownloadedDomoticzUpdateSuccessFull) ? true : false;
}
void CWebServer::Cmd_DeleteDatePoint(WebEmSession & session, const request& req, Json::Value &root)
{
const std::string idx = request::findValue(&req, "idx");
const std::string Date = request::findValue(&req, "date");
if (
(idx.empty()) ||
(Date.empty())
)
return;
root["status"] = "OK";
root["title"] = "deletedatapoint";
m_sql.DeleteDataPoint(idx.c_str(), Date);
}
bool CWebServer::IsIdxForUser(const WebEmSession *pSession, const int Idx)
{
if (pSession->rights == 2)
return true;
if (pSession->rights == 0)
return false; //viewer
//User
int iUser = FindUser(pSession->username.c_str());
if ((iUser < 0) || (iUser >= (int)m_users.size()))
return false;
if (m_users[iUser].TotSensors == 0)
return true; // all sensors
std::vector<std::vector<std::string> > result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == '%d') AND (DeviceRowID == '%d')", m_users[iUser].ID, Idx);
return (!result.empty());
}
void CWebServer::HandleCommand(const std::string &cparam, WebEmSession & session, const request& req, Json::Value &root)
{
std::map < std::string, webserver_response_function >::iterator pf = m_webcommands.find(cparam);
if (pf != m_webcommands.end())
{
pf->second(session, req, root);
return;
}
std::vector<std::vector<std::string> > result;
char szTmp[300];
bool bHaveUser = (session.username != "");
int iUser = -1;
if (bHaveUser)
{
iUser = FindUser(session.username.c_str());
}
if (cparam == "deleteallsubdevices")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllSubDevices";
result = m_sql.safe_query("DELETE FROM LightSubDevices WHERE (ParentID == '%q')", idx.c_str());
}
else if (cparam == "deletesubdevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteSubDevice";
result = m_sql.safe_query("DELETE FROM LightSubDevices WHERE (ID == '%q')", idx.c_str());
}
else if (cparam == "addsubdevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string subidx = request::findValue(&req, "subidx");
if ((idx.empty()) || (subidx.empty()))
return;
if (idx == subidx)
return;
//first check if it is not already a sub device
result = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q') AND (ParentID =='%q')",
subidx.c_str(), idx.c_str());
if (result.empty())
{
root["status"] = "OK";
root["title"] = "AddSubDevice";
//no it is not, add it
result = m_sql.safe_query(
"INSERT INTO LightSubDevices (DeviceRowID, ParentID) VALUES ('%q','%q')",
subidx.c_str(),
idx.c_str()
);
}
}
else if (cparam == "addscenedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string devidx = request::findValue(&req, "devidx");
std::string isscene = request::findValue(&req, "isscene");
std::string scommand = request::findValue(&req, "command");
int ondelay = atoi(request::findValue(&req, "ondelay").c_str());
int offdelay = atoi(request::findValue(&req, "offdelay").c_str());
if (
(idx.empty()) ||
(devidx.empty()) ||
(isscene.empty())
)
return;
int level = -1;
if (request::hasValue(&req, "level"))
level = atoi(request::findValue(&req, "level").c_str());
std::string color = _tColor(request::findValue(&req, "color")).toJSONString(); //Parse the color to detect incorrectly formatted color data
unsigned char command = 0;
result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType, SwitchType, Options FROM DeviceStatus WHERE (ID=='%q')",
devidx.c_str());
if (!result.empty())
{
int dType = atoi(result[0][3].c_str());
int sType = atoi(result[0][4].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(result[0][5].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(result[0][6].c_str());
GetLightCommand(dType, sType, switchtype, scommand, command, options);
}
//first check if this device is not the scene code!
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID=='%q')", idx.c_str());
if (!result.empty())
{
int SceneType = atoi(result[0][1].c_str());
std::vector<std::string> arrayActivators;
StringSplit(result[0][0], ";", arrayActivators);
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
std::string sCode = "";
if (arrayCode.size() == 2)
{
sCode = arrayCode[1];
}
if (sID == devidx)
{
return; //Group does not work with separate codes, so already there
}
}
}
//first check if it is not already a part of this scene/group (with the same OnDelay)
if (isscene == "true") {
result = m_sql.safe_query("SELECT ID FROM SceneDevices WHERE (DeviceRowID=='%q') AND (SceneRowID =='%q') AND (OnDelay == %d) AND (OffDelay == %d) AND (Cmd == %d)",
devidx.c_str(), idx.c_str(), ondelay, offdelay, command);
}
else {
result = m_sql.safe_query("SELECT ID FROM SceneDevices WHERE (DeviceRowID=='%q') AND (SceneRowID =='%q') AND (OnDelay == %d)",
devidx.c_str(), idx.c_str(), ondelay);
}
if (result.empty())
{
root["status"] = "OK";
root["title"] = "AddSceneDevice";
//no it is not, add it
if (isscene == "true")
{
m_sql.safe_query(
"INSERT INTO SceneDevices (DeviceRowID, SceneRowID, Cmd, Level, Color, OnDelay, OffDelay) VALUES ('%q','%q',%d,%d,'%q',%d,%d)",
devidx.c_str(),
idx.c_str(),
command,
level,
color.c_str(),
ondelay,
offdelay
);
}
else
{
m_sql.safe_query(
"INSERT INTO SceneDevices (DeviceRowID, SceneRowID, Level, Color, OnDelay, OffDelay) VALUES ('%q','%q',%d,'%q',%d,%d)",
devidx.c_str(),
idx.c_str(),
level,
color.c_str(),
ondelay,
offdelay
);
}
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentScenesGroups();
}
}
else if (cparam == "updatescenedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string devidx = request::findValue(&req, "devidx");
std::string scommand = request::findValue(&req, "command");
int ondelay = atoi(request::findValue(&req, "ondelay").c_str());
int offdelay = atoi(request::findValue(&req, "offdelay").c_str());
if (
(idx.empty()) ||
(devidx.empty())
)
return;
unsigned char command = 0;
result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType, SwitchType, Options FROM DeviceStatus WHERE (ID=='%q')",
devidx.c_str());
if (!result.empty())
{
int dType = atoi(result[0][3].c_str());
int sType = atoi(result[0][4].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(result[0][5].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(result[0][6].c_str());
GetLightCommand(dType, sType, switchtype, scommand, command, options);
}
int level = -1;
if (request::hasValue(&req, "level"))
level = atoi(request::findValue(&req, "level").c_str());
std::string color = _tColor(request::findValue(&req, "color")).toJSONString(); //Parse the color to detect incorrectly formatted color data
root["status"] = "OK";
root["title"] = "UpdateSceneDevice";
result = m_sql.safe_query(
"UPDATE SceneDevices SET Cmd=%d, Level=%d, Color='%q', OnDelay=%d, OffDelay=%d WHERE (ID == '%q')",
command, level, color.c_str(), ondelay, offdelay, idx.c_str());
}
else if (cparam == "deletescenedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteSceneDevice";
m_sql.safe_query("DELETE FROM SceneDevices WHERE (ID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM CamerasActiveDevices WHERE (DevSceneType==1) AND (DevSceneRowID == '%q')", idx.c_str());
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentScenesGroups();
}
else if (cparam == "getsubdevices")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetSubDevices";
result = m_sql.safe_query("SELECT a.ID, b.Name FROM LightSubDevices a, DeviceStatus b WHERE (a.ParentID=='%q') AND (b.ID == a.DeviceRowID)",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["ID"] = sd[0];
root["result"][ii]["Name"] = sd[1];
ii++;
}
}
}
else if (cparam == "getscenedevices")
{
std::string idx = request::findValue(&req, "idx");
std::string isscene = request::findValue(&req, "isscene");
if (
(idx.empty()) ||
(isscene.empty())
)
return;
root["status"] = "OK";
root["title"] = "GetSceneDevices";
result = m_sql.safe_query("SELECT a.ID, b.Name, a.DeviceRowID, b.Type, b.SubType, b.nValue, b.sValue, a.Cmd, a.Level, b.ID, a.[Order], a.Color, a.OnDelay, a.OffDelay, b.SwitchType FROM SceneDevices a, DeviceStatus b WHERE (a.SceneRowID=='%q') AND (b.ID == a.DeviceRowID) ORDER BY a.[Order]",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["ID"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["DevID"] = sd[2];
root["result"][ii]["DevRealIdx"] = sd[9];
root["result"][ii]["Order"] = atoi(sd[10].c_str());
root["result"][ii]["OnDelay"] = atoi(sd[12].c_str());
root["result"][ii]["OffDelay"] = atoi(sd[13].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(sd[14].c_str());
unsigned char devType = atoi(sd[3].c_str());
//switchtype seemed not to be used down with the GetLightStatus command,
//causing RFY to go wrong, fixing here
if (devType != pTypeRFY)
switchtype = STYPE_OnOff;
unsigned char subType = atoi(sd[4].c_str());
unsigned char nValue = (unsigned char)atoi(sd[5].c_str());
std::string sValue = sd[6];
int command = atoi(sd[7].c_str());
int level = atoi(sd[8].c_str());
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(devType, subType, switchtype, command, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Command"] = lstatus;
root["result"][ii]["Level"] = level;
root["result"][ii]["Color"] = _tColor(sd[11]).toJSONString();
root["result"][ii]["Type"] = RFX_Type_Desc(devType, 1);
root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(devType, subType);
ii++;
}
}
}
else if (cparam == "changescenedeviceorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string sway = request::findValue(&req, "way");
if (sway.empty())
return;
bool bGoUp = (sway == "0");
std::string aScene, aOrder, oID, oOrder;
//Get actual device order
result = m_sql.safe_query("SELECT SceneRowID, [Order] FROM SceneDevices WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
aScene = result[0][0];
aOrder = result[0][1];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM SceneDevices WHERE (SceneRowID=='%q' AND [Order]>'%q') ORDER BY [Order] ASC",
aScene.c_str(), aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM SceneDevices WHERE (SceneRowID=='%q' AND [Order]<'%q') ORDER BY [Order] DESC",
aScene.c_str(), aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangeSceneDeviceOrder";
result = m_sql.safe_query("UPDATE SceneDevices SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
result = m_sql.safe_query("UPDATE SceneDevices SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
else if (cparam == "deleteallscenedevices")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllSceneDevices";
result = m_sql.safe_query("DELETE FROM SceneDevices WHERE (SceneRowID == %q)", idx.c_str());
}
else if (cparam == "getmanualhardware")
{
//used by Add Manual Light/Switch dialog
root["status"] = "OK";
root["title"] = "GetHardware";
result = m_sql.safe_query("SELECT ID, Name, Type FROM Hardware ORDER BY ID ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int ID = atoi(sd[0].c_str());
std::string Name = sd[1];
_eHardwareTypes Type = (_eHardwareTypes)atoi(sd[2].c_str());
if (
(Type == HTYPE_RFXLAN) ||
(Type == HTYPE_RFXtrx315) ||
(Type == HTYPE_RFXtrx433) ||
(Type == HTYPE_RFXtrx868) ||
(Type == HTYPE_EnOceanESP2) ||
(Type == HTYPE_EnOceanESP3) ||
(Type == HTYPE_Dummy) ||
(Type == HTYPE_Tellstick) ||
(Type == HTYPE_EVOHOME_SCRIPT) ||
(Type == HTYPE_EVOHOME_SERIAL) ||
(Type == HTYPE_EVOHOME_WEB) ||
(Type == HTYPE_EVOHOME_TCP) ||
(Type == HTYPE_RaspberryGPIO) ||
(Type == HTYPE_RFLINKUSB) ||
(Type == HTYPE_RFLINKTCP) ||
(Type == HTYPE_ZIBLUEUSB) ||
(Type == HTYPE_ZIBLUETCP) ||
(Type == HTYPE_OpenWebNetTCP) ||
(Type == HTYPE_OpenWebNetUSB) ||
(Type == HTYPE_SysfsGpio) ||
(Type == HTYPE_USBtinGateway)
)
{
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
}
else if (cparam == "getgpio")
{
//used by Add Manual Light/Switch dialog
root["title"] = "GetGpio";
#ifdef WITH_GPIO
std::vector<CGpioPin> pins = CGpio::GetPinList();
if (pins.size() == 0) {
root["status"] = "ERROR";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "GPIO INIT ERROR";
}
else {
int ii = 0;
for (const auto & it : pins)
{
CGpioPin pin = it;
root["status"] = "OK";
root["result"][ii]["idx"] = pin.GetPin();
root["result"][ii]["Name"] = pin.ToString();
ii++;
}
}
#else
root["status"] = "OK";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "N/A";
#endif
}
else if (cparam == "getsysfsgpio")
{
//used by Add Manual Light/Switch dialog
root["title"] = "GetSysfsGpio";
#ifdef WITH_GPIO
std::vector<int> gpio_ids = CSysfsGpio::GetGpioIds();
std::vector<std::string> gpio_names = CSysfsGpio::GetGpioNames();
if (gpio_ids.size() == 0) {
root["status"] = "ERROR";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "No sysfs-gpio exports";
}
else {
for (int ii = 0; ii < gpio_ids.size(); ii++)
{
root["status"] = "OK";
root["result"][ii]["idx"] = gpio_ids[ii];
root["result"][ii]["Name"] = gpio_names[ii];
}
}
#else
root["status"] = "OK";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "N/A";
#endif
}
else if (cparam == "getlightswitches")
{
root["status"] = "OK";
root["title"] = "GetLightSwitches";
result = m_sql.safe_query("SELECT ID, Name, Type, SubType, Used, SwitchType, Options FROM DeviceStatus ORDER BY Name");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
std::string Name = sd[1];
int Type = atoi(sd[2].c_str());
int SubType = atoi(sd[3].c_str());
int used = atoi(sd[4].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(sd[5].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sd[6]);
bool bdoAdd = false;
switch (Type)
{
case pTypeLighting1:
case pTypeLighting2:
case pTypeLighting3:
case pTypeLighting4:
case pTypeLighting5:
case pTypeLighting6:
case pTypeFan:
case pTypeColorSwitch:
case pTypeSecurity1:
case pTypeSecurity2:
case pTypeEvohome:
case pTypeEvohomeRelay:
case pTypeCurtain:
case pTypeBlinds:
case pTypeRFY:
case pTypeChime:
case pTypeThermostat2:
case pTypeThermostat3:
case pTypeThermostat4:
case pTypeRemote:
case pTypeRadiator1:
case pTypeGeneralSwitch:
case pTypeHomeConfort:
case pTypeFS20:
bdoAdd = true;
if (!used)
{
bdoAdd = false;
bool bIsSubDevice = false;
std::vector<std::vector<std::string> > resultSD;
resultSD = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q')",
sd[0].c_str());
if (resultSD.size() > 0)
bdoAdd = true;
}
if ((Type == pTypeRadiator1) && (SubType != sTypeSmartwaresSwitchRadiator))
bdoAdd = false;
if (bdoAdd)
{
int idx = atoi(ID.c_str());
if (!IsIdxForUser(&session, idx))
continue;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = Name;
root["result"][ii]["Type"] = RFX_Type_Desc(Type, 1);
root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(Type, SubType);
bool bIsDimmer = (
(switchtype == STYPE_Dimmer) ||
(switchtype == STYPE_BlindsPercentage) ||
(switchtype == STYPE_BlindsPercentageInverted) ||
(switchtype == STYPE_Selector)
);
root["result"][ii]["IsDimmer"] = bIsDimmer;
std::string dimmerLevels = "none";
if (bIsDimmer)
{
std::stringstream ss;
if (switchtype == STYPE_Selector) {
std::map<std::string, std::string> selectorStatuses;
GetSelectorSwitchStatuses(options, selectorStatuses);
bool levelOffHidden = (options["LevelOffHidden"] == "true");
for (int i = 0; i < (int)selectorStatuses.size(); i++) {
if (levelOffHidden && (i == 0)) {
continue;
}
if ((levelOffHidden && (i > 1)) || (i > 0)) {
ss << ",";
}
ss << i * 10;
}
}
else
{
int nValue = 0;
std::string sValue = "";
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
int maxDimLevel = 0;
bool bHaveGroupCmd = false;
GetLightStatus(Type, SubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
for (int i = 0; i <= maxDimLevel; i++)
{
if (i != 0)
{
ss << ",";
}
ss << (int)float((100.0f / float(maxDimLevel))*i);
}
}
dimmerLevels = ss.str();
}
root["result"][ii]["DimmerLevels"] = dimmerLevels;
ii++;
}
break;
}
}
}
}
else if (cparam == "getlightswitchesscenes")
{
root["status"] = "OK";
root["title"] = "GetLightSwitchesScenes";
int ii = 0;
//First List/Switch Devices
result = m_sql.safe_query("SELECT ID, Name, Type, SubType, Used FROM DeviceStatus ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
std::string Name = sd[1];
int Type = atoi(sd[2].c_str());
int SubType = atoi(sd[3].c_str());
int used = atoi(sd[4].c_str());
if (used)
{
switch (Type)
{
case pTypeLighting1:
case pTypeLighting2:
case pTypeLighting3:
case pTypeLighting4:
case pTypeLighting5:
case pTypeLighting6:
case pTypeFan:
case pTypeColorSwitch:
case pTypeSecurity1:
case pTypeSecurity2:
case pTypeEvohome:
case pTypeEvohomeRelay:
case pTypeCurtain:
case pTypeBlinds:
case pTypeRFY:
case pTypeChime:
case pTypeThermostat2:
case pTypeThermostat3:
case pTypeThermostat4:
case pTypeRemote:
case pTypeGeneralSwitch:
case pTypeHomeConfort:
case pTypeFS20:
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = "[Light/Switch] " + Name;
ii++;
break;
case pTypeRadiator1:
if (SubType == sTypeSmartwaresSwitchRadiator)
{
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = "[Light/Switch] " + Name;
ii++;
}
break;
}
}
}
}//end light/switches
//Add Scenes
result = m_sql.safe_query("SELECT ID, Name FROM Scenes ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
std::string Name = sd[1];
root["result"][ii]["type"] = 1;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = "[Scene] " + Name;
ii++;
}
}//end light/switches
}
else if (cparam == "getcamactivedevices")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetCameraActiveDevices";
//First List/Switch Devices
result = m_sql.safe_query("SELECT ID, DevSceneType, DevSceneRowID, DevSceneWhen, DevSceneDelay FROM CamerasActiveDevices WHERE (CameraRowID=='%q') ORDER BY ID",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
int DevSceneType = atoi(sd[1].c_str());
std::string DevSceneRowID = sd[2];
int DevSceneWhen = atoi(sd[3].c_str());
int DevSceneDelay = atoi(sd[4].c_str());
std::string Name = "";
if (DevSceneType == 0)
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM DeviceStatus WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = "[Light/Switches] " + result2[0][0];
}
}
else
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM Scenes WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = "[Scene] " + result2[0][0];
}
}
if (Name != "")
{
root["result"][ii]["idx"] = ID;
root["result"][ii]["type"] = DevSceneType;
root["result"][ii]["DevSceneRowID"] = DevSceneRowID;
root["result"][ii]["when"] = DevSceneWhen;
root["result"][ii]["delay"] = DevSceneDelay;
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
}
else if (cparam == "addcamactivedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string activeidx = request::findValue(&req, "activeidx");
std::string sactivetype = request::findValue(&req, "activetype");
std::string sactivewhen = request::findValue(&req, "activewhen");
std::string sactivedelay = request::findValue(&req, "activedelay");
if (
(idx.empty()) ||
(activeidx.empty()) ||
(sactivetype.empty()) ||
(sactivewhen.empty()) ||
(sactivedelay.empty())
)
{
return;
}
int activetype = atoi(sactivetype.c_str());
int activewhen = atoi(sactivewhen.c_str());
int activedelay = atoi(sactivedelay.c_str());
//first check if it is not already a Active Device
result = m_sql.safe_query(
"SELECT ID FROM CamerasActiveDevices WHERE (CameraRowID=='%q')"
" AND (DevSceneType==%d) AND (DevSceneRowID=='%q')"
" AND (DevSceneWhen==%d)",
idx.c_str(), activetype, activeidx.c_str(), activewhen);
if (result.empty())
{
root["status"] = "OK";
root["title"] = "AddCameraActiveDevice";
//no it is not, add it
result = m_sql.safe_query(
"INSERT INTO CamerasActiveDevices (CameraRowID, DevSceneType, DevSceneRowID, DevSceneWhen, DevSceneDelay) VALUES ('%q',%d,'%q',%d,%d)",
idx.c_str(),
activetype,
activeidx.c_str(),
activewhen,
activedelay
);
m_mainworker.m_cameras.ReloadCameras();
}
}
else if (cparam == "deleteamactivedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteCameraActiveDevice";
result = m_sql.safe_query("DELETE FROM CamerasActiveDevices WHERE (ID == '%q')", idx.c_str());
m_mainworker.m_cameras.ReloadCameras();
}
else if (cparam == "deleteallactivecamdevices")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllCameraActiveDevices";
result = m_sql.safe_query("DELETE FROM CamerasActiveDevices WHERE (CameraRowID == '%q')", idx.c_str());
m_mainworker.m_cameras.ReloadCameras();
}
else if (cparam == "testnotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string notification_Title = "Domoticz test";
std::string notification_Message = "Domoticz test message!";
std::string subsystem = request::findValue(&req, "subsystem");
std::string extraData = request::findValue(&req, "extradata");
m_notifications.ConfigFromGetvars(req, false);
if (m_notifications.SendMessage(0, std::string(""), subsystem, notification_Title, notification_Message, extraData, 1, std::string(""), false)) {
root["status"] = "OK";
}
/* we need to reload the config, because the values that were set were only for testing */
m_notifications.LoadConfig();
}
else if (cparam == "testswitch")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string hwdid = request::findValue(&req, "hwdid");
std::string sswitchtype = request::findValue(&req, "switchtype");
std::string slighttype = request::findValue(&req, "lighttype");
if (
(hwdid.empty()) ||
(sswitchtype.empty()) ||
(slighttype.empty())
)
return;
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
int lighttype = atoi(slighttype.c_str());
int dtype;
int subtype = 0;
std::string sunitcode;
std::string devid;
if (lighttype == 70)
{
//EnOcean (Lighting2 with Base_ID offset)
dtype = pTypeLighting2;
subtype = sTypeAC;
std::string sgroupcode = request::findValue(&req, "groupcode");
sunitcode = request::findValue(&req, "unitcode");
int iUnitTest = atoi(sunitcode.c_str()); //only First Rocker_ID at the moment, gives us 128 devices we can control, should be enough!
if (
(sunitcode.empty()) ||
(sgroupcode.empty()) ||
((iUnitTest < 1) || (iUnitTest > 128))
)
return;
sunitcode = sgroupcode;//Button A or B
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pBaseHardware == NULL)
return;
if ((pBaseHardware->HwdType != HTYPE_EnOceanESP2) && (pBaseHardware->HwdType != HTYPE_EnOceanESP3)
&& (pBaseHardware->HwdType != HTYPE_USBtinGateway) )
return;
unsigned long rID = 0;
if (pBaseHardware->HwdType == HTYPE_EnOceanESP2)
{
CEnOceanESP2 *pEnoceanHardware = reinterpret_cast<CEnOceanESP2 *>(pBaseHardware);
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_EnOceanESP3)
{
CEnOceanESP3 *pEnoceanHardware = reinterpret_cast<CEnOceanESP3 *>(pBaseHardware);
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_USBtinGateway) //Like EnOcean (Lighting2 with Base_ID offset)
{
USBtin *pUSBtinHardware = reinterpret_cast<USBtin *>(pBaseHardware);
//base ID calculate in the USBtinharwade dependant of the CAN Layer !
//for exemple see MultiblocV8 layer...
rID = pUSBtinHardware->switch_id_base;
std::stringstream ssunitcode;
ssunitcode << iUnitTest;
sunitcode = ssunitcode.str();
}
//convert to hex, and we have our ID
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << rID;
devid = s_strid.str();
}
else if (lighttype == 68)
{
#ifdef WITH_GPIO
dtype = pTypeLighting1;
subtype = sTypeIMPULS;
devid = "0";
sunitcode = request::findValue(&req, "unitcode"); //Unit code = GPIO number
if (sunitcode.empty()) {
root["status"] = "ERROR";
root["message"] = "No GPIO number given";
return;
}
CGpio *pGpio = reinterpret_cast<CGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pGpio == NULL) {
root["status"] = "ERROR";
root["message"] = "Could not retrieve GPIO hardware pointer";
return;
}
if (pGpio->HwdType != HTYPE_RaspberryGPIO) {
root["status"] = "ERROR";
root["message"] = "Given hardware is not GPIO";
return;
}
CGpioPin *pPin = CGpio::GetPPinById(atoi(sunitcode.c_str()));
if (pPin == NULL) {
root["status"] = "ERROR";
root["message"] = "Given pin does not exist on this GPIO hardware";
return;
}
if (pPin->GetIsInput()) {
root["status"] = "ERROR";
root["message"] = "Given pin is not configured for output";
return;
}
#else
root["status"] = "ERROR";
root["message"] = "GPIO support is disabled";
return;
#endif
}
else if (lighttype == 69)
{
#ifdef WITH_GPIO
sunitcode = request::findValue(&req, "unitcode"); // sysfs-gpio number
int unitcode = atoi(sunitcode.c_str());
dtype = pTypeLighting2;
subtype = sTypeAC;
std::string sswitchtype = request::findValue(&req, "switchtype");
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
std::string id = request::findValue(&req, "id");
if ((id.empty()) || (sunitcode.empty()))
{
return;
}
devid = id;
if (sunitcode.empty())
{
root["status"] = "ERROR";
root["message"] = "No GPIO number given";
return;
}
CSysfsGpio *pSysfsGpio = reinterpret_cast<CSysfsGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pSysfsGpio == NULL) {
root["status"] = "ERROR";
root["message"] = "Could not retrieve SysfsGpio hardware pointer";
return;
}
if (pSysfsGpio->HwdType != HTYPE_SysfsGpio) {
root["status"] = "ERROR";
root["message"] = "Given hardware is not SysfsGpio";
return;
}
#else
root["status"] = "ERROR";
root["message"] = "GPIO support is disabled";
return;
#endif
}
else if (lighttype < 20)
{
dtype = pTypeLighting1;
subtype = lighttype;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype < 30)
{
dtype = pTypeLighting2;
subtype = lighttype - 20;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype < 70)
{
dtype = pTypeLighting5;
subtype = lighttype - 50;
if (lighttype == 59)
subtype = sTypeIT;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
if ((subtype != sTypeEMW100) && (subtype != sTypeLivolo) && (subtype != sTypeLivolo1to10) && (subtype != sTypeRGB432W) && (subtype != sTypeIT))
devid = "00" + id;
else
devid = id;
}
else
{
if (lighttype == 100)
{
//Chime/ByronSX
dtype = pTypeChime;
subtype = sTypeByronSX;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str()) - 1;
switch (iUnitCode)
{
case 0:
iUnitCode = chime_sound0;
break;
case 1:
iUnitCode = chime_sound1;
break;
case 2:
iUnitCode = chime_sound2;
break;
case 3:
iUnitCode = chime_sound3;
break;
case 4:
iUnitCode = chime_sound4;
break;
case 5:
iUnitCode = chime_sound5;
break;
case 6:
iUnitCode = chime_sound6;
break;
case 7:
iUnitCode = chime_sound7;
break;
}
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if (lighttype == 101)
{
//Curtain Harrison
dtype = pTypeCurtain;
subtype = sTypeHarrison;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype == 102)
{
//RFY
dtype = pTypeRFY;
subtype = sTypeRFY;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 103)
{
//Meiantech
dtype = pTypeSecurity1;
subtype = sTypeMeiantech;
std::string id = request::findValue(&req, "id");
if (
(id.empty())
)
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 104)
{
//HE105
dtype = pTypeThermostat2;
subtype = sTypeHE105;
sunitcode = request::findValue(&req, "unitcode");
if (sunitcode.empty())
return;
//convert to hex, and we have our Unit Code
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << sunitcode;
int iUnitCode;
s_strid >> iUnitCode;
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = "1";
}
else if (lighttype == 105)
{
//ASA
dtype = pTypeRFY;
subtype = sTypeASA;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 106)
{
//Blyss
dtype = pTypeLighting6;
subtype = sTypeBlyss;
std::string sgroupcode = request::findValue(&req, "groupcode");
sunitcode = request::findValue(&req, "unitcode");
std::string id = request::findValue(&req, "id");
if (
(sgroupcode.empty()) ||
(sunitcode.empty()) ||
(id.empty())
)
return;
devid = id + sgroupcode;
}
else if (lighttype == 107)
{
//RFY2
dtype = pTypeRFY;
subtype = sTypeRFY2;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if ((lighttype >= 200) && (lighttype < 300))
{
dtype = pTypeBlinds;
subtype = lighttype - 200;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if (lighttype == 301)
{
//Smartwares Radiator
dtype = pTypeRadiator1;
subtype = sTypeSmartwaresSwitchRadiator;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 302)
{
//Home Confort
dtype = pTypeHomeConfort;
subtype = sTypeHomeConfortTEL010;
std::string id = request::findValue(&req, "id");
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
sprintf(szTmp, "%02X", atoi(shousecode.c_str()));
shousecode = szTmp;
devid = id + shousecode;
}
else if (lighttype == 303)
{
//Selector Switch
dtype = pTypeGeneralSwitch;
subtype = sSwitchTypeSelector;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 304)
{
//Itho CVE RFT
dtype = pTypeFan;
subtype = sTypeItho;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 305)
{
//Lucci Air/DC
dtype = pTypeFan;
subtype = sTypeLucciAir;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 306)
{
//Lucci Air DC
dtype = pTypeFan;
subtype = sTypeLucciAirDC;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 307)
{
//Westinghouse
dtype = pTypeFan;
subtype = sTypeWestinghouse;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 400) {
//Openwebnet Bus Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 401) {
//Openwebnet Bus Lights
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 402)
{
//Openwebnet Bus Auxiliary
dtype = pTypeGeneralSwitch;
subtype = sSwitchAuxiliaryT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 403) {
//Openwebnet Zigbee Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 404) {
//Light Openwebnet Zigbee
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if ((lighttype == 405) || (lighttype == 406)) {
// Openwebnet Dry Contact / IR Detection
dtype = pTypeGeneralSwitch;
subtype = sSwitchContactT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
}
// ----------- If needed convert to GeneralSwitch type (for o.a. RFlink) -----------
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pBaseHardware != NULL)
{
if ((pBaseHardware->HwdType == HTYPE_RFLINKUSB) || (pBaseHardware->HwdType == HTYPE_RFLINKTCP)) {
ConvertToGeneralSwitchType(devid, dtype, subtype);
}
}
// -----------------------------------------------
root["status"] = "OK";
root["message"] = "OK";
root["title"] = "TestSwitch";
std::vector<std::string> sd;
sd.push_back(hwdid);
sd.push_back(devid);
sd.push_back(sunitcode);
sprintf(szTmp, "%d", dtype);
sd.push_back(szTmp);
sprintf(szTmp, "%d", subtype);
sd.push_back(szTmp);
sprintf(szTmp, "%d", switchtype);
sd.push_back(szTmp);
sd.push_back(""); //AddjValue2
sd.push_back(""); //nValue
sd.push_back(""); //sValue
sd.push_back(""); //Name
sd.push_back(""); //Options
std::string switchcmd = "On";
int level = 0;
if (lighttype == 70)
{
//Special EnOcean case, if it is a dimmer, set a dim value
if (switchtype == STYPE_Dimmer)
level = 5;
}
m_mainworker.SwitchLightInt(sd, switchcmd, level, NoColor, true);
}
else if (cparam == "addswitch")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string hwdid = request::findValue(&req, "hwdid");
std::string name = request::findValue(&req, "name");
std::string sswitchtype = request::findValue(&req, "switchtype");
std::string slighttype = request::findValue(&req, "lighttype");
std::string maindeviceidx = request::findValue(&req, "maindeviceidx");
std::string deviceoptions;
if (
(hwdid.empty()) ||
(sswitchtype.empty()) ||
(slighttype.empty()) ||
(name.empty())
)
return;
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
int lighttype = atoi(slighttype.c_str());
int dtype = 0;
int subtype = 0;
std::string sunitcode;
std::string devid;
#ifdef ENABLE_PYTHON
//check if HW is plugin
{
result = m_sql.safe_query("SELECT Type FROM Hardware WHERE (ID == '%q')", hwdid.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
_eHardwareTypes Type = (_eHardwareTypes)atoi(sd[0].c_str());
if (Type == HTYPE_PythonPlugin)
{
// Not allowed to add device to plugin HW (plugin framework does not use key column "ID" but instead uses column "unit" as key)
_log.Log(LOG_ERROR, "CWebServer::HandleCommand addswitch: Not allowed to add device owned by plugin %u!", atoi(hwdid.c_str()));
root["message"] = "Not allowed to add switch to plugin HW!";
return;
}
}
}
#endif
if (lighttype == 70)
{
//EnOcean (Lighting2 with Base_ID offset)
dtype = pTypeLighting2;
subtype = sTypeAC;
sunitcode = request::findValue(&req, "unitcode");
std::string sgroupcode = request::findValue(&req, "groupcode");
int iUnitTest = atoi(sunitcode.c_str()); //gives us 128 devices we can control, should be enough!
if (
(sunitcode.empty()) ||
(sgroupcode.empty()) ||
((iUnitTest < 1) || (iUnitTest > 128))
)
return;
sunitcode = sgroupcode;//Button A/B
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pBaseHardware == NULL)
return;
if ((pBaseHardware->HwdType != HTYPE_EnOceanESP2) && (pBaseHardware->HwdType != HTYPE_EnOceanESP3)
&& (pBaseHardware->HwdType != HTYPE_USBtinGateway) )
return;
unsigned long rID = 0;
if (pBaseHardware->HwdType == HTYPE_EnOceanESP2)
{
CEnOceanESP2 *pEnoceanHardware = reinterpret_cast<CEnOceanESP2*>(pBaseHardware);
if (pEnoceanHardware->m_id_base == 0)
{
root["message"] = "BaseID not found, is the hardware running?";
return;
}
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_EnOceanESP3)
{
CEnOceanESP3 *pEnoceanHardware = reinterpret_cast<CEnOceanESP3*>(pBaseHardware);
if (pEnoceanHardware->m_id_base == 0)
{
root["message"] = "BaseID not found, is the hardware running?";
return;
}
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_USBtinGateway)
{
USBtin *pUSBtinHardware = reinterpret_cast<USBtin *>(pBaseHardware);
rID = pUSBtinHardware->switch_id_base;
std::stringstream ssunitcode;
ssunitcode << iUnitTest;
sunitcode = ssunitcode.str();
}
//convert to hex, and we have our ID
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << rID;
devid = s_strid.str();
}
else if (lighttype == 68)
{
#ifdef WITH_GPIO
dtype = pTypeLighting1;
subtype = sTypeIMPULS;
devid = "0";
sunitcode = request::findValue(&req, "unitcode"); //Unit code = GPIO number
if (sunitcode.empty()) {
return;
}
CGpio *pGpio = reinterpret_cast<CGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pGpio == NULL) {
return;
}
if (pGpio->HwdType != HTYPE_RaspberryGPIO) {
return;
}
CGpioPin *pPin = CGpio::GetPPinById(atoi(sunitcode.c_str()));
if (pPin == NULL) {
return;
}
#else
return;
#endif
}
else if (lighttype == 69)
{
#ifdef WITH_GPIO
dtype = pTypeLighting2;
subtype = sTypeAC;
devid = "0";
sunitcode = request::findValue(&req, "unitcode"); // sysfs-gpio number
int unitcode = atoi(sunitcode.c_str());
std::string sswitchtype = request::findValue(&req, "switchtype");
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
std::string id = request::findValue(&req, "id");
CSysfsGpio::RequestDbUpdate(unitcode);
if ((id.empty()) || (sunitcode.empty()))
{
return;
}
devid = id;
CSysfsGpio *pSysfsGpio = reinterpret_cast<CSysfsGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if ((pSysfsGpio == NULL) || (pSysfsGpio->HwdType != HTYPE_SysfsGpio))
{
return;
}
#else
return;
#endif
}
else if (lighttype < 20)
{
dtype = pTypeLighting1;
subtype = lighttype;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype < 30)
{
dtype = pTypeLighting2;
subtype = lighttype - 20;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype < 70)
{
dtype = pTypeLighting5;
subtype = lighttype - 50;
if (lighttype == 59)
subtype = sTypeIT;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
if ((subtype != sTypeEMW100) && (subtype != sTypeLivolo) && (subtype != sTypeLivolo1to10) && (subtype != sTypeRGB432W) && (subtype != sTypeLightwaveRF) && (subtype != sTypeIT))
devid = "00" + id;
else
devid = id;
}
else if (lighttype == 101)
{
//Curtain Harrison
dtype = pTypeCurtain;
subtype = sTypeHarrison;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype == 102)
{
//RFY
dtype = pTypeRFY;
subtype = sTypeRFY;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 103)
{
//Meiantech
dtype = pTypeSecurity1;
subtype = sTypeMeiantech;
std::string id = request::findValue(&req, "id");
if (
(id.empty())
)
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 104)
{
//HE105
dtype = pTypeThermostat2;
subtype = sTypeHE105;
sunitcode = request::findValue(&req, "unitcode");
if (sunitcode.empty())
return;
//convert to hex, and we have our Unit Code
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << sunitcode;
int iUnitCode;
s_strid >> iUnitCode;
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = "1";
}
else if (lighttype == 105)
{
//ASA
dtype = pTypeRFY;
subtype = sTypeASA;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 106)
{
//Blyss
dtype = pTypeLighting6;
subtype = sTypeBlyss;
std::string sgroupcode = request::findValue(&req, "groupcode");
sunitcode = request::findValue(&req, "unitcode");
std::string id = request::findValue(&req, "id");
if (
(sgroupcode.empty()) ||
(sunitcode.empty()) ||
(id.empty())
)
return;
devid = id + sgroupcode;
}
else if (lighttype == 107)
{
//RFY2
dtype = pTypeRFY;
subtype = sTypeRFY2;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else
{
if (lighttype == 100)
{
//Chime/ByronSX
dtype = pTypeChime;
subtype = sTypeByronSX;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str()) - 1;
switch (iUnitCode)
{
case 0:
iUnitCode = chime_sound0;
break;
case 1:
iUnitCode = chime_sound1;
break;
case 2:
iUnitCode = chime_sound2;
break;
case 3:
iUnitCode = chime_sound3;
break;
case 4:
iUnitCode = chime_sound4;
break;
case 5:
iUnitCode = chime_sound5;
break;
case 6:
iUnitCode = chime_sound6;
break;
case 7:
iUnitCode = chime_sound7;
break;
}
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if ((lighttype >= 200) && (lighttype < 300))
{
dtype = pTypeBlinds;
subtype = lighttype - 200;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if (lighttype == 301)
{
//Smartwares Radiator
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
//For this device, we will also need to add a Radiator type, do that first
dtype = pTypeRadiator1;
subtype = sTypeSmartwares;
//check if switch is unique
result = m_sql.safe_query(
"SELECT Name FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (!result.empty())
{
root["message"] = "Switch already exists!";
return;
}
bool bActEnabledState = m_sql.m_bAcceptNewHardware;
m_sql.m_bAcceptNewHardware = true;
std::string devname;
m_sql.UpdateValue(atoi(hwdid.c_str()), devid.c_str(), atoi(sunitcode.c_str()), dtype, subtype, 0, -1, 0, "20.5", devname);
m_sql.m_bAcceptNewHardware = bActEnabledState;
//set name and switchtype
result = m_sql.safe_query(
"SELECT ID FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (result.empty())
{
root["message"] = "Error finding switch in Database!?!?";
return;
}
std::string ID = result[0][0];
m_sql.safe_query(
"UPDATE DeviceStatus SET Used=1, Name='%q', SwitchType=%d WHERE (ID == '%q')",
name.c_str(), switchtype, ID.c_str());
//Now continue to insert the switch
dtype = pTypeRadiator1;
subtype = sTypeSmartwaresSwitchRadiator;
}
else if (lighttype == 302)
{
//Home Confort
dtype = pTypeHomeConfort;
subtype = sTypeHomeConfortTEL010;
std::string id = request::findValue(&req, "id");
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
sprintf(szTmp, "%02X", atoi(shousecode.c_str()));
shousecode = szTmp;
devid = id + shousecode;
}
else if (lighttype == 303)
{
//Selector Switch
dtype = pTypeGeneralSwitch;
subtype = sSwitchTypeSelector;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = "0" + id;
switchtype = STYPE_Selector;
if (!deviceoptions.empty()) {
deviceoptions.append(";");
}
deviceoptions.append("SelectorStyle:0;LevelNames:Off|Level1|Level2|Level3");
}
else if (lighttype == 304)
{
//Itho CVE RFT
dtype = pTypeFan;
subtype = sTypeItho;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 305)
{
//Lucci Air
dtype = pTypeFan;
subtype = sTypeLucciAir;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 306)
{
//Lucci Air DC
dtype = pTypeFan;
subtype = sTypeLucciAirDC;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 307)
{
//Westinghouse
dtype = pTypeFan;
subtype = sTypeWestinghouse;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 400)
{
//Openwebnet Bus Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 401)
{
//Openwebnet Bus Lights
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 402)
{
//Openwebnet Bus Auxiliary
dtype = pTypeGeneralSwitch;
subtype = sSwitchAuxiliaryT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 403)
{
//Openwebnet Zigbee Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 404)
{
//Openwebnet Zigbee Lights
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if ((lighttype == 405) || (lighttype == 406))
{
//Openwebnet Dry Contact / IR Detection
dtype = pTypeGeneralSwitch;
subtype = sSwitchContactT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
}
//check if switch is unique
result = m_sql.safe_query(
"SELECT Name FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (!result.empty())
{
root["message"] = "Switch already exists!";
return;
}
// ----------- If needed convert to GeneralSwitch type (for o.a. RFlink) -----------
CDomoticzHardwareBase *pBaseHardware = m_mainworker.GetHardware(atoi(hwdid.c_str()));
if (pBaseHardware != NULL)
{
if ((pBaseHardware->HwdType == HTYPE_RFLINKUSB) || (pBaseHardware->HwdType == HTYPE_RFLINKTCP)) {
ConvertToGeneralSwitchType(devid, dtype, subtype);
}
}
// -----------------------------------------------
bool bActEnabledState = m_sql.m_bAcceptNewHardware;
m_sql.m_bAcceptNewHardware = true;
std::string devname;
m_sql.UpdateValue(atoi(hwdid.c_str()), devid.c_str(), atoi(sunitcode.c_str()), dtype, subtype, 0, -1, 0, devname);
m_sql.m_bAcceptNewHardware = bActEnabledState;
//set name and switchtype
result = m_sql.safe_query(
"SELECT ID FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (result.empty())
{
root["message"] = "Error finding switch in Database!?!?";
return;
}
std::string ID = result[0][0];
m_sql.safe_query(
"UPDATE DeviceStatus SET Used=1, Name='%q', SwitchType=%d WHERE (ID == '%q')",
name.c_str(), switchtype, ID.c_str());
m_mainworker.m_eventsystem.GetCurrentStates();
//Set device options
m_sql.SetDeviceOptions(atoi(ID.c_str()), m_sql.BuildDeviceOptions(deviceoptions, false));
if (maindeviceidx != "")
{
if (maindeviceidx != ID)
{
//this is a sub device for another light/switch
//first check if it is not already a sub device
result = m_sql.safe_query(
"SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q') AND (ParentID =='%q')",
ID.c_str(), maindeviceidx.c_str());
if (result.empty())
{
//no it is not, add it
result = m_sql.safe_query(
"INSERT INTO LightSubDevices (DeviceRowID, ParentID) VALUES ('%q','%q')",
ID.c_str(),
maindeviceidx.c_str()
);
}
}
}
root["status"] = "OK";
root["title"] = "AddSwitch";
}
else if (cparam == "getnotificationtypes")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
//First get Device Type/SubType
result = m_sql.safe_query("SELECT Type, SubType, SwitchType FROM DeviceStatus WHERE (ID == '%q')",
idx.c_str());
if (result.empty())
return;
root["status"] = "OK";
root["title"] = "GetNotificationTypes";
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
unsigned char switchtype = atoi(result[0][2].c_str());
int ii = 0;
if (
(dType == pTypeLighting1) ||
(dType == pTypeLighting2) ||
(dType == pTypeLighting3) ||
(dType == pTypeLighting4) ||
(dType == pTypeLighting5) ||
(dType == pTypeLighting6) ||
(dType == pTypeColorSwitch) ||
(dType == pTypeSecurity1) ||
(dType == pTypeSecurity2) ||
(dType == pTypeEvohome) ||
(dType == pTypeEvohomeRelay) ||
(dType == pTypeCurtain) ||
(dType == pTypeBlinds) ||
(dType == pTypeRFY) ||
(dType == pTypeChime) ||
(dType == pTypeThermostat2) ||
(dType == pTypeThermostat3) ||
(dType == pTypeThermostat4) ||
(dType == pTypeRemote) ||
(dType == pTypeGeneralSwitch) ||
(dType == pTypeHomeConfort) ||
(dType == pTypeFS20) ||
((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator))
)
{
if (switchtype != STYPE_PushOff)
{
root["result"][ii]["val"] = NTYPE_SWITCH_ON;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 1);
ii++;
}
if (switchtype != STYPE_PushOn)
{
root["result"][ii]["val"] = NTYPE_SWITCH_OFF;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 1);
ii++;
}
if (switchtype == STYPE_Media)
{
std::string idx = request::findValue(&req, "idx");
result = m_sql.safe_query("SELECT HardwareID FROM DeviceStatus WHERE (ID=='%q')", idx.c_str());
if (!result.empty())
{
std::string hdwid = result[0][0];
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hdwid.c_str())));
if (pBaseHardware != NULL) {
_eHardwareTypes type = pBaseHardware->HwdType;
root["result"][ii]["val"] = NTYPE_PAUSED;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PAUSED, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PAUSED, 1);
ii++;
if (type == HTYPE_Kodi) {
root["result"][ii]["val"] = NTYPE_AUDIO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AUDIO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AUDIO, 1);
ii++;
root["result"][ii]["val"] = NTYPE_VIDEO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_VIDEO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_VIDEO, 1);
ii++;
root["result"][ii]["val"] = NTYPE_PHOTO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PHOTO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PHOTO, 1);
ii++;
}
if (type == HTYPE_LogitechMediaServer) {
root["result"][ii]["val"] = NTYPE_PLAYING;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PLAYING, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PLAYING, 1);
ii++;
root["result"][ii]["val"] = NTYPE_STOPPED;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_STOPPED, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_STOPPED, 1);
ii++;
}
if (type == HTYPE_HEOS) {
root["result"][ii]["val"] = NTYPE_PLAYING;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PLAYING, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PLAYING, 1);
ii++;
root["result"][ii]["val"] = NTYPE_STOPPED;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_STOPPED, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_STOPPED, 1);
ii++;
}
}
}
}
}
if (
(
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
(dType == pTypeEvohomeZone) ||
(dType == pTypeEvohomeWater) ||
(dType == pTypeThermostat1) ||
(dType == pTypeRego6XXTemp) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))
) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp))
)
{
root["result"][ii]["val"] = NTYPE_TEMPERATURE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 1);
ii++;
}
if (
(dType == pTypeHUM) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO)
)
{
root["result"][ii]["val"] = NTYPE_HUMIDITY;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_HUMIDITY, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_HUMIDITY, 1);
ii++;
}
if (
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO)
)
{
root["result"][ii]["val"] = NTYPE_DEWPOINT;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_DEWPOINT, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_DEWPOINT, 1);
ii++;
}
if (dType == pTypeRAIN)
{
root["result"][ii]["val"] = NTYPE_RAIN;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_RAIN, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_RAIN, 1);
ii++;
}
if (dType == pTypeWIND)
{
root["result"][ii]["val"] = NTYPE_WIND;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_WIND, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_WIND, 1);
ii++;
}
if (dType == pTypeUV)
{
root["result"][ii]["val"] = NTYPE_UV;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_UV, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_UV, 1);
ii++;
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeBARO) ||
(dType == pTypeTEMP_BARO)
)
{
root["result"][ii]["val"] = NTYPE_BARO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_BARO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_BARO, 1);
ii++;
}
if (
((dType == pTypeRFXMeter) && (dSubType == sTypeRFXMeterCount)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental)) ||
(dType == pTypeYouLess) ||
((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))
)
{
if ((switchtype == MTYPE_ENERGY) || (switchtype == MTYPE_ENERGY_GENERATED))
{
root["result"][ii]["val"] = NTYPE_TODAYENERGY;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 1);
}
else if (switchtype == MTYPE_GAS)
{
root["result"][ii]["val"] = NTYPE_TODAYGAS;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYGAS, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYGAS, 1);
}
else if (switchtype == MTYPE_COUNTER)
{
root["result"][ii]["val"] = NTYPE_TODAYCOUNTER;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYCOUNTER, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYCOUNTER, 1);
}
else
{
//water (same as gas)
root["result"][ii]["val"] = NTYPE_TODAYGAS;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYGAS, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYGAS, 1);
}
ii++;
}
if (dType == pTypeYouLess)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeAirQuality)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
else if ((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness)))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeVisibility))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeDistance))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypePressure))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeLux)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeWEIGHT)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeUsage)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (
(dType == pTypeENERGY) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypePOWER)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeCURRENT) && (dSubType == sTypeELEC1))
{
root["result"][ii]["val"] = NTYPE_AMPERE1;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE1, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE1, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE2;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE2, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE2, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE3;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE3, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE3, 1);
ii++;
}
if ((dType == pTypeCURRENTENERGY) && (dSubType == sTypeELEC4))
{
root["result"][ii]["val"] = NTYPE_AMPERE1;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE1, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE1, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE2;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE2, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE2, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE3;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE3, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE3, 1);
ii++;
}
if (dType == pTypeP1Power)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
root["result"][ii]["val"] = NTYPE_TODAYENERGY;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 1);
ii++;
}
if (dType == pTypeP1Gas)
{
root["result"][ii]["val"] = NTYPE_TODAYGAS;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYGAS, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYGAS, 1);
ii++;
}
if ((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint))
{
root["result"][ii]["val"] = NTYPE_TEMPERATURE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 1);
ii++;
}
if (dType == pTypeEvohomeZone)
{
root["result"][ii]["val"] = NTYPE_TEMPERATURE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SETPOINT, 0); //FIXME NTYPE_SETPOINT implementation?
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SETPOINT, 1);
ii++;
}
if ((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypePercentage))
{
root["result"][ii]["val"] = NTYPE_PERCENTAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PERCENTAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PERCENTAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeWaterflow))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeCustom))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeFan))
{
root["result"][ii]["val"] = NTYPE_RPM;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_RPM, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_RPM, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeAlert))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeZWaveAlarm))
{
root["result"][ii]["val"] = NTYPE_VALUE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_VALUE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_VALUE, 1);
ii++;
}
if ((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))
{
root["result"][ii]["val"] = NTYPE_SWITCH_ON;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 1);
ii++;
root["result"][ii]["val"] = NTYPE_SWITCH_OFF;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 1);
ii++;
}
if (!IsLightOrSwitch(dType, dSubType))
{
root["result"][ii]["val"] = NTYPE_LASTUPDATE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_LASTUPDATE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_LASTUPDATE, 1);
ii++;
}
}
else if (cparam == "addnotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string stype = request::findValue(&req, "ttype");
std::string swhen = request::findValue(&req, "twhen");
std::string svalue = request::findValue(&req, "tvalue");
std::string scustommessage = request::findValue(&req, "tmsg");
std::string sactivesystems = request::findValue(&req, "tsystems");
std::string spriority = request::findValue(&req, "tpriority");
std::string ssendalways = request::findValue(&req, "tsendalways");
std::string srecovery = (request::findValue(&req, "trecovery") == "true") ? "1" : "0";
if ((stype.empty()) || (swhen.empty()) || (svalue.empty()) || (spriority.empty()) || (ssendalways.empty()) || (srecovery.empty()))
return;
_eNotificationTypes ntype = (_eNotificationTypes)atoi(stype.c_str());
std::string ttype = Notification_Type_Desc(ntype, 1);
if (
(ntype == NTYPE_SWITCH_ON) ||
(ntype == NTYPE_SWITCH_OFF) ||
(ntype == NTYPE_DEWPOINT)
)
{
if ((ntype == NTYPE_SWITCH_ON) && (swhen == "2")) { // '='
unsigned char twhen = '=';
sprintf(szTmp, "%s;%c;%s", ttype.c_str(), twhen, svalue.c_str());
}
else
strcpy(szTmp, ttype.c_str());
}
else
{
std::string twhen;
if (swhen == "0")
twhen = ">";
else if (swhen == "1")
twhen = ">=";
else if (swhen == "2")
twhen = "=";
else if (swhen == "3")
twhen = "!=";
else if (swhen == "4")
twhen = "<=";
else
twhen = "<";
sprintf(szTmp, "%s;%s;%s;%s", ttype.c_str(), twhen.c_str(), svalue.c_str(), srecovery.c_str());
}
int priority = atoi(spriority.c_str());
bool bOK = m_notifications.AddNotification(idx, szTmp, scustommessage, sactivesystems, priority, (ssendalways == "true") ? true : false);
if (bOK) {
root["status"] = "OK";
root["title"] = "AddNotification";
}
}
else if (cparam == "updatenotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string devidx = request::findValue(&req, "devidx");
if ((idx.empty()) || (devidx.empty()))
return;
std::string stype = request::findValue(&req, "ttype");
std::string swhen = request::findValue(&req, "twhen");
std::string svalue = request::findValue(&req, "tvalue");
std::string scustommessage = request::findValue(&req, "tmsg");
std::string sactivesystems = request::findValue(&req, "tsystems");
std::string spriority = request::findValue(&req, "tpriority");
std::string ssendalways = request::findValue(&req, "tsendalways");
std::string srecovery = (request::findValue(&req, "trecovery") == "true") ? "1" : "0";
if ((stype.empty()) || (swhen.empty()) || (svalue.empty()) || (spriority.empty()) || (ssendalways.empty()) || srecovery.empty())
return;
root["status"] = "OK";
root["title"] = "UpdateNotification";
std::string recoverymsg;
if ((srecovery == "1") && (m_notifications.CustomRecoveryMessage(strtoull(idx.c_str(), NULL, 0), recoverymsg, true)))
{
scustommessage.append(";;");
scustommessage.append(recoverymsg);
}
//delete old record
m_notifications.RemoveNotification(idx);
_eNotificationTypes ntype = (_eNotificationTypes)atoi(stype.c_str());
std::string ttype = Notification_Type_Desc(ntype, 1);
if (
(ntype == NTYPE_SWITCH_ON) ||
(ntype == NTYPE_SWITCH_OFF) ||
(ntype == NTYPE_DEWPOINT)
)
{
if ((ntype == NTYPE_SWITCH_ON) && (swhen == "2")) { // '='
unsigned char twhen = '=';
sprintf(szTmp, "%s;%c;%s", ttype.c_str(), twhen, svalue.c_str());
}
else
strcpy(szTmp, ttype.c_str());
}
else
{
std::string twhen;
if (swhen == "0")
twhen = ">";
else if (swhen == "1")
twhen = ">=";
else if (swhen == "2")
twhen = "=";
else if (swhen == "3")
twhen = "!=";
else if (swhen == "4")
twhen = "<=";
else
twhen = "<";
sprintf(szTmp, "%s;%s;%s;%s", ttype.c_str(), twhen.c_str(), svalue.c_str(), srecovery.c_str());
}
int priority = atoi(spriority.c_str());
m_notifications.AddNotification(devidx, szTmp, scustommessage, sactivesystems, priority, (ssendalways == "true") ? true : false);
}
else if (cparam == "deletenotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteNotification";
m_notifications.RemoveNotification(idx);
}
else if (cparam == "switchdeviceorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx1 = request::findValue(&req, "idx1");
std::string idx2 = request::findValue(&req, "idx2");
if ((idx1.empty()) || (idx2.empty()))
return;
std::string sroomid = request::findValue(&req, "roomid");
int roomid = atoi(sroomid.c_str());
std::string Order1, Order2;
if (roomid == 0)
{
//get device order 1
result = m_sql.safe_query("SELECT [Order] FROM DeviceStatus WHERE (ID == '%q')",
idx1.c_str());
if (result.empty())
return;
Order1 = result[0][0];
//get device order 2
result = m_sql.safe_query("SELECT [Order] FROM DeviceStatus WHERE (ID == '%q')",
idx2.c_str());
if (result.empty())
return;
Order2 = result[0][0];
root["status"] = "OK";
root["title"] = "SwitchDeviceOrder";
if (atoi(Order1.c_str()) < atoi(Order2.c_str()))
{
m_sql.safe_query(
"UPDATE DeviceStatus SET [Order] = [Order]+1 WHERE ([Order] >= '%q' AND [Order] < '%q')",
Order1.c_str(), Order2.c_str());
}
else
{
m_sql.safe_query(
"UPDATE DeviceStatus SET [Order] = [Order]-1 WHERE ([Order] > '%q' AND [Order] <= '%q')",
Order2.c_str(), Order1.c_str());
}
m_sql.safe_query("UPDATE DeviceStatus SET [Order] = '%q' WHERE (ID == '%q')",
Order1.c_str(), idx2.c_str());
}
else
{
//change order in a room
//get device order 1
result = m_sql.safe_query("SELECT [Order] FROM DeviceToPlansMap WHERE (DeviceRowID == '%q') AND (PlanID==%d)",
idx1.c_str(), roomid);
if (result.empty())
return;
Order1 = result[0][0];
//get device order 2
result = m_sql.safe_query("SELECT [Order] FROM DeviceToPlansMap WHERE (DeviceRowID == '%q') AND (PlanID==%d)",
idx2.c_str(), roomid);
if (result.empty())
return;
Order2 = result[0][0];
root["status"] = "OK";
root["title"] = "SwitchDeviceOrder";
if (atoi(Order1.c_str()) < atoi(Order2.c_str()))
{
m_sql.safe_query(
"UPDATE DeviceToPlansMap SET [Order] = [Order]+1 WHERE ([Order] >= '%q' AND [Order] < '%q') AND (PlanID==%d)",
Order1.c_str(), Order2.c_str(), roomid);
}
else
{
m_sql.safe_query(
"UPDATE DeviceToPlansMap SET [Order] = [Order]-1 WHERE ([Order] > '%q' AND [Order] <= '%q') AND (PlanID==%d)",
Order2.c_str(), Order1.c_str(), roomid);
}
m_sql.safe_query("UPDATE DeviceToPlansMap SET [Order] = '%q' WHERE (DeviceRowID == '%q') AND (PlanID==%d)",
Order1.c_str(), idx2.c_str(), roomid);
}
}
else if (cparam == "switchsceneorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx1 = request::findValue(&req, "idx1");
std::string idx2 = request::findValue(&req, "idx2");
if ((idx1.empty()) || (idx2.empty()))
return;
std::string Order1, Order2;
//get device order 1
result = m_sql.safe_query("SELECT [Order] FROM Scenes WHERE (ID == '%q')",
idx1.c_str());
if (result.empty())
return;
Order1 = result[0][0];
//get device order 2
result = m_sql.safe_query("SELECT [Order] FROM Scenes WHERE (ID == '%q')",
idx2.c_str());
if (result.empty())
return;
Order2 = result[0][0];
root["status"] = "OK";
root["title"] = "SwitchSceneOrder";
if (atoi(Order1.c_str()) < atoi(Order2.c_str()))
{
m_sql.safe_query(
"UPDATE Scenes SET [Order] = [Order]+1 WHERE ([Order] >= '%q' AND [Order] < '%q')",
Order1.c_str(), Order2.c_str());
}
else
{
m_sql.safe_query(
"UPDATE Scenes SET [Order] = [Order]-1 WHERE ([Order] > '%q' AND [Order] <= '%q')",
Order2.c_str(), Order1.c_str());
}
m_sql.safe_query("UPDATE Scenes SET [Order] = '%q' WHERE (ID == '%q')",
Order1.c_str(), idx2.c_str());
}
else if (cparam == "clearnotifications")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "ClearNotification";
m_notifications.RemoveDeviceNotifications(idx);
}
else if (cparam == "adduser")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string senabled = request::findValue(&req, "enabled");
std::string username = request::findValue(&req, "username");
std::string password = request::findValue(&req, "password");
std::string srights = request::findValue(&req, "rights");
std::string sRemoteSharing = request::findValue(&req, "RemoteSharing");
std::string sTabsEnabled = request::findValue(&req, "TabsEnabled");
if (
(senabled.empty()) ||
(username.empty()) ||
(password.empty()) ||
(srights.empty()) ||
(sRemoteSharing.empty()) ||
(sTabsEnabled.empty())
)
return;
int rights = atoi(srights.c_str());
if (rights != 2)
{
if (!FindAdminUser())
{
root["message"] = "Add a Admin user first! (Or enable Settings/Website Protection)";
return;
}
}
root["status"] = "OK";
root["title"] = "AddUser";
m_sql.safe_query(
"INSERT INTO Users (Active, Username, Password, Rights, RemoteSharing, TabsEnabled) VALUES (%d,'%q','%q','%d','%d','%d')",
(senabled == "true") ? 1 : 0,
base64_encode(username).c_str(),
password.c_str(),
rights,
(sRemoteSharing == "true") ? 1 : 0,
atoi(sTabsEnabled.c_str())
);
LoadUsers();
}
else if (cparam == "updateuser")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string senabled = request::findValue(&req, "enabled");
std::string username = request::findValue(&req, "username");
std::string password = request::findValue(&req, "password");
std::string srights = request::findValue(&req, "rights");
std::string sRemoteSharing = request::findValue(&req, "RemoteSharing");
std::string sTabsEnabled = request::findValue(&req, "TabsEnabled");
if (
(senabled.empty()) ||
(username.empty()) ||
(password.empty()) ||
(srights.empty()) ||
(sRemoteSharing.empty()) ||
(sTabsEnabled.empty())
)
return;
int rights = atoi(srights.c_str());
if (rights != 2)
{
if (!FindAdminUser())
{
root["message"] = "Add a Admin user first! (Or enable Settings/Website Protection)";
return;
}
}
std::string sHashedUsername = base64_encode(username);
// Invalid user's sessions if username or password has changed
std::string sOldUsername;
std::string sOldPassword;
result = m_sql.safe_query("SELECT Username, Password FROM Users WHERE (ID == '%q')", idx.c_str());
if (result.size() == 1)
{
sOldUsername = result[0][0];
sOldPassword = result[0][1];
}
if ((sHashedUsername != sOldUsername) || (password != sOldPassword))
RemoveUsersSessions(sOldUsername, session);
root["status"] = "OK";
root["title"] = "UpdateUser";
m_sql.safe_query(
"UPDATE Users SET Active=%d, Username='%q', Password='%q', Rights=%d, RemoteSharing=%d, TabsEnabled=%d WHERE (ID == '%q')",
(senabled == "true") ? 1 : 0,
sHashedUsername.c_str(),
password.c_str(),
rights,
(sRemoteSharing == "true") ? 1 : 0,
atoi(sTabsEnabled.c_str()),
idx.c_str()
);
LoadUsers();
}
else if (cparam == "deleteuser")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteUser";
// Remove user's sessions
result = m_sql.safe_query("SELECT Username FROM Users WHERE (ID == '%q')", idx.c_str());
if (result.size() == 1)
{
RemoveUsersSessions(result[0][0], session);
}
m_sql.safe_query("DELETE FROM Users WHERE (ID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SharedDevices WHERE (SharedUserID == '%q')", idx.c_str());
LoadUsers();
}
else if (cparam == "clearlightlog")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
//First get Device Type/SubType
result = m_sql.safe_query("SELECT Type, SubType FROM DeviceStatus WHERE (ID == '%q')",
idx.c_str());
if (result.empty())
return;
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
if (
(dType != pTypeLighting1) &&
(dType != pTypeLighting2) &&
(dType != pTypeLighting3) &&
(dType != pTypeLighting4) &&
(dType != pTypeLighting5) &&
(dType != pTypeLighting6) &&
(dType != pTypeFan) &&
(dType != pTypeColorSwitch) &&
(dType != pTypeSecurity1) &&
(dType != pTypeSecurity2) &&
(dType != pTypeEvohome) &&
(dType != pTypeEvohomeRelay) &&
(dType != pTypeCurtain) &&
(dType != pTypeBlinds) &&
(dType != pTypeRFY) &&
(dType != pTypeChime) &&
(dType != pTypeThermostat2) &&
(dType != pTypeThermostat3) &&
(dType != pTypeThermostat4) &&
(dType != pTypeRemote) &&
(dType != pTypeGeneralSwitch) &&
(dType != pTypeHomeConfort) &&
(dType != pTypeFS20) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeTextStatus))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeAlert)))
)
return; //no light device! we should not be here!
root["status"] = "OK";
root["title"] = "ClearLightLog";
result = m_sql.safe_query("DELETE FROM LightingLog WHERE (DeviceRowID=='%q')", idx.c_str());
}
else if (cparam == "clearscenelog")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "ClearSceneLog";
result = m_sql.safe_query("DELETE FROM SceneLog WHERE (SceneRowID=='%q')", idx.c_str());
}
else if (cparam == "learnsw")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
m_sql.AllowNewHardwareTimer(5);
m_sql.m_LastSwitchID = "";
bool bReceivedSwitch = false;
unsigned char cntr = 0;
while ((!bReceivedSwitch) && (cntr < 50)) //wait for max. 5 seconds
{
if (m_sql.m_LastSwitchID != "")
{
bReceivedSwitch = true;
break;
}
else
{
//sleep 100ms
sleep_milliseconds(100);
cntr++;
}
}
if (bReceivedSwitch)
{
//check if used
result = m_sql.safe_query("SELECT Name, Used, nValue FROM DeviceStatus WHERE (ID==%" PRIu64 ")",
m_sql.m_LastSwitchRowID);
if (!result.empty())
{
root["status"] = "OK";
root["title"] = "LearnSW";
root["ID"] = m_sql.m_LastSwitchID;
root["idx"] = m_sql.m_LastSwitchRowID;
root["Name"] = result[0][0];
root["Used"] = atoi(result[0][1].c_str());
root["Cmd"] = atoi(result[0][2].c_str());
}
}
} //learnsw
else if (cparam == "makefavorite")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string sisfavorite = request::findValue(&req, "isfavorite");
if ((idx.empty()) || (sisfavorite.empty()))
return;
int isfavorite = atoi(sisfavorite.c_str());
m_sql.safe_query("UPDATE DeviceStatus SET Favorite=%d WHERE (ID == '%q')",
isfavorite, idx.c_str());
root["status"] = "OK";
root["title"] = "MakeFavorite";
} //makefavorite
else if (cparam == "makescenefavorite")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string sisfavorite = request::findValue(&req, "isfavorite");
if ((idx.empty()) || (sisfavorite.empty()))
return;
int isfavorite = atoi(sisfavorite.c_str());
m_sql.safe_query("UPDATE Scenes SET Favorite=%d WHERE (ID == '%q')",
isfavorite, idx.c_str());
root["status"] = "OK";
root["title"] = "MakeSceneFavorite";
} //makescenefavorite
else if (cparam == "resetsecuritystatus")
{
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "switchcmd");
if ((idx.empty()) || (switchcmd.empty()))
return;
root["status"] = "OK";
root["title"] = "ResetSecurityStatus";
int nValue = -1;
// Change to generic *Security_Status_Desc lookup...
if (switchcmd == "Panic End") {
nValue = 7;
}
else if (switchcmd == "Normal") {
nValue = 0;
}
if (nValue >= 0)
{
m_sql.safe_query("UPDATE DeviceStatus SET nValue=%d WHERE (ID == '%q')",
nValue, idx.c_str());
root["status"] = "OK";
root["title"] = "SwitchLight";
}
}
else if (cparam == "verifypasscode")
{
std::string passcode = request::findValue(&req, "passcode");
if (passcode.empty())
return;
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode == rpassword)
{
root["title"] = "VerifyPasscode";
root["status"] = "OK";
return;
}
}
else if (cparam == "switchmodal")
{
int urights = 3;
if (bHaveUser)
{
int iUser = -1;
iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = (int)m_users[iUser].userrights;
_log.Log(LOG_STATUS, "User: %s initiated a modal command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "status");
std::string until = request::findValue(&req, "until");//optional until date / time as applicable
std::string action = request::findValue(&req, "action");//Run action or not (update status only)
std::string onlyonchange = request::findValue(&req, "ooc");//No update unless the value changed (check if updated)
//The on action is used to call a script to update the real device so we only want to use it when altering the status in the Domoticz Web Client
//If we're posting the status from the real device to domoticz we don't want to run the on action script ("action"!=1) to avoid loops and contention
//""... we only want to log a change (and trigger an event) when the status has actually changed ("ooc"==1) i.e. suppress non transient updates
if ((idx.empty()) || (switchcmd.empty()))
return;
std::string passcode = request::findValue(&req, "passcode");
if (passcode.size() > 0)
{
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode != rpassword)
{
root["title"] = "Modal";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
}
if (m_mainworker.SwitchModal(idx, switchcmd, action, onlyonchange, until) == true)//FIXME we need to return a status of already set / no update if ooc=="1" and no status update was performed
{
root["status"] = "OK";
root["title"] = "Modal";
}
}
else if (cparam == "switchlight")
{
if (session.rights < 1)
{
session.reply_status = reply::forbidden;
return; //Only user/admin allowed
}
std::string Username = "Admin";
if (!session.username.empty())
Username = session.username;
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "switchcmd");
std::string level = "-1";
if (switchcmd == "Set Level")
level = request::findValue(&req, "level");
std::string onlyonchange = request::findValue(&req, "ooc");//No update unless the value changed (check if updated)
_log.Debug(DEBUG_WEBSERVER, "WEBS switchlight idx:%s switchcmd:%s level:%s", idx.c_str(), switchcmd.c_str(), level.c_str());
std::string passcode = request::findValue(&req, "passcode");
if ((idx.empty()) || (switchcmd.empty()) || ((switchcmd == "Set Level") && (level.empty())) )
return;
result = m_sql.safe_query(
"SELECT [Protected],[Name] FROM DeviceStatus WHERE (ID = '%q')", idx.c_str());
if (result.empty())
{
//Switch not found!
return;
}
bool bIsProtected = atoi(result[0][0].c_str()) != 0;
std::string sSwitchName = result[0][1];
if (session.rights == 1)
{
if (!IsIdxForUser(&session, atoi(idx.c_str())))
{
_log.Log(LOG_ERROR, "User: %s initiated a Unauthorized switch command!", Username.c_str());
session.reply_status = reply::forbidden;
return;
}
}
if (bIsProtected)
{
if (passcode.empty())
{
//Switch is protected, but no passcode has been
root["title"] = "SwitchLight";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode != rpassword)
{
_log.Log(LOG_ERROR, "User: %s initiated a switch command (Wrong code!)", Username.c_str());
root["title"] = "SwitchLight";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
}
_log.Log(LOG_STATUS, "User: %s initiated a switch command (%s/%s/%s)", Username.c_str(), idx.c_str(), sSwitchName.c_str(), switchcmd.c_str());
root["title"] = "SwitchLight";
if (m_mainworker.SwitchLight(idx, switchcmd, level, "-1", onlyonchange, 0) == true)
{
root["status"] = "OK";
}
else
{
root["status"] = "ERROR";
root["message"] = "Error sending switch command, check device/hardware !";
}
} //(rtype=="switchlight")
else if (cparam == "switchscene")
{
if (session.rights < 1)
{
session.reply_status = reply::forbidden;
return; //Only user/admin allowed
}
std::string Username = "Admin";
if (!session.username.empty())
Username = session.username;
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "switchcmd");
std::string passcode = request::findValue(&req, "passcode");
if ((idx.empty()) || (switchcmd.empty()))
return;
result = m_sql.safe_query(
"SELECT [Protected] FROM Scenes WHERE (ID = '%q')", idx.c_str());
if (result.empty())
{
//Scene/Group not found!
return;
}
bool bIsProtected = atoi(result[0][0].c_str()) != 0;
if (bIsProtected)
{
if (passcode.empty())
{
root["title"] = "SwitchScene";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode != rpassword)
{
root["title"] = "SwitchScene";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
_log.Log(LOG_ERROR, "User: %s initiated a scene/group command (Wrong code!)", Username.c_str());
return;
}
}
_log.Log(LOG_STATUS, "User: %s initiated a scene/group command", Username.c_str());
if (m_mainworker.SwitchScene(idx, switchcmd) == true)
{
root["status"] = "OK";
root["title"] = "SwitchScene";
}
} //(rtype=="switchscene")
else if (cparam == "getSunRiseSet") {
if (!m_mainworker.m_LastSunriseSet.empty())
{
std::vector<std::string> strarray;
StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray);
if (strarray.size() == 10)
{
struct tm loctime;
time_t now = mytime(NULL);
localtime_r(&now, &loctime);
//strftime(szTmp, 80, "%b %d %Y %X", &loctime);
strftime(szTmp, 80, "%Y-%m-%d %X", &loctime);
root["status"] = "OK";
root["title"] = "getSunRiseSet";
root["ServerTime"] = szTmp;
root["Sunrise"] = strarray[0];
root["Sunset"] = strarray[1];
root["SunAtSouth"] = strarray[2];
root["CivTwilightStart"] = strarray[3];
root["CivTwilightEnd"] = strarray[4];
root["NautTwilightStart"] = strarray[5];
root["NautTwilightEnd"] = strarray[6];
root["AstrTwilightStart"] = strarray[7];
root["AstrTwilightEnd"] = strarray[8];
root["DayLength"] = strarray[9];
}
}
}
else if (cparam == "getServerTime") {
struct tm loctime;
time_t now = mytime(NULL);
localtime_r(&now, &loctime);
//strftime(szTmp, 80, "%b %d %Y %X", &loctime);
strftime(szTmp, 80, "%Y-%m-%d %X", &loctime);
root["status"] = "OK";
root["title"] = "getServerTime";
root["ServerTime"] = szTmp;
}
else if (cparam == "getsecstatus")
{
root["status"] = "OK";
root["title"] = "GetSecStatus";
int secstatus = 0;
m_sql.GetPreferencesVar("SecStatus", secstatus);
root["secstatus"] = secstatus;
int secondelay = 30;
m_sql.GetPreferencesVar("SecOnDelay", secondelay);
root["secondelay"] = secondelay;
}
else if (cparam == "setsecstatus")
{
std::string ssecstatus = request::findValue(&req, "secstatus");
std::string seccode = request::findValue(&req, "seccode");
if ((ssecstatus.empty()) || (seccode.empty()))
{
root["message"] = "WRONG CODE";
return;
}
root["title"] = "SetSecStatus";
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("SecPassword", nValue, rpassword);
if (seccode != rpassword)
{
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
root["status"] = "OK";
int iSecStatus = atoi(ssecstatus.c_str());
m_mainworker.UpdateDomoticzSecurityStatus(iSecStatus);
}
else if (cparam == "setcolbrightnessvalue")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
_tColor color;
std::string json = request::findValue(&req, "color");
std::string hex = request::findValue(&req, "hex");
std::string hue = request::findValue(&req, "hue");
std::string sat = request::findValue(&req, "sat");
std::string brightness = request::findValue(&req, "brightness");
std::string iswhite = request::findValue(&req, "iswhite");
int ival = 100;
float brightnessAdj = 1.0f;
if (!json.empty())
{
color = _tColor(json);
if (color.mode == ColorModeRGB)
{
// Normalize RGB to full brightness
float hsb[3];
int r, g, b;
rgb2hsb(color.r, color.g, color.b, hsb);
hsb2rgb(hsb[0]*360.0f, hsb[1], 1.0f, r, g, b, 255);
color.r = r;
color.g = g;
color.b = b;
brightnessAdj = hsb[2];
}
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue: json: %s, color: '%s', bri: '%s'", json.c_str(), color.toString().c_str(), brightness.c_str());
}
else if (!hex.empty())
{
uint64_t ihex = hexstrtoui64(hex);
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue: hex: '%s', ihex: %" PRIx64 ", bri: '%s', iswhite: '%s'", hex.c_str(), ihex, brightness.c_str(), iswhite.c_str());
uint8_t r = 0;
uint8_t g = 0;
uint8_t b = 0;
uint8_t cw = 0;
uint8_t ww = 0;
switch (hex.length())
{
case 6: //RGB
r = (uint8_t)((ihex & 0x0000FF0000) >> 16);
g = (uint8_t)((ihex & 0x000000FF00) >> 8);
b = (uint8_t)ihex & 0xFF;
float hsb[3];
int tr, tg, tb; // tmp of 'int' type so can be passed as references to hsb2rgb
rgb2hsb(r, g, b, hsb);
// Normalize RGB to full brightness
hsb2rgb(hsb[0]*360.0f, hsb[1], 1.0f, tr, tg, tb, 255);
r = tr;
g = tg;
b = tb;
brightnessAdj = hsb[2];
// Backwards compatibility: set iswhite for unsaturated colors
iswhite = (hsb[1] < (20.0 / 255.0)) ? "true" : "false";
color = _tColor(r, g, b, cw, ww, ColorModeRGB);
break;
case 8: //RGB_WW
r = (uint8_t)((ihex & 0x00FF000000) >> 24);
g = (uint8_t)((ihex & 0x0000FF0000) >> 16);
b = (uint8_t)((ihex & 0x000000FF00) >> 8);
ww = (uint8_t)ihex & 0xFF;
color = _tColor(r, g, b, cw, ww, ColorModeCustom);
break;
case 10: //RGB_CW_WW
r = (uint8_t)((ihex & 0xFF00000000) >> 32);
g = (uint8_t)((ihex & 0x00FF000000) >> 24);
b = (uint8_t)((ihex & 0x0000FF0000) >> 16);
cw = (uint8_t)((ihex & 0x000000FF00) >> 8);
ww = (uint8_t)ihex & 0xFF;
color = _tColor(r, g, b, cw, ww, ColorModeCustom);
break;
}
if (iswhite == "true") color.mode = ColorModeWhite;
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue: rgbww: %02x%02x%02x%02x%02x, color: '%s'", r, g, b, cw, ww, color.toString().c_str());
}
else if (!hue.empty())
{
int r, g, b;
//convert hue to RGB
float iHue = float(atof(hue.c_str()));
float iSat = 100.0f;
if (!sat.empty()) iSat = float(atof(sat.c_str()));
hsb2rgb(iHue, iSat/100.0f, 1.0f, r, g, b, 255);
color = _tColor(r, g, b, 0, 0, ColorModeRGB);
if (iswhite == "true") color.mode = ColorModeWhite;
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue2: hue: %f, rgb: %02x%02x%02x, color: '%s'", iHue, r, g, b, color.toString().c_str());
}
if (color.mode == ColorModeNone)
{
return;
}
if (!brightness.empty())
ival = atoi(brightness.c_str());
ival = int(ival * brightnessAdj);
ival = std::max(ival, 0);
ival = std::min(ival, 100);
_log.Log(LOG_STATUS, "setcolbrightnessvalue: ID: %" PRIx64 ", bri: %d, color: '%s'", ID, ival, color.toString().c_str());
m_mainworker.SwitchLight(ID, "Set Color", (unsigned char)ival, color, false, 0);
root["status"] = "OK";
root["title"] = "SetColBrightnessValue";
}
else if (cparam.find("setkelvinlevel") == 0)
{
root["status"] = "OK";
root["title"] = "Set Kelvin Level";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
std::string kelvin = request::findValue(&req, "kelvin");
double ival = atof(kelvin.c_str());
ival = std::max(ival, 0.0);
ival = std::min(ival, 100.0);
_tColor color = _tColor(round(ival*255.0f/100.0f), ColorModeTemp);
_log.Log(LOG_STATUS, "setkelvinlevel: t: %f, color: '%s'", ival, color.toString().c_str());
m_mainworker.SwitchLight(ID, "Set Color", -1, color, false, 0);
}
else if (cparam == "brightnessup")
{
root["status"] = "OK";
root["title"] = "Set brightness up!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Bright Up", 0, NoColor, false, 0);
}
else if (cparam == "brightnessdown")
{
root["status"] = "OK";
root["title"] = "Set brightness down!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Bright Down", 0, NoColor, false, 0);
}
else if (cparam == "discomode")
{
root["status"] = "OK";
root["title"] = "Set to last known disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Disco Mode", 0, NoColor, false, 0);
}
else if (cparam.find("discomodenum") == 0 && cparam != "discomode" && cparam.size() == 13)
{
root["status"] = "OK";
root["title"] = "Set to disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
char szTmp[40];
sprintf(szTmp, "Disco Mode %s", cparam.substr(12).c_str());
m_mainworker.SwitchLight(ID, szTmp, 0, NoColor, false, 0);
}
else if (cparam == "discoup")
{
root["status"] = "OK";
root["title"] = "Set to next disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Disco Up", 0, NoColor, false, 0);
}
else if (cparam == "discodown")
{
root["status"] = "OK";
root["title"] = "Set to previous disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Disco Down", 0, NoColor, false, 0);
}
else if (cparam == "speedup")
{
root["status"] = "OK";
root["title"] = "Set disco speed up!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Up", 0, NoColor, false, 0);
}
else if (cparam == "speeduplong")
{
root["status"] = "OK";
root["title"] = "Set speed long!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Up Long", 0, NoColor, false, 0);
}
else if (cparam == "speeddown")
{
root["status"] = "OK";
root["title"] = "Set disco speed down!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Down", 0, NoColor, false, 0);
}
else if (cparam == "speedmin")
{
root["status"] = "OK";
root["title"] = "Set disco speed minimal!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Minimal", 0, NoColor, false, 0);
}
else if (cparam == "speedmax")
{
root["status"] = "OK";
root["title"] = "Set disco speed maximal!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Maximal", 0, NoColor, false, 0);
}
else if (cparam == "warmer")
{
root["status"] = "OK";
root["title"] = "Set Kelvin up!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Warmer", 0, NoColor, false, 0);
}
else if (cparam == "cooler")
{
root["status"] = "OK";
root["title"] = "Set Kelvin down!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Cooler", 0, NoColor, false, 0);
}
else if (cparam == "fulllight")
{
root["status"] = "OK";
root["title"] = "Set Full!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Set Full", 0, NoColor, false, 0);
}
else if (cparam == "nightlight")
{
root["status"] = "OK";
root["title"] = "Set to nightlight!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Set Night", 0, NoColor, false, 0);
}
else if (cparam == "whitelight")
{
root["status"] = "OK";
root["title"] = "Set to clear white!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
//TODO: Change to color with mode=ColorModeWhite and level=100?
m_mainworker.SwitchLight(ID, "Set White", 0, NoColor, false, 0);
}
else if (cparam == "getfloorplanimages")
{
root["status"] = "OK";
root["title"] = "GetFloorplanImages";
bool bReturnUnused = atoi(request::findValue(&req, "unused").c_str()) != 0;
if (!bReturnUnused)
result = m_sql.safe_query("SELECT ID, Name, ScaleFactor FROM Floorplans ORDER BY [Name]");
else
result = m_sql.safe_query("SELECT ID, Name, ScaleFactor FROM Floorplans WHERE ID NOT IN(SELECT FloorplanID FROM Plans)");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["name"] = sd[1];
root["result"][ii]["scalefactor"] = sd[2];
ii++;
}
}
}
else if (cparam == "updatefloorplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string name = request::findValue(&req, "name");
std::string scalefactor = request::findValue(&req, "scalefactor");
if (
(name.empty())
||(scalefactor.empty())
)
return;
root["status"] = "OK";
root["title"] = "UpdateFloorplan";
m_sql.safe_query(
"UPDATE Floorplans SET Name='%q',ScaleFactor='%q' WHERE (ID == '%q')",
name.c_str(),
scalefactor.c_str(),
idx.c_str()
);
}
else if (cparam == "deletefloorplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteFloorplan";
m_sql.safe_query("UPDATE DeviceToPlansMap SET XOffset=0,YOffset=0 WHERE (PlanID IN (SELECT ID from Plans WHERE (FloorplanID == '%q')))", idx.c_str());
m_sql.safe_query("UPDATE Plans SET FloorplanID=0,Area='' WHERE (FloorplanID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM Floorplans WHERE (ID == '%q')", idx.c_str());
}
else if (cparam == "changefloorplanorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string sway = request::findValue(&req, "way");
if (sway.empty())
return;
bool bGoUp = (sway == "0");
std::string aOrder, oID, oOrder;
result = m_sql.safe_query("SELECT [Order] FROM Floorplans WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
aOrder = result[0][0];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Floorplans WHERE ([Order]>'%q') ORDER BY [Order] ASC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Floorplans WHERE ([Order]<'%q') ORDER BY [Order] DESC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangeFloorPlanOrder";
m_sql.safe_query("UPDATE Floorplans SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
m_sql.safe_query("UPDATE Floorplans SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
else if (cparam == "getunusedfloorplanplans")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "GetUnusedFloorplanPlans";
int ii = 0;
result = m_sql.safe_query("SELECT ID, Name FROM Plans WHERE (FloorplanID==0) ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
ii++;
}
}
}
else if (cparam == "getfloorplanplans")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetFloorplanPlans";
int ii = 0;
result = m_sql.safe_query("SELECT ID, Name, Area FROM Plans WHERE (FloorplanID=='%q') ORDER BY Name",
idx.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Area"] = sd[2];
ii++;
}
}
}
else if (cparam == "addfloorplanplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string planidx = request::findValue(&req, "planidx");
if (
(idx.empty()) ||
(planidx.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddFloorplanPlan";
m_sql.safe_query(
"UPDATE Plans SET FloorplanID='%q' WHERE (ID == '%q')",
idx.c_str(),
planidx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Plan '%s' added to floorplan '%s'.", planidx.c_str(), idx.c_str());
}
else if (cparam == "updatefloorplanplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string planidx = request::findValue(&req, "planidx");
std::string planarea = request::findValue(&req, "area");
if (planidx.empty())
return;
root["status"] = "OK";
root["title"] = "UpdateFloorplanPlan";
m_sql.safe_query(
"UPDATE Plans SET Area='%q' WHERE (ID == '%q')",
planarea.c_str(),
planidx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Plan '%s' floor area updated to '%s'.", planidx.c_str(), planarea.c_str());
}
else if (cparam == "deletefloorplanplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteFloorplanPlan";
m_sql.safe_query(
"UPDATE DeviceToPlansMap SET XOffset=0,YOffset=0 WHERE (PlanID == '%q')",
idx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Device coordinates reset for plan '%s'.", idx.c_str());
m_sql.safe_query(
"UPDATE Plans SET FloorplanID=0,Area='' WHERE (ID == '%q')",
idx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Plan '%s' floorplan data reset.", idx.c_str());
}
}
void CWebServer::DisplaySwitchTypesCombo(std::string & content_part)
{
char szTmp[200];
std::map<std::string, int> _switchtypes;
for (int ii = 0; ii < STYPE_END; ii++)
{
_switchtypes[Switch_Type_Desc((_eSwitchType)ii)] = ii;
}
//return a sorted list
for (const auto & itt : _switchtypes)
{
sprintf(szTmp, "<option value=\"%d\">%s</option>\n", itt.second, itt.first.c_str());
content_part += szTmp;
}
}
void CWebServer::DisplayMeterTypesCombo(std::string & content_part)
{
char szTmp[200];
for (int ii = 0; ii < MTYPE_END; ii++)
{
sprintf(szTmp, "<option value=\"%d\">%s</option>\n", ii, Meter_Type_Desc((_eMeterType)ii));
content_part += szTmp;
}
}
void CWebServer::DisplayLanguageCombo(std::string & content_part)
{
//return a sorted list
std::map<std::string, std::string> _ltypes;
char szTmp[200];
int ii = 0;
while (guiLanguage[ii].szShort != NULL)
{
_ltypes[guiLanguage[ii].szLong] = guiLanguage[ii].szShort;
ii++;
}
for (const auto & itt : _ltypes)
{
sprintf(szTmp, "<option value=\"%s\">%s</option>\n", itt.second.c_str(), itt.first.c_str());
content_part += szTmp;
}
}
void CWebServer::DisplayTimerTypesCombo(std::string & content_part)
{
char szTmp[200];
for (int ii = 0; ii < TTYPE_END; ii++)
{
sprintf(szTmp, "<option data-i18n=\"%s\" value=\"%d\">%s</option>\n", Timer_Type_Desc(ii), ii, Timer_Type_Desc(ii));
content_part += szTmp;
}
}
void CWebServer::LoadUsers()
{
ClearUserPasswords();
std::string WebUserName, WebPassword;
int nValue = 0;
if (m_sql.GetPreferencesVar("WebUserName", nValue, WebUserName))
{
if (m_sql.GetPreferencesVar("WebPassword", nValue, WebPassword))
{
if ((WebUserName != "") && (WebPassword != ""))
{
WebUserName = base64_decode(WebUserName);
//WebPassword = WebPassword;
AddUser(10000, WebUserName, WebPassword, URIGHTS_ADMIN, 0xFFFF);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Active, Username, Password, Rights, TabsEnabled FROM Users");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int bIsActive = static_cast<int>(atoi(sd[1].c_str()));
if (bIsActive)
{
unsigned long ID = (unsigned long)atol(sd[0].c_str());
std::string username = base64_decode(sd[2]);
std::string password = sd[3];
_eUserRights rights = (_eUserRights)atoi(sd[4].c_str());
int activetabs = atoi(sd[5].c_str());
AddUser(ID, username, password, rights, activetabs);
}
}
}
}
}
}
m_mainworker.LoadSharedUsers();
}
void CWebServer::AddUser(const unsigned long ID, const std::string &username, const std::string &password, const int userrights, const int activetabs)
{
std::vector<std::vector<std::string> > result = m_sql.safe_query("SELECT COUNT(*) FROM SharedDevices WHERE (SharedUserID == '%d')", ID);
if (result.empty())
return;
_tWebUserPassword wtmp;
wtmp.ID = ID;
wtmp.Username = username;
wtmp.Password = password;
wtmp.userrights = (_eUserRights)userrights;
wtmp.ActiveTabs = activetabs;
wtmp.TotSensors = atoi(result[0][0].c_str());
m_users.push_back(wtmp);
m_pWebEm->AddUserPassword(ID, username, password, (_eUserRights)userrights, activetabs);
}
void CWebServer::ClearUserPasswords()
{
m_users.clear();
m_pWebEm->ClearUserPasswords();
}
int CWebServer::FindUser(const char* szUserName)
{
int iUser = 0;
for (const auto & itt : m_users)
{
if (itt.Username == szUserName)
return iUser;
iUser++;
}
return -1;
}
bool CWebServer::FindAdminUser()
{
for (const auto & itt : m_users)
{
if (itt.userrights == URIGHTS_ADMIN)
return true;
}
return false;
}
void CWebServer::PostSettings(WebEmSession & session, const request& req, std::string & redirect_uri)
{
redirect_uri = "/index.html";
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string Latitude = request::findValue(&req, "Latitude");
std::string Longitude = request::findValue(&req, "Longitude");
if ((Latitude != "") && (Longitude != ""))
{
std::string LatLong = Latitude + ";" + Longitude;
m_sql.UpdatePreferencesVar("Location", LatLong.c_str());
m_mainworker.GetSunSettings();
}
m_notifications.ConfigFromGetvars(req, true);
std::string DashboardType = request::findValue(&req, "DashboardType");
m_sql.UpdatePreferencesVar("DashboardType", atoi(DashboardType.c_str()));
std::string MobileType = request::findValue(&req, "MobileType");
m_sql.UpdatePreferencesVar("MobileType", atoi(MobileType.c_str()));
int nUnit = atoi(request::findValue(&req, "WindUnit").c_str());
m_sql.UpdatePreferencesVar("WindUnit", nUnit);
m_sql.m_windunit = (_eWindUnit)nUnit;
nUnit = atoi(request::findValue(&req, "TempUnit").c_str());
m_sql.UpdatePreferencesVar("TempUnit", nUnit);
m_sql.m_tempunit = (_eTempUnit)nUnit;
nUnit = atoi(request::findValue(&req, "WeightUnit").c_str());
m_sql.UpdatePreferencesVar("WeightUnit", nUnit);
m_sql.m_weightunit = (_eWeightUnit)nUnit;
m_sql.SetUnitsAndScale();
std::string AuthenticationMethod = request::findValue(&req, "AuthenticationMethod");
_eAuthenticationMethod amethod = (_eAuthenticationMethod)atoi(AuthenticationMethod.c_str());
m_sql.UpdatePreferencesVar("AuthenticationMethod", static_cast<int>(amethod));
m_pWebEm->SetAuthenticationMethod(amethod);
std::string ReleaseChannel = request::findValue(&req, "ReleaseChannel");
m_sql.UpdatePreferencesVar("ReleaseChannel", atoi(ReleaseChannel.c_str()));
std::string LightHistoryDays = request::findValue(&req, "LightHistoryDays");
m_sql.UpdatePreferencesVar("LightHistoryDays", atoi(LightHistoryDays.c_str()));
std::string s5MinuteHistoryDays = request::findValue(&req, "ShortLogDays");
m_sql.UpdatePreferencesVar("5MinuteHistoryDays", atoi(s5MinuteHistoryDays.c_str()));
int iShortLogInterval = atoi(request::findValue(&req, "ShortLogInterval").c_str());
if (iShortLogInterval < 1)
iShortLogInterval = 5;
m_sql.UpdatePreferencesVar("ShortLogInterval", iShortLogInterval);
m_sql.m_ShortLogInterval = iShortLogInterval;
std::string sElectricVoltage = request::findValue(&req, "ElectricVoltage");
m_sql.UpdatePreferencesVar("ElectricVoltage", atoi(sElectricVoltage.c_str()));
std::string sCM113DisplayType = request::findValue(&req, "CM113DisplayType");
m_sql.UpdatePreferencesVar("CM113DisplayType", atoi(sCM113DisplayType.c_str()));
std::string WebUserName = base64_encode(CURLEncode::URLDecode(request::findValue(&req, "WebUserName")));
std::string WebPassword = CURLEncode::URLDecode(request::findValue(&req, "WebPassword"));
//Get old username/password
std::string sOldWebLogin;
std::string sOldWebPassword;
m_sql.GetPreferencesVar("WebUserName", sOldWebLogin);
m_sql.GetPreferencesVar("WebPassword", sOldWebPassword);
bool bHaveAdminUserPasswordChange = false;
if ((WebUserName == sOldWebLogin) && (WebPassword.empty()))
{
//All is OK, no changes
}
else if (WebUserName.empty() || WebPassword.empty())
{
//If no Admin User/Password is specified, we clear them
if ((!sOldWebLogin.empty()) || (!sOldWebPassword.empty()))
bHaveAdminUserPasswordChange = true;
WebUserName = "";
WebPassword = "";
}
else {
if ((WebUserName != sOldWebLogin) || (WebPassword != sOldWebPassword))
{
bHaveAdminUserPasswordChange = true;
}
}
// Invalid sessions of WebUser when the username or password has been changed
if (bHaveAdminUserPasswordChange)
{
RemoveUsersSessions(sOldWebLogin, session);
m_sql.UpdatePreferencesVar("WebUserName", WebUserName.c_str());
m_sql.UpdatePreferencesVar("WebPassword", WebPassword.c_str());
}
std::string WebLocalNetworks = CURLEncode::URLDecode(request::findValue(&req, "WebLocalNetworks"));
std::string WebRemoteProxyIPs = CURLEncode::URLDecode(request::findValue(&req, "WebRemoteProxyIPs"));
m_sql.UpdatePreferencesVar("WebLocalNetworks", WebLocalNetworks.c_str());
m_sql.UpdatePreferencesVar("WebRemoteProxyIPs", WebRemoteProxyIPs.c_str());
LoadUsers();
m_pWebEm->ClearLocalNetworks();
std::vector<std::string> strarray;
StringSplit(WebLocalNetworks, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddLocalNetworks(itt);
//add local hostname
m_pWebEm->AddLocalNetworks("");
m_pWebEm->ClearRemoteProxyIPs();
strarray.clear();
StringSplit(WebRemoteProxyIPs, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddRemoteProxyIPs(itt);
if (session.username.empty())
{
//Local network could be changed so lets for a check here
session.rights = -1;
}
std::string SecPassword = request::findValue(&req, "SecPassword");
SecPassword = CURLEncode::URLDecode(SecPassword);
if (SecPassword.size() != 32)
{
SecPassword = GenerateMD5Hash(SecPassword);
}
m_sql.UpdatePreferencesVar("SecPassword", SecPassword.c_str());
std::string ProtectionPassword = request::findValue(&req, "ProtectionPassword");
ProtectionPassword = CURLEncode::URLDecode(ProtectionPassword);
if (ProtectionPassword.size() != 32)
{
ProtectionPassword = GenerateMD5Hash(ProtectionPassword);
}
m_sql.UpdatePreferencesVar("ProtectionPassword", ProtectionPassword.c_str());
int EnergyDivider = atoi(request::findValue(&req, "EnergyDivider").c_str());
int GasDivider = atoi(request::findValue(&req, "GasDivider").c_str());
int WaterDivider = atoi(request::findValue(&req, "WaterDivider").c_str());
if (EnergyDivider < 1)
EnergyDivider = 1000;
if (GasDivider < 1)
GasDivider = 100;
if (WaterDivider < 1)
WaterDivider = 100;
m_sql.UpdatePreferencesVar("MeterDividerEnergy", EnergyDivider);
m_sql.UpdatePreferencesVar("MeterDividerGas", GasDivider);
m_sql.UpdatePreferencesVar("MeterDividerWater", WaterDivider);
std::string scheckforupdates = request::findValue(&req, "checkforupdates");
m_sql.UpdatePreferencesVar("UseAutoUpdate", (scheckforupdates == "on" ? 1 : 0));
std::string senableautobackup = request::findValue(&req, "enableautobackup");
m_sql.UpdatePreferencesVar("UseAutoBackup", (senableautobackup == "on" ? 1 : 0));
float CostEnergy = static_cast<float>(atof(request::findValue(&req, "CostEnergy").c_str()));
float CostEnergyT2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyT2").c_str()));
float CostEnergyR1 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR1").c_str()));
float CostEnergyR2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR2").c_str()));
float CostGas = static_cast<float>(atof(request::findValue(&req, "CostGas").c_str()));
float CostWater = static_cast<float>(atof(request::findValue(&req, "CostWater").c_str()));
m_sql.UpdatePreferencesVar("CostEnergy", int(CostEnergy*10000.0f));
m_sql.UpdatePreferencesVar("CostEnergyT2", int(CostEnergyT2*10000.0f));
m_sql.UpdatePreferencesVar("CostEnergyR1", int(CostEnergyR1*10000.0f));
m_sql.UpdatePreferencesVar("CostEnergyR2", int(CostEnergyR2*10000.0f));
m_sql.UpdatePreferencesVar("CostGas", int(CostGas*10000.0f));
m_sql.UpdatePreferencesVar("CostWater", int(CostWater*10000.0f));
int rnOldvalue = 0;
int rnvalue = 0;
m_sql.GetPreferencesVar("ActiveTimerPlan", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "ActiveTimerPlan").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("ActiveTimerPlan", rnvalue);
m_sql.m_ActiveTimerPlan = rnvalue;
m_mainworker.m_scheduler.ReloadSchedules();
}
m_sql.UpdatePreferencesVar("DoorbellCommand", atoi(request::findValue(&req, "DoorbellCommand").c_str()));
m_sql.UpdatePreferencesVar("SmartMeterType", atoi(request::findValue(&req, "SmartMeterType").c_str()));
std::string EnableTabFloorplans = request::findValue(&req, "EnableTabFloorplans");
m_sql.UpdatePreferencesVar("EnableTabFloorplans", (EnableTabFloorplans == "on" ? 1 : 0));
std::string EnableTabLights = request::findValue(&req, "EnableTabLights");
m_sql.UpdatePreferencesVar("EnableTabLights", (EnableTabLights == "on" ? 1 : 0));
std::string EnableTabTemp = request::findValue(&req, "EnableTabTemp");
m_sql.UpdatePreferencesVar("EnableTabTemp", (EnableTabTemp == "on" ? 1 : 0));
std::string EnableTabWeather = request::findValue(&req, "EnableTabWeather");
m_sql.UpdatePreferencesVar("EnableTabWeather", (EnableTabWeather == "on" ? 1 : 0));
std::string EnableTabUtility = request::findValue(&req, "EnableTabUtility");
m_sql.UpdatePreferencesVar("EnableTabUtility", (EnableTabUtility == "on" ? 1 : 0));
std::string EnableTabScenes = request::findValue(&req, "EnableTabScenes");
m_sql.UpdatePreferencesVar("EnableTabScenes", (EnableTabScenes == "on" ? 1 : 0));
std::string EnableTabCustom = request::findValue(&req, "EnableTabCustom");
m_sql.UpdatePreferencesVar("EnableTabCustom", (EnableTabCustom == "on" ? 1 : 0));
m_sql.GetPreferencesVar("NotificationSensorInterval", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "NotificationSensorInterval").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("NotificationSensorInterval", rnvalue);
m_notifications.ReloadNotifications();
}
m_sql.GetPreferencesVar("NotificationSwitchInterval", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "NotificationSwitchInterval").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("NotificationSwitchInterval", rnvalue);
m_notifications.ReloadNotifications();
}
std::string RaspCamParams = request::findValue(&req, "RaspCamParams");
if (RaspCamParams != "")
{
if (IsArgumentSecure(RaspCamParams))
m_sql.UpdatePreferencesVar("RaspCamParams", RaspCamParams.c_str());
}
std::string UVCParams = request::findValue(&req, "UVCParams");
if (UVCParams != "")
{
if (IsArgumentSecure(UVCParams))
m_sql.UpdatePreferencesVar("UVCParams", UVCParams.c_str());
}
std::string EnableNewHardware = request::findValue(&req, "AcceptNewHardware");
int iEnableNewHardware = (EnableNewHardware == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("AcceptNewHardware", iEnableNewHardware);
m_sql.m_bAcceptNewHardware = (iEnableNewHardware == 1);
std::string HideDisabledHardwareSensors = request::findValue(&req, "HideDisabledHardwareSensors");
int iHideDisabledHardwareSensors = (HideDisabledHardwareSensors == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("HideDisabledHardwareSensors", iHideDisabledHardwareSensors);
std::string ShowUpdateEffect = request::findValue(&req, "ShowUpdateEffect");
int iShowUpdateEffect = (ShowUpdateEffect == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("ShowUpdateEffect", iShowUpdateEffect);
std::string SendErrorsAsNotification = request::findValue(&req, "SendErrorsAsNotification");
int iSendErrorsAsNotification = (SendErrorsAsNotification == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("SendErrorsAsNotification", iSendErrorsAsNotification);
_log.ForwardErrorsToNotificationSystem(iSendErrorsAsNotification != 0);
std::string DegreeDaysBaseTemperature = request::findValue(&req, "DegreeDaysBaseTemperature");
m_sql.UpdatePreferencesVar("DegreeDaysBaseTemperature", DegreeDaysBaseTemperature);
rnOldvalue = 0;
m_sql.GetPreferencesVar("EnableEventScriptSystem", rnOldvalue);
std::string EnableEventScriptSystem = request::findValue(&req, "EnableEventScriptSystem");
int iEnableEventScriptSystem = (EnableEventScriptSystem == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("EnableEventScriptSystem", iEnableEventScriptSystem);
m_sql.m_bEnableEventSystem = (iEnableEventScriptSystem == 1);
if (iEnableEventScriptSystem != rnOldvalue)
{
m_mainworker.m_eventsystem.SetEnabled(m_sql.m_bEnableEventSystem);
m_mainworker.m_eventsystem.StartEventSystem();
}
rnOldvalue = 0;
m_sql.GetPreferencesVar("DisableDzVentsSystem", rnOldvalue);
std::string DisableDzVentsSystem = request::findValue(&req, "DisableDzVentsSystem");
int iDisableDzVentsSystem = (DisableDzVentsSystem == "on" ? 0 : 1);
m_sql.UpdatePreferencesVar("DisableDzVentsSystem", iDisableDzVentsSystem);
m_sql.m_bDisableDzVentsSystem = (iDisableDzVentsSystem == 1);
if (m_sql.m_bEnableEventSystem && !iDisableDzVentsSystem && iDisableDzVentsSystem != rnOldvalue)
{
m_mainworker.m_eventsystem.LoadEvents();
m_mainworker.m_eventsystem.GetCurrentStates();
}
m_sql.UpdatePreferencesVar("DzVentsLogLevel", atoi(request::findValue(&req, "DzVentsLogLevel").c_str()));
std::string LogEventScriptTrigger = request::findValue(&req, "LogEventScriptTrigger");
m_sql.m_bLogEventScriptTrigger = (LogEventScriptTrigger == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("LogEventScriptTrigger", m_sql.m_bLogEventScriptTrigger);
std::string EnableWidgetOrdering = request::findValue(&req, "AllowWidgetOrdering");
int iEnableAllowWidgetOrdering = (EnableWidgetOrdering == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("AllowWidgetOrdering", iEnableAllowWidgetOrdering);
m_sql.m_bAllowWidgetOrdering = (iEnableAllowWidgetOrdering == 1);
rnOldvalue = 0;
m_sql.GetPreferencesVar("RemoteSharedPort", rnOldvalue);
m_sql.UpdatePreferencesVar("RemoteSharedPort", atoi(request::findValue(&req, "RemoteSharedPort").c_str()));
rnvalue = 0;
m_sql.GetPreferencesVar("RemoteSharedPort", rnvalue);
if (rnvalue != rnOldvalue)
{
m_mainworker.m_sharedserver.StopServer();
if (rnvalue != 0)
{
char szPort[100];
sprintf(szPort, "%d", rnvalue);
m_mainworker.m_sharedserver.StartServer("::", szPort);
m_mainworker.LoadSharedUsers();
}
}
m_sql.UpdatePreferencesVar("Language", request::findValue(&req, "Language").c_str());
std::string SelectedTheme = request::findValue(&req, "Themes");
m_sql.UpdatePreferencesVar("WebTheme", SelectedTheme.c_str());
m_pWebEm->SetWebTheme(SelectedTheme);
std::string Title = request::findValue(&req, "Title").c_str();
m_sql.UpdatePreferencesVar("Title", (Title.empty()) ? "Domoticz" : Title);
m_sql.GetPreferencesVar("RandomTimerFrame", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "RandomSpread").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("RandomTimerFrame", rnvalue);
m_mainworker.m_scheduler.ReloadSchedules();
}
m_sql.UpdatePreferencesVar("SecOnDelay", atoi(request::findValue(&req, "SecOnDelay").c_str()));
int sensortimeout = atoi(request::findValue(&req, "SensorTimeout").c_str());
if (sensortimeout < 10)
sensortimeout = 10;
m_sql.UpdatePreferencesVar("SensorTimeout", sensortimeout);
int batterylowlevel = atoi(request::findValue(&req, "BatterLowLevel").c_str());
if (batterylowlevel > 100)
batterylowlevel = 100;
m_sql.GetPreferencesVar("BatteryLowNotification", rnOldvalue);
m_sql.UpdatePreferencesVar("BatteryLowNotification", batterylowlevel);
if ((rnOldvalue != batterylowlevel) && (batterylowlevel != 0))
m_sql.CheckBatteryLow();
int nValue = 0;
nValue = atoi(request::findValue(&req, "FloorplanPopupDelay").c_str());
m_sql.UpdatePreferencesVar("FloorplanPopupDelay", nValue);
std::string FloorplanFullscreenMode = request::findValue(&req, "FloorplanFullscreenMode");
m_sql.UpdatePreferencesVar("FloorplanFullscreenMode", (FloorplanFullscreenMode == "on" ? 1 : 0));
std::string FloorplanAnimateZoom = request::findValue(&req, "FloorplanAnimateZoom");
m_sql.UpdatePreferencesVar("FloorplanAnimateZoom", (FloorplanAnimateZoom == "on" ? 1 : 0));
std::string FloorplanShowSensorValues = request::findValue(&req, "FloorplanShowSensorValues");
m_sql.UpdatePreferencesVar("FloorplanShowSensorValues", (FloorplanShowSensorValues == "on" ? 1 : 0));
std::string FloorplanShowSwitchValues = request::findValue(&req, "FloorplanShowSwitchValues");
m_sql.UpdatePreferencesVar("FloorplanShowSwitchValues", (FloorplanShowSwitchValues == "on" ? 1 : 0));
std::string FloorplanShowSceneNames = request::findValue(&req, "FloorplanShowSceneNames");
m_sql.UpdatePreferencesVar("FloorplanShowSceneNames", (FloorplanShowSceneNames == "on" ? 1 : 0));
m_sql.UpdatePreferencesVar("FloorplanRoomColour", CURLEncode::URLDecode(request::findValue(&req, "FloorplanRoomColour").c_str()).c_str());
m_sql.UpdatePreferencesVar("FloorplanActiveOpacity", atoi(request::findValue(&req, "FloorplanActiveOpacity").c_str()));
m_sql.UpdatePreferencesVar("FloorplanInactiveOpacity", atoi(request::findValue(&req, "FloorplanInactiveOpacity").c_str()));
#ifndef NOCLOUD
std::string md_userid, md_password, pf_userid, pf_password;
int md_subsystems, pf_subsystems;
m_sql.GetPreferencesVar("MyDomoticzUserId", pf_userid);
m_sql.GetPreferencesVar("MyDomoticzPassword", pf_password);
m_sql.GetPreferencesVar("MyDomoticzSubsystems", pf_subsystems);
md_userid = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzUserId"));
md_password = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzPassword"));
md_subsystems = (request::findValue(&req, "SubsystemHttp").empty() ? 0 : 1) + (request::findValue(&req, "SubsystemShared").empty() ? 0 : 2) + (request::findValue(&req, "SubsystemApps").empty() ? 0 : 4);
if (md_userid != pf_userid || md_password != pf_password || md_subsystems != pf_subsystems) {
m_sql.UpdatePreferencesVar("MyDomoticzUserId", md_userid);
if (md_password != pf_password) {
md_password = base64_encode(md_password);
m_sql.UpdatePreferencesVar("MyDomoticzPassword", md_password);
}
m_sql.UpdatePreferencesVar("MyDomoticzSubsystems", md_subsystems);
m_webservers.RestartProxy();
}
#endif
m_sql.UpdatePreferencesVar("OneWireSensorPollPeriod", atoi(request::findValue(&req, "OneWireSensorPollPeriod").c_str()));
m_sql.UpdatePreferencesVar("OneWireSwitchPollPeriod", atoi(request::findValue(&req, "OneWireSwitchPollPeriod").c_str()));
std::string IFTTTEnabled = request::findValue(&req, "IFTTTEnabled");
int iIFTTTEnabled = (IFTTTEnabled == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("IFTTTEnabled", iIFTTTEnabled);
std::string szKey = request::findValue(&req, "IFTTTAPI");
m_sql.UpdatePreferencesVar("IFTTTAPI", base64_encode(szKey));
m_notifications.LoadConfig();
#ifdef ENABLE_PYTHON
//Signal plugins to update Settings dictionary
PluginLoadConfig();
#endif
}
void CWebServer::RestoreDatabase(WebEmSession & session, const request& req, std::string & redirect_uri)
{
redirect_uri = "/index.html";
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string dbasefile = request::findValue(&req, "dbasefile");
if (dbasefile.empty()) {
return;
}
m_mainworker.StopDomoticzHardware();
m_sql.RestoreDatabase(dbasefile);
m_mainworker.AddAllDomoticzHardware();
}
struct _tHardwareListInt {
std::string Name;
int HardwareTypeVal;
std::string HardwareType;
bool Enabled;
std::string Mode1; // Used to flag DimmerType as relative for some old LimitLessLight type bulbs
std::string Mode2; // Used to flag DimmerType as relative for some old LimitLessLight type bulbs
} tHardwareList;
void CWebServer::GetJSonDevices(
Json::Value &root,
const std::string &rused,
const std::string &rfilter,
const std::string &order,
const std::string &rowid,
const std::string &planID,
const std::string &floorID,
const bool bDisplayHidden,
const bool bDisplayDisabled,
const bool bFetchFavorites,
const time_t LastUpdate,
const std::string &username,
const std::string &hardwareid)
{
std::vector<std::vector<std::string> > result;
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
struct tm tLastUpdate;
localtime_r(&now, &tLastUpdate);
const time_t iLastUpdate = LastUpdate - 1;
int SensorTimeOut = 60;
m_sql.GetPreferencesVar("SensorTimeout", SensorTimeOut);
//Get All Hardware ID's/Names, need them later
std::map<int, _tHardwareListInt> _hardwareNames;
result = m_sql.safe_query("SELECT ID, Name, Enabled, Type, Mode1, Mode2 FROM Hardware");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
_tHardwareListInt tlist;
int ID = atoi(sd[0].c_str());
tlist.Name = sd[1];
tlist.Enabled = (atoi(sd[2].c_str()) != 0);
tlist.HardwareTypeVal = atoi(sd[3].c_str());
#ifndef ENABLE_PYTHON
tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal);
#else
if (tlist.HardwareTypeVal != HTYPE_PythonPlugin)
{
tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal);
}
else
{
tlist.HardwareType = PluginHardwareDesc(ID);
}
#endif
tlist.Mode1 = sd[4];
tlist.Mode2 = sd[5];
_hardwareNames[ID] = tlist;
}
}
root["ActTime"] = static_cast<int>(now);
char szTmp[300];
if (!m_mainworker.m_LastSunriseSet.empty())
{
std::vector<std::string> strarray;
StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray);
if (strarray.size() == 10)
{
//strftime(szTmp, 80, "%b %d %Y %X", &tm1);
strftime(szTmp, 80, "%Y-%m-%d %X", &tm1);
root["ServerTime"] = szTmp;
root["Sunrise"] = strarray[0];
root["Sunset"] = strarray[1];
root["SunAtSouth"] = strarray[2];
root["CivTwilightStart"] = strarray[3];
root["CivTwilightEnd"] = strarray[4];
root["NautTwilightStart"] = strarray[5];
root["NautTwilightEnd"] = strarray[6];
root["AstrTwilightStart"] = strarray[7];
root["AstrTwilightEnd"] = strarray[8];
root["DayLength"] = strarray[9];
}
}
char szOrderBy[50];
std::string szQuery;
bool isAlpha = true;
const std::string orderBy = order.c_str();
for (size_t i = 0; i < orderBy.size(); i++) {
if (!isalpha(orderBy[i])) {
isAlpha = false;
}
}
if (order.empty() || (!isAlpha)) {
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
} else {
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
unsigned char tempsign = m_sql.m_tempsign[0];
bool bHaveUser = false;
int iUser = -1;
unsigned int totUserDevices = 0;
bool bShowScenes = true;
bHaveUser = (username != "");
if (bHaveUser)
{
iUser = FindUser(username.c_str());
if (iUser != -1)
{
_eUserRights urights = m_users[iUser].userrights;
if (urights != URIGHTS_ADMIN)
{
result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == %lu)", m_users[iUser].ID);
totUserDevices = (unsigned int)result.size();
bShowScenes = (m_users[iUser].ActiveTabs&(1 << 1)) != 0;
}
}
}
std::set<std::string> _HiddenDevices;
bool bAllowDeviceToBeHidden = false;
int ii = 0;
if (rfilter == "all")
{
if (
(bShowScenes) &&
((rused == "all") || (rused == "true"))
)
{
//add scenes
if (rowid != "")
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A"
" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)"
" WHERE (A.ID=='%q')",
rowid.c_str());
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A, DeviceToPlansMap as B WHERE (B.PlanID=='%q')"
" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==1) ORDER BY B.[Order]",
planID.c_str());
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A, DeviceToPlansMap as B, Plans as C"
" WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID) AND (B.DeviceRowID==a.ID)"
" AND (B.DevSceneType==1) ORDER BY B.[Order]",
floorID.c_str());
else {
szQuery = (
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A"
" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)"
" ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), order.c_str());
}
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
unsigned char favorite = atoi(sd[4].c_str());
//Check if we only want favorite devices
if ((bFetchFavorites) && (!favorite))
continue;
std::string sLastUpdate = sd[3];
if (iLastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= iLastUpdate)
continue;
}
int nValue = atoi(sd[2].c_str());
unsigned char scenetype = atoi(sd[5].c_str());
int iProtected = atoi(sd[6].c_str());
std::string sSceneName = sd[1];
if (!bDisplayHidden && sSceneName[0] == '$')
{
continue;
}
if (scenetype == 0)
{
root["result"][ii]["Type"] = "Scene";
root["result"][ii]["TypeImg"] = "scene";
}
else
{
root["result"][ii]["Type"] = "Group";
root["result"][ii]["TypeImg"] = "group";
}
// has this scene/group already been seen, now with different plan?
// assume results are ordered such that same device is adjacent
// if the idx and the Type are equal (type to prevent matching against Scene with same idx)
std::string thisIdx = sd[0];
if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) {
std::string typeOfThisOne = root["result"][ii]["Type"].asString();
if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) {
root["result"][ii - 1]["PlanIDs"].append(atoi(sd[9].c_str()));
continue;
}
}
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sSceneName;
root["result"][ii]["Description"] = sd[10];
root["result"][ii]["Favorite"] = favorite;
root["result"][ii]["Protected"] = (iProtected != 0);
root["result"][ii]["LastUpdate"] = sLastUpdate;
root["result"][ii]["PlanID"] = sd[9].c_str();
Json::Value jsonArray;
jsonArray.append(atoi(sd[9].c_str()));
root["result"][ii]["PlanIDs"] = jsonArray;
if (nValue == 0)
root["result"][ii]["Status"] = "Off";
else if (nValue == 1)
root["result"][ii]["Status"] = "On";
else
root["result"][ii]["Status"] = "Mixed";
root["result"][ii]["Data"] = root["result"][ii]["Status"];
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(1, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
root["result"][ii]["XOffset"] = atoi(sd[7].c_str());
root["result"][ii]["YOffset"] = atoi(sd[8].c_str());
ii++;
}
}
}
}
char szData[250];
if (totUserDevices == 0)
{
//All
if (rowid != "")
{
//_log.Log(LOG_STATUS, "Getting device with id: %s", rowid.c_str());
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used, A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus A LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) "
"WHERE (A.ID=='%q')",
rowid.c_str());
}
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, B.XOffset, B.YOffset,"
" B.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, DeviceToPlansMap as B "
"WHERE (B.PlanID=='%q') AND (B.DeviceRowID==a.ID)"
" AND (B.DevSceneType==0) ORDER BY B.[Order]",
planID.c_str());
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, B.XOffset, B.YOffset,"
" B.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, DeviceToPlansMap as B,"
" Plans as C "
"WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID)"
" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"ORDER BY B.[Order]",
floorID.c_str());
else {
if (!bDisplayHidden)
{
//Build a list of Hidden Devices
result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')");
if (!result.empty())
{
std::string pID = result[0][0];
result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)",
pID.c_str());
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator ittP;
for (ittP = result.begin(); ittP != result.end(); ++ittP)
{
_HiddenDevices.insert(ittP[0][0]);
}
}
}
bAllowDeviceToBeHidden = true;
}
if (order.empty() || (!isAlpha))
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
else
{
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
//_log.Log(LOG_STATUS, "Getting all devices: order by %s ", szOrderBy);
if (hardwareid != "") {
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B "
"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"WHERE (A.HardwareID == %q) "
"ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), hardwareid.c_str(), order.c_str());
}
else {
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B "
"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), order.c_str());
}
}
}
else
{
if (iUser == -1) {
return;
}
//Specific devices
if (rowid != "")
{
//_log.Log(LOG_STATUS, "Getting device with id: %s for user %lu", rowid.c_str(), m_users[iUser].ID);
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, 0 as XOffset,"
" 0 as YOffset, 0 as PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B "
"WHERE (B.DeviceRowID==a.ID)"
" AND (B.SharedUserID==%lu) AND (A.ID=='%q')",
m_users[iUser].ID, rowid.c_str());
}
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, C.XOffset,"
" C.YOffset, C.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B,"
" DeviceToPlansMap as C "
"WHERE (C.PlanID=='%q') AND (C.DeviceRowID==a.ID)"
" AND (B.DeviceRowID==a.ID) "
"AND (B.SharedUserID==%lu) ORDER BY C.[Order]",
planID.c_str(), m_users[iUser].ID);
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, C.XOffset, C.YOffset,"
" C.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B,"
" DeviceToPlansMap as C, Plans as D "
"WHERE (D.FloorplanID=='%q') AND (D.ID==C.PlanID)"
" AND (C.DeviceRowID==a.ID) AND (B.DeviceRowID==a.ID)"
" AND (B.SharedUserID==%lu) ORDER BY C.[Order]",
floorID.c_str(), m_users[iUser].ID);
else {
if (!bDisplayHidden)
{
//Build a list of Hidden Devices
result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')");
if (!result.empty())
{
std::string pID = result[0][0];
result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)",
pID.c_str());
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator ittP;
for (ittP = result.begin(); ittP != result.end(); ++ittP)
{
_HiddenDevices.insert(ittP[0][0]);
}
}
}
bAllowDeviceToBeHidden = true;
}
if (order.empty() || (!isAlpha))
{
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
}
else
{
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
// _log.Log(LOG_STATUS, "Getting all devices for user %lu", m_users[iUser].ID);
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, IFNULL(C.XOffset,0),"
" IFNULL(C.YOffset,0), IFNULL(C.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B "
"LEFT OUTER JOIN DeviceToPlansMap as C ON (C.DeviceRowID==A.ID)"
"WHERE (B.DeviceRowID==A.ID)"
" AND (B.SharedUserID==%lu) ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), m_users[iUser].ID, order.c_str());
}
}
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
unsigned char favorite = atoi(sd[12].c_str());
if ((planID != "") && (planID != "0"))
favorite = 1;
//Check if we only want favorite devices
if ((bFetchFavorites) && (!favorite))
continue;
std::string sDeviceName = sd[3];
if (!bDisplayHidden)
{
if (_HiddenDevices.find(sd[0]) != _HiddenDevices.end())
continue;
if (sDeviceName[0] == '$')
{
if (bAllowDeviceToBeHidden)
continue;
if (planID.size() > 0)
sDeviceName = sDeviceName.substr(1);
}
}
int hardwareID = atoi(sd[14].c_str());
std::map<int, _tHardwareListInt>::iterator hItt = _hardwareNames.find(hardwareID);
if (hItt != _hardwareNames.end())
{
//ignore sensors where the hardware is disabled
if ((!bDisplayDisabled) && (!(*hItt).second.Enabled))
continue;
}
unsigned int dType = atoi(sd[5].c_str());
unsigned int dSubType = atoi(sd[6].c_str());
unsigned int used = atoi(sd[4].c_str());
int nValue = atoi(sd[9].c_str());
std::string sValue = sd[10];
std::string sLastUpdate = sd[11];
if (sLastUpdate.size() > 19)
sLastUpdate = sLastUpdate.substr(0, 19);
if (iLastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= iLastUpdate)
continue;
}
_eSwitchType switchtype = (_eSwitchType)atoi(sd[13].c_str());
_eMeterType metertype = (_eMeterType)switchtype;
double AddjValue = atof(sd[15].c_str());
double AddjMulti = atof(sd[16].c_str());
double AddjValue2 = atof(sd[17].c_str());
double AddjMulti2 = atof(sd[18].c_str());
int LastLevel = atoi(sd[19].c_str());
int CustomImage = atoi(sd[20].c_str());
std::string strParam1 = base64_encode(sd[21]);
std::string strParam2 = base64_encode(sd[22]);
int iProtected = atoi(sd[23].c_str());
std::string Description = sd[27];
std::string sOptions = sd[28];
std::string sColor = sd[29];
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sOptions);
struct tm ntime;
time_t checktime;
ParseSQLdatetime(checktime, ntime, sLastUpdate, tm1.tm_isdst);
bool bHaveTimeout = (now - checktime >= SensorTimeOut * 60);
if (dType == pTypeTEMP_RAIN)
continue; //dont want you for now
if ((rused == "true") && (!used))
continue;
if (
(rused == "false") &&
(used)
)
continue;
if (rfilter != "")
{
if (rfilter == "light")
{
if (
(dType != pTypeLighting1) &&
(dType != pTypeLighting2) &&
(dType != pTypeLighting3) &&
(dType != pTypeLighting4) &&
(dType != pTypeLighting5) &&
(dType != pTypeLighting6) &&
(dType != pTypeFan) &&
(dType != pTypeColorSwitch) &&
(dType != pTypeSecurity1) &&
(dType != pTypeSecurity2) &&
(dType != pTypeEvohome) &&
(dType != pTypeEvohomeRelay) &&
(dType != pTypeCurtain) &&
(dType != pTypeBlinds) &&
(dType != pTypeRFY) &&
(dType != pTypeChime) &&
(dType != pTypeThermostat2) &&
(dType != pTypeThermostat3) &&
(dType != pTypeThermostat4) &&
(dType != pTypeRemote) &&
(dType != pTypeGeneralSwitch) &&
(dType != pTypeHomeConfort) &&
(dType != pTypeChime) &&
(dType != pTypeFS20) &&
(!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)))
)
continue;
}
else if (rfilter == "temp")
{
if (
(dType != pTypeTEMP) &&
(dType != pTypeHUM) &&
(dType != pTypeTEMP_HUM) &&
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO) &&
(dType != pTypeEvohomeZone) &&
(dType != pTypeEvohomeWater) &&
(!((dType == pTypeWIND) && (dSubType == sTypeWIND4))) &&
(!((dType == pTypeUV) && (dSubType == sTypeUV3))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp))) &&
(dType != pTypeThermostat1) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))) &&
(dType != pTypeRego6XXTemp)
)
continue;
}
else if (rfilter == "weather")
{
if (
(dType != pTypeWIND) &&
(dType != pTypeRAIN) &&
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO) &&
(dType != pTypeUV) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeVisibility))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeBaro))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)))
)
continue;
}
else if (rfilter == "utility")
{
if (
(dType != pTypeRFXMeter) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD))) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeVoltage))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCurrent))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeTextStatus))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeAlert))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypePressure))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypePercentage))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeWaterflow))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCustom))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeFan))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveClock))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatMode))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatFanMode))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeDistance))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeKwh))) &&
(dType != pTypeCURRENT) &&
(dType != pTypeCURRENTENERGY) &&
(dType != pTypeENERGY) &&
(dType != pTypePOWER) &&
(dType != pTypeP1Power) &&
(dType != pTypeP1Gas) &&
(dType != pTypeYouLess) &&
(dType != pTypeAirQuality) &&
(dType != pTypeLux) &&
(dType != pTypeUsage) &&
(!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))) &&
(!((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint))) &&
(dType != pTypeWEIGHT) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwares)))
)
continue;
}
else if (rfilter == "wind")
{
if (
(dType != pTypeWIND)
)
continue;
}
else if (rfilter == "rain")
{
if (
(dType != pTypeRAIN)
)
continue;
}
else if (rfilter == "uv")
{
if (
(dType != pTypeUV)
)
continue;
}
else if (rfilter == "baro")
{
if (
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO)
)
continue;
}
else if (rfilter == "zwavealarms")
{
if (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveAlarm)))
continue;
}
}
// has this device already been seen, now with different plan?
// assume results are ordered such that same device is adjacent
// if the idx and the Type are equal (type to prevent matching against Scene with same idx)
std::string thisIdx = sd[0];
int devIdx = atoi(thisIdx.c_str());
if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) {
std::string typeOfThisOne = RFX_Type_Desc(dType, 1);
if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) {
root["result"][ii - 1]["PlanIDs"].append(atoi(sd[26].c_str()));
continue;
}
}
root["result"][ii]["HardwareID"] = hardwareID;
if (_hardwareNames.find(hardwareID) == _hardwareNames.end())
{
root["result"][ii]["HardwareName"] = "Unknown?";
root["result"][ii]["HardwareTypeVal"] = 0;
root["result"][ii]["HardwareType"] = "Unknown?";
}
else
{
root["result"][ii]["HardwareName"] = _hardwareNames[hardwareID].Name;
root["result"][ii]["HardwareTypeVal"] = _hardwareNames[hardwareID].HardwareTypeVal;
root["result"][ii]["HardwareType"] = _hardwareNames[hardwareID].HardwareType;
}
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Protected"] = (iProtected != 0);
CDomoticzHardwareBase *pHardware = m_mainworker.GetHardware(hardwareID);
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_SolarEdgeAPI)
{
int seSensorTimeOut = 60 * 24 * 60;
bHaveTimeout = (now - checktime >= seSensorTimeOut * 60);
}
else if (pHardware->HwdType == HTYPE_Wunderground)
{
CWunderground *pWHardware = reinterpret_cast<CWunderground *>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_DarkSky)
{
CDarkSky *pWHardware = reinterpret_cast<CDarkSky*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_AccuWeather)
{
CAccuWeather *pWHardware = reinterpret_cast<CAccuWeather*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_OpenWeatherMap)
{
COpenWeatherMap *pWHardware = reinterpret_cast<COpenWeatherMap*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
}
if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_PythonPlugin))
{
// Device ID special formatting should not be applied to Python plugins
root["result"][ii]["ID"] = sd[1];
}
else
{
sprintf(szData, "%04X", (unsigned int)atoi(sd[1].c_str()));
if (
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_BARO) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeBARO) ||
(dType == pTypeHUM) ||
(dType == pTypeWIND) ||
(dType == pTypeRAIN) ||
(dType == pTypeUV) ||
(dType == pTypeCURRENT) ||
(dType == pTypeCURRENTENERGY) ||
(dType == pTypeENERGY) ||
(dType == pTypeRFXMeter) ||
(dType == pTypeAirQuality) ||
(dType == pTypeRFXSensor) ||
(dType == pTypeP1Power) ||
(dType == pTypeP1Gas)
)
{
root["result"][ii]["ID"] = szData;
}
else
{
root["result"][ii]["ID"] = sd[1];
}
}
root["result"][ii]["Unit"] = atoi(sd[2].c_str());
root["result"][ii]["Type"] = RFX_Type_Desc(dType, 1);
root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(dType, dSubType);
root["result"][ii]["TypeImg"] = RFX_Type_Desc(dType, 2);
root["result"][ii]["Name"] = sDeviceName;
root["result"][ii]["Description"] = Description;
root["result"][ii]["Used"] = used;
root["result"][ii]["Favorite"] = favorite;
int iSignalLevel = atoi(sd[7].c_str());
if (iSignalLevel < 12)
root["result"][ii]["SignalLevel"] = iSignalLevel;
else
root["result"][ii]["SignalLevel"] = "-";
root["result"][ii]["BatteryLevel"] = atoi(sd[8].c_str());
root["result"][ii]["LastUpdate"] = sLastUpdate;
root["result"][ii]["CustomImage"] = CustomImage;
root["result"][ii]["XOffset"] = sd[24].c_str();
root["result"][ii]["YOffset"] = sd[25].c_str();
root["result"][ii]["PlanID"] = sd[26].c_str();
Json::Value jsonArray;
jsonArray.append(atoi(sd[26].c_str()));
root["result"][ii]["PlanIDs"] = jsonArray;
root["result"][ii]["AddjValue"] = AddjValue;
root["result"][ii]["AddjMulti"] = AddjMulti;
root["result"][ii]["AddjValue2"] = AddjValue2;
root["result"][ii]["AddjMulti2"] = AddjMulti2;
std::stringstream s_data;
s_data << int(nValue) << ", " << sValue;
root["result"][ii]["Data"] = s_data.str();
root["result"][ii]["Notifications"] = (m_notifications.HasNotifications(sd[0]) == true) ? "true" : "false";
root["result"][ii]["ShowNotifications"] = true;
bool bHasTimers = false;
if (
(dType == pTypeLighting1) ||
(dType == pTypeLighting2) ||
(dType == pTypeLighting3) ||
(dType == pTypeLighting4) ||
(dType == pTypeLighting5) ||
(dType == pTypeLighting6) ||
(dType == pTypeFan) ||
(dType == pTypeColorSwitch) ||
(dType == pTypeCurtain) ||
(dType == pTypeBlinds) ||
(dType == pTypeRFY) ||
(dType == pTypeChime) ||
(dType == pTypeThermostat2) ||
(dType == pTypeThermostat3) ||
(dType == pTypeThermostat4) ||
(dType == pTypeRemote) ||
(dType == pTypeGeneralSwitch) ||
(dType == pTypeHomeConfort) ||
(dType == pTypeFS20) ||
((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)) ||
((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))
)
{
//add light details
bHasTimers = m_sql.HasTimers(sd[0]);
bHaveTimeout = false;
#ifdef WITH_OPENZWAVE
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
int nodeID = (ID & 0x0000FF00) >> 8;
bHaveTimeout = pZWave->HasNodeFailed(nodeID);
}
}
#endif
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
std::string IconFile = "Light";
std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage);
if (ittIcon != m_custom_light_icons_lookup.end())
{
IconFile = m_custom_light_icons[ittIcon->second].RootFile;
}
root["result"][ii]["Image"] = IconFile;
if (switchtype == STYPE_Dimmer)
{
root["result"][ii]["Level"] = LastLevel;
int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel);
root["result"][ii]["LevelInt"] = iLevel;
if ((dType == pTypeColorSwitch) ||
(dType == pTypeLighting5 && dSubType == sTypeTRC02) ||
(dType == pTypeLighting5 && dSubType == sTypeTRC02_2) ||
(dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02) ||
(dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02_2))
{
_tColor color(sColor);
std::string jsonColor = color.toJSONString();
root["result"][ii]["Color"] = jsonColor;
llevel = LastLevel;
if (lstatus == "Set Level" || lstatus == "Set Color")
{
sprintf(szTmp, "Set Level: %d %%", LastLevel);
root["result"][ii]["Status"] = szTmp;
}
}
}
else
{
root["result"][ii]["Level"] = llevel;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
}
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
std::string DimmerType = "none";
if (switchtype == STYPE_Dimmer)
{
DimmerType = "abs";
if (_hardwareNames.find(hardwareID) != _hardwareNames.end())
{
// Milight V4/V5 bridges do not support absolute dimming for RGB or CW_WW lights
if (_hardwareNames[hardwareID].HardwareTypeVal == HTYPE_LimitlessLights &&
atoi(_hardwareNames[hardwareID].Mode2.c_str()) != CLimitLess::LBTYPE_V6 &&
(atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_RGB ||
atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_White ||
atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_CW_WW))
{
DimmerType = "rel";
}
}
}
root["result"][ii]["DimmerType"] = DimmerType;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(switchtype);
root["result"][ii]["SwitchTypeVal"] = switchtype;
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
bool bIsSubDevice = false;
std::vector<std::vector<std::string> > resultSD;
resultSD = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q')",
sd[0].c_str());
bIsSubDevice = (resultSD.size() > 0);
root["result"][ii]["IsSubDevice"] = bIsSubDevice;
if (switchtype == STYPE_Doorbell)
{
root["result"][ii]["TypeImg"] = "doorbell";
root["result"][ii]["Status"] = "";//"Pressed";
}
else if (switchtype == STYPE_DoorContact)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Open" : "Closed";
if (bIsOn) {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_DoorLock)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Locked" : "Unlocked";
if (bIsOn) {
lstatus = "Locked";
}
else {
lstatus = "Unlocked";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_DoorLockInverted)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Unlocked" : "Locked";
if (bIsOn) {
lstatus = "Unlocked";
}
else {
lstatus = "Locked";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_PushOn)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Push";
}
root["result"][ii]["TypeImg"] = "push";
root["result"][ii]["Status"] = "";
root["result"][ii]["InternalState"] = (IsLightSwitchOn(lstatus) == true) ? "On" : "Off";
}
else if (switchtype == STYPE_PushOff)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Push";
}
root["result"][ii]["TypeImg"] = "push";
root["result"][ii]["Status"] = "";
root["result"][ii]["TypeImg"] = "pushoff";
}
else if (switchtype == STYPE_X10Siren)
root["result"][ii]["TypeImg"] = "siren";
else if (switchtype == STYPE_SMOKEDETECTOR)
{
root["result"][ii]["TypeImg"] = "smoke";
root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR);
}
else if (switchtype == STYPE_Contact)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Contact";
}
root["result"][ii]["TypeImg"] = "contact";
bool bIsOn = IsLightSwitchOn(lstatus);
if (bIsOn) {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_Media)
{
if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_LogitechMediaServer))
root["result"][ii]["TypeImg"] = "LogitechMediaServer";
else
root["result"][ii]["TypeImg"] = "Media";
root["result"][ii]["Status"] = Media_Player_States((_eMediaStatus)nValue);
lstatus = sValue;
}
else if (
(switchtype == STYPE_Blinds) ||
(switchtype == STYPE_VenetianBlindsUS) ||
(switchtype == STYPE_VenetianBlindsEU)
)
{
root["result"][ii]["TypeImg"] = "blinds";
if ((lstatus == "On") || (lstatus == "Close inline relay")) {
lstatus = "Closed";
}
else if ((lstatus == "Stop") || (lstatus == "Stop inline relay")) {
lstatus = "Stopped";
}
else {
lstatus = "Open";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_BlindsInverted)
{
root["result"][ii]["TypeImg"] = "blinds";
if (lstatus == "On") {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if ((switchtype == STYPE_BlindsPercentage) || (switchtype == STYPE_BlindsPercentageInverted))
{
root["result"][ii]["TypeImg"] = "blinds";
root["result"][ii]["Level"] = LastLevel;
int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel);
root["result"][ii]["LevelInt"] = iLevel;
if (lstatus == "On") {
lstatus = (switchtype == STYPE_BlindsPercentage) ? "Closed" : "Open";
}
else if (lstatus == "Off") {
lstatus = (switchtype == STYPE_BlindsPercentage) ? "Open" : "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_Dimmer)
{
root["result"][ii]["TypeImg"] = "dimmer";
}
else if (switchtype == STYPE_Motion)
{
root["result"][ii]["TypeImg"] = "motion";
}
else if (switchtype == STYPE_Selector)
{
std::string selectorStyle = options["SelectorStyle"];
std::string levelOffHidden = options["LevelOffHidden"];
std::string levelNames = options["LevelNames"];
std::string levelActions = options["LevelActions"];
if (selectorStyle.empty()) {
selectorStyle.assign("0"); // default is 'button set'
}
if (levelOffHidden.empty()) {
levelOffHidden.assign("false"); // default is 'not hidden'
}
if (levelNames.empty()) {
levelNames.assign("Off"); // default is Off only
}
root["result"][ii]["TypeImg"] = "Light";
root["result"][ii]["SelectorStyle"] = atoi(selectorStyle.c_str());
root["result"][ii]["LevelOffHidden"] = (levelOffHidden == "true");
root["result"][ii]["LevelNames"] = base64_encode(levelNames);
root["result"][ii]["LevelActions"] = base64_encode(levelActions);
}
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
}
else if (dType == pTypeSecurity1)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "Security";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "security";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
if ((dSubType == sTypeKD101) || (dSubType == sTypeSA30) || (switchtype == STYPE_SMOKEDETECTOR))
{
root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR;
root["result"][ii]["TypeImg"] = "smoke";
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR);
}
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeSecurity2)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "Security";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "security";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeEvohome || dType == pTypeEvohomeRelay)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "evohome";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "override_mini";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
if (dType == pTypeEvohomeRelay)
{
root["result"][ii]["SwitchType"] = "TPI";
root["result"][ii]["Level"] = llevel;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
if (root["result"][ii]["Unit"].asInt() > 100)
root["result"][ii]["Protected"] = true;
sprintf(szData, "%s: %d", lstatus.c_str(), atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
}
}
else if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "override_mini";
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() >= 3)
{
int i = 0;
double tempCelcius = atof(strarray[i++].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
double tempSetPoint;
root["result"][ii]["Temp"] = temp;
if (dType == pTypeEvohomeZone)
{
tempCelcius = atof(strarray[i++].c_str());
tempSetPoint = ConvertTemperature(tempCelcius, tempsign);
root["result"][ii]["SetPoint"] = tempSetPoint;
}
else
root["result"][ii]["State"] = strarray[i++];
std::string strstatus = strarray[i++];
root["result"][ii]["Status"] = strstatus;
if ((dType == pTypeEvohomeZone || dType == pTypeEvohomeWater) && strarray.size() >= 4)
{
root["result"][ii]["Until"] = strarray[i++];
}
if (dType == pTypeEvohomeZone)
{
if (tempCelcius == 325.1)
sprintf(szTmp, "Off");
else
sprintf(szTmp, "%.1f %c", tempSetPoint, tempsign);
if (strarray.size() >= 4)
sprintf(szData, "%.1f %c, (%s), %s until %s", temp, tempsign, szTmp, strstatus.c_str(), strarray[3].c_str());
else
sprintf(szData, "%.1f %c, (%s), %s", temp, tempsign, szTmp, strstatus.c_str());
}
else
if (strarray.size() >= 4)
sprintf(szData, "%.1f %c, %s, %s until %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str(), strarray[3].c_str());
else
sprintf(szData, "%.1f %c, %s, %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if ((dType == pTypeTEMP) || (dType == pTypeRego6XXTemp))
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dType == pTypeThermostat1)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 4)
{
double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if ((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "temperature";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dType == pTypeHUM)
{
root["result"][ii]["Humidity"] = nValue;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(sValue.c_str()));
sprintf(szData, "Humidity %d %%", nValue);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeTEMP_HUM)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 3)
{
double tempCelcius = atof(strarray[0].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
int humidity = atoi(strarray[1].c_str());
root["result"][ii]["Temp"] = temp;
root["result"][ii]["Humidity"] = humidity;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str()));
sprintf(szData, "%.1f %c, %d %%", temp, tempsign, atoi(strarray[1].c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
//Calculate dew point
sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign));
root["result"][ii]["DewPoint"] = szTmp;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeTEMP_HUM_BARO)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 5)
{
double tempCelcius = atof(strarray[0].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
int humidity = atoi(strarray[1].c_str());
root["result"][ii]["Temp"] = temp;
root["result"][ii]["Humidity"] = humidity;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str()));
root["result"][ii]["Forecast"] = atoi(strarray[4].c_str());
sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign));
root["result"][ii]["DewPoint"] = szTmp;
if (dSubType == sTypeTHBFloat)
{
root["result"][ii]["Barometer"] = atof(strarray[3].c_str());
root["result"][ii]["ForecastStr"] = RFX_WSForecast_Desc(atoi(strarray[4].c_str()));
}
else
{
root["result"][ii]["Barometer"] = atoi(strarray[3].c_str());
root["result"][ii]["ForecastStr"] = RFX_Forecast_Desc(atoi(strarray[4].c_str()));
}
if (dSubType == sTypeTHBFloat)
{
sprintf(szData, "%.1f %c, %d %%, %.1f hPa",
temp,
tempsign,
atoi(strarray[1].c_str()),
atof(strarray[3].c_str())
);
}
else
{
sprintf(szData, "%.1f %c, %d %%, %d hPa",
temp,
tempsign,
atoi(strarray[1].c_str()),
atoi(strarray[3].c_str())
);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeTEMP_BARO)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() >= 3)
{
double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
int forecast = atoi(strarray[2].c_str());
root["result"][ii]["Forecast"] = forecast;
root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast);
root["result"][ii]["Barometer"] = atof(strarray[1].c_str());
sprintf(szData, "%.1f %c, %.1f hPa",
tvalue,
tempsign,
atof(strarray[1].c_str())
);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeUV)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
float UVI = static_cast<float>(atof(strarray[0].c_str()));
root["result"][ii]["UVI"] = strarray[0];
if (dSubType == sTypeUV3)
{
double tvalue = ConvertTemperature(atof(strarray[1].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f UVI, %.1f° %c", UVI, tvalue, tempsign);
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else
{
sprintf(szData, "%.1f UVI", UVI);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeWIND)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 6)
{
root["result"][ii]["Direction"] = atof(strarray[0].c_str());
root["result"][ii]["DirectionStr"] = strarray[1];
if (dSubType != sTypeWIND5)
{
int intSpeed = atoi(strarray[2].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
}
else
{
float windms = float(intSpeed) * 0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windms));
}
root["result"][ii]["Speed"] = szTmp;
}
//if (dSubType!=sTypeWIND6) //problem in RFXCOM firmware? gust=speed?
{
int intGust = atoi(strarray[3].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intGust) *m_sql.m_windscale);
}
else
{
float gustms = float(intGust) * 0.1f;
sprintf(szTmp, "%d", MStoBeaufort(gustms));
}
root["result"][ii]["Gust"] = szTmp;
}
if ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp))
{
if (dSubType == sTypeWIND4)
{
double tvalue = ConvertTemperature(atof(strarray[4].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
}
double tvalue = ConvertTemperature(atof(strarray[5].c_str()), tempsign);
root["result"][ii]["Chill"] = tvalue;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeRAIN)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
//get lowest value of today, and max rate
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
if (dSubType != sTypeRAINWU)
{
result2 = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total) FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
}
else
{
result2 = m_sql.safe_query(
"SELECT Total, Total FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q') ORDER BY ROWID DESC LIMIT 1", sd[0].c_str(), szDate);
}
if (!result2.empty())
{
double total_real = 0;
float rate = 0;
std::vector<std::string> sd2 = result2[0];
if (dSubType != sTypeRAINWU)
{
double total_min = atof(sd2[0].c_str());
double total_max = atof(strarray[1].c_str());
total_real = total_max - total_min;
}
else
{
total_real = atof(sd2[1].c_str());
}
total_real *= AddjMulti;
rate = (static_cast<float>(atof(strarray[0].c_str())) / 100.0f)*float(AddjMulti);
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["Rain"] = szTmp;
sprintf(szTmp, "%g", rate);
root["result"][ii]["RainRate"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else
{
root["result"][ii]["Rain"] = "0";
root["result"][ii]["RainRate"] = "0";
root["result"][ii]["Data"] = "0";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
}
else if (dType == pTypeRFXMeter)
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min = std::stoull(sd2[0]);
uint64_t total_max = std::stoull(sValue);
uint64_t total_real = total_max - total_min;
sprintf(szTmp, "%" PRIu64, total_real);
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
float musage = 0.0f;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / (divider / 1000.0f);
sprintf(szTmp, "%d Liter", round(musage));
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64, total_real);
if (!ValueUnits.empty())
{
strcat(szTmp, " ");
strcat(szTmp, ValueUnits.c_str());
}
break;
default:
strcpy(szTmp, "?");
break;
}
}
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
double meteroffset = AddjValue;
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
double dvalue = static_cast<double>(atof(sValue.c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min = std::stoull(sd2[0]);
uint64_t total_max = std::stoull(sValue);
uint64_t total_real = total_max - total_min;
sprintf(szTmp, "%" PRIu64, total_real);
float musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64, total_real);
if (!ValueUnits.empty())
{
strcat(szTmp, " ");
strcat(szTmp, ValueUnits.c_str());
}
break;
default:
strcpy(szTmp, "0");
break;
}
}
root["result"][ii]["Counter"] = sValue;
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "counter";
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
double dvalue = static_cast<double>(atof(sValue.c_str()));
double meteroffset = AddjValue;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64 " %s", static_cast<uint64_t>(meteroffset + dvalue), ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
double dvalue;
if (splitresults.size() < 2) {
dvalue = static_cast<double>(atof(sValue.c_str()));
}
else {
dvalue = static_cast<double>(atof(splitresults[1].c_str()));
if (dvalue < 0.0) {
dvalue = static_cast<double>(atof(splitresults[0].c_str()));
}
}
root["result"][ii]["Data"] = root["result"][ii]["Counter"];
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "counter";
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
root["result"][ii]["ShowNotifications"] = false;
double meteroffset = AddjValue;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if (dType == pTypeYouLess)
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
float musage = 0;
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu %s", total_real, ValueUnits.c_str());
break;
default:
strcpy(szTmp, "0");
break;
}
}
root["result"][ii]["CounterToday"] = szTmp;
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() < 2)
continue;
unsigned long long total_actual = std::strtoull(splitresults[0].c_str(), nullptr, 10);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_actual) / divider;
sprintf(szTmp, "%.03f", musage);
break;
case MTYPE_GAS:
case MTYPE_WATER:
musage = float(total_actual) / divider;
sprintf(szTmp, "%.03f", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu", total_actual);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
unsigned long long acounter = std::strtoull(sValue.c_str(), nullptr, 10);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f kWh %s Watt", musage, splitresults[1].c_str());
break;
case MTYPE_GAS:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu %s", acounter, ValueUnits.c_str());
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%s Watt", splitresults[1].c_str());
break;
case MTYPE_GAS:
sprintf(szTmp, "%s m3", splitresults[1].c_str());
break;
case MTYPE_WATER:
sprintf(szTmp, "%s m3", splitresults[1].c_str());
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%s", splitresults[1].c_str());
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Usage"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeP1Power)
{
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() != 6)
{
root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY;
root["result"][ii]["Counter"] = "0";
root["result"][ii]["CounterDeliv"] = "0";
root["result"][ii]["Usage"] = "Invalid";
root["result"][ii]["UsageDeliv"] = "Invalid";
root["result"][ii]["Data"] = "Invalid!: " + sValue;
root["result"][ii]["HaveTimeout"] = true;
root["result"][ii]["CounterToday"] = "Invalid";
root["result"][ii]["CounterDelivToday"] = "Invalid";
}
else
{
float EnergyDivider = 1000.0f;
int tValue;
if (m_sql.GetPreferencesVar("MeterDividerEnergy", tValue))
{
EnergyDivider = float(tValue);
}
unsigned long long powerusage1 = std::strtoull(splitresults[0].c_str(), nullptr, 10);
unsigned long long powerusage2 = std::strtoull(splitresults[1].c_str(), nullptr, 10);
unsigned long long powerdeliv1 = std::strtoull(splitresults[2].c_str(), nullptr, 10);
unsigned long long powerdeliv2 = std::strtoull(splitresults[3].c_str(), nullptr, 10);
unsigned long long usagecurrent = std::strtoull(splitresults[4].c_str(), nullptr, 10);
unsigned long long delivcurrent = std::strtoull(splitresults[5].c_str(), nullptr, 10);
powerdeliv1 = (powerdeliv1 < 10) ? 0 : powerdeliv1;
powerdeliv2 = (powerdeliv2 < 10) ? 0 : powerdeliv2;
unsigned long long powerusage = powerusage1 + powerusage2;
unsigned long long powerdeliv = powerdeliv1 + powerdeliv2;
if (powerdeliv < 2)
powerdeliv = 0;
double musage = 0;
root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY;
musage = double(powerusage) / EnergyDivider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["Counter"] = szTmp;
musage = double(powerdeliv) / EnergyDivider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["CounterDeliv"] = szTmp;
if (bHaveTimeout)
{
usagecurrent = 0;
delivcurrent = 0;
}
sprintf(szTmp, "%llu Watt", usagecurrent);
root["result"][ii]["Usage"] = szTmp;
sprintf(szTmp, "%llu Watt", delivcurrent);
root["result"][ii]["UsageDeliv"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value1), MIN(Value2), MIN(Value5), MIN(Value6) FROM MultiMeter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min_usage_1 = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_min_deliv_1 = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd2[2].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd2[3].c_str(), nullptr, 10);
unsigned long long total_real_usage, total_real_deliv;
total_real_usage = powerusage - (total_min_usage_1 + total_min_usage_2);
total_real_deliv = powerdeliv - (total_min_deliv_1 + total_min_deliv_2);
musage = double(total_real_usage) / EnergyDivider;
sprintf(szTmp, "%.3f kWh", musage);
root["result"][ii]["CounterToday"] = szTmp;
musage = double(total_real_deliv) / EnergyDivider;
sprintf(szTmp, "%.3f kWh", musage);
root["result"][ii]["CounterDelivToday"] = szTmp;
}
else
{
sprintf(szTmp, "%.3f kWh", 0.0f);
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["CounterDelivToday"] = szTmp;
}
}
}
else if (dType == pTypeP1Gas)
{
root["result"][ii]["SwitchTypeVal"] = MTYPE_GAS;
//get lowest value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min_gas = std::stoull(sd2[0]);
uint64_t gasactual = std::stoull(sValue);
uint64_t total_real_gas = gasactual - total_min_gas;
double musage = double(gasactual) / divider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["Counter"] = szTmp;
musage = double(total_real_gas) / divider;
sprintf(szTmp, "%.03f m3", musage);
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider);
root["result"][ii]["Data"] = szTmp;
}
else
{
sprintf(szTmp, "%.03f", 0.0f);
root["result"][ii]["Counter"] = szTmp;
sprintf(szTmp, "%.03f m3", 0.0f);
root["result"][ii]["CounterToday"] = szTmp;
sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeCURRENT)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 3)
{
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
double val1 = atof(strarray[0].c_str());
double val2 = atof(strarray[1].c_str());
double val3 = atof(strarray[2].c_str());
if (displaytype == 0)
{
if ((val2 == 0) && (val3 == 0))
sprintf(szData, "%.1f A", val1);
else
sprintf(szData, "%.1f A, %.1f A, %.1f A", val1, val2, val3);
}
else
{
if ((val2 == 0) && (val3 == 0))
sprintf(szData, "%d Watt", int(val1*voltage));
else
sprintf(szData, "%d Watt, %d Watt, %d Watt", int(val1*voltage), int(val2*voltage), int(val3*voltage));
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["displaytype"] = displaytype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeCURRENTENERGY)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 4)
{
//CM180i
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
double total = atof(strarray[3].c_str());
if (displaytype == 0)
{
sprintf(szData, "%.1f A, %.1f A, %.1f A", atof(strarray[0].c_str()), atof(strarray[1].c_str()), atof(strarray[2].c_str()));
}
else
{
sprintf(szData, "%d Watt, %d Watt, %d Watt", int(atof(strarray[0].c_str())*voltage), int(atof(strarray[1].c_str())*voltage), int(atof(strarray[2].c_str())*voltage));
}
if (total > 0)
{
sprintf(szTmp, ", Total: %.3f kWh", total / 1000.0f);
strcat(szData, szTmp);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["displaytype"] = displaytype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (
((dType == pTypeENERGY) || (dType == pTypePOWER)) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
double total = atof(strarray[1].c_str()) / 1000;
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::vector<std::string> sd2 = result2[0];
double minimum = atof(sd2[0].c_str()) / divider;
sprintf(szData, "%.3f kWh", total);
root["result"][ii]["Data"] = szData;
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
{
sprintf(szData, "%ld Watt", atol(strarray[0].c_str()));
}
else
{
sprintf(szData, "%g Watt", atof(strarray[0].c_str()));
}
root["result"][ii]["Usage"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%.3f kWh", total - minimum);
root["result"][ii]["CounterToday"] = szTmp;
}
else
{
sprintf(szData, "%.3f kWh", total);
root["result"][ii]["Data"] = szData;
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
{
sprintf(szData, "%ld Watt", atol(strarray[0].c_str()));
}
else
{
sprintf(szData, "%g Watt", atof(strarray[0].c_str()));
}
root["result"][ii]["Usage"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%d kWh", 0);
root["result"][ii]["CounterToday"] = szTmp;
}
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["SwitchTypeVal"] = switchtype; //MTYPE_ENERGY
root["result"][ii]["EnergyMeterMode"] = options["EnergyMeterMode"]; //for alternate Energy Reading
}
}
else if (dType == pTypeAirQuality)
{
if (bHaveTimeout)
nValue = 0;
sprintf(szTmp, "%d ppm", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
int airquality = nValue;
if (airquality < 700)
root["result"][ii]["Quality"] = "Excellent";
else if (airquality < 900)
root["result"][ii]["Quality"] = "Good";
else if (airquality < 1100)
root["result"][ii]["Quality"] = "Fair";
else if (airquality < 1600)
root["result"][ii]["Quality"] = "Mediocre";
else
root["result"][ii]["Quality"] = "Bad";
}
else if (dType == pTypeThermostat)
{
if (dSubType == sTypeThermSetpoint)
{
bHasTimers = m_sql.HasTimers(sd[0]);
double tempCelcius = atof(sValue.c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
sprintf(szTmp, "%.1f", temp);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["SetPoint"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "override_mini";
}
}
else if (dType == pTypeRadiator1)
{
if (dSubType == sTypeSmartwares)
{
bHasTimers = m_sql.HasTimers(sd[0]);
double tempCelcius = atof(sValue.c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
sprintf(szTmp, "%.1f", temp);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["SetPoint"] = szTmp;
root["result"][ii]["HaveTimeout"] = false; //this device does not provide feedback, so no timeout!
root["result"][ii]["TypeImg"] = "override_mini";
}
}
else if (dType == pTypeGeneral)
{
if (dSubType == sTypeVisibility)
{
float vis = static_cast<float>(atof(sValue.c_str()));
if (metertype == 0)
{
//km
sprintf(szTmp, "%.1f km", vis);
}
else
{
//miles
sprintf(szTmp, "%.1f mi", vis*0.6214f);
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Visibility"] = atof(sValue.c_str());
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "visibility";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeDistance)
{
float vis = static_cast<float>(atof(sValue.c_str()));
if (metertype == 0)
{
//km
sprintf(szTmp, "%.1f cm", vis);
}
else
{
//miles
sprintf(szTmp, "%.1f in", vis*0.6214f);
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "visibility";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSolarRadiation)
{
float radiation = static_cast<float>(atof(sValue.c_str()));
sprintf(szTmp, "%.1f Watt/m2", radiation);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Radiation"] = atof(sValue.c_str());
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "radiation";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSoilMoisture)
{
sprintf(szTmp, "%d cb", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Desc"] = Get_Moisture_Desc(nValue);
root["result"][ii]["TypeImg"] = "moisture";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeLeafWetness)
{
sprintf(szTmp, "%d", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["TypeImg"] = "leaf";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSystemTemp)
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Computer";
root["result"][ii]["TypeImg"] = "temperature";
root["result"][ii]["Type"] = "temperature";
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dSubType == sTypePercentage)
{
sprintf(szData, "%g%%", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Computer";
root["result"][ii]["TypeImg"] = "hardware";
}
else if (dSubType == sTypeWaterflow)
{
sprintf(szData, "%g l/min", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Moisture";
root["result"][ii]["TypeImg"] = "moisture";
}
else if (dSubType == sTypeCustom)
{
std::string szAxesLabel = "";
int SensorType = 1;
std::vector<std::string> sResults;
StringSplit(sOptions, ";", sResults);
if (sResults.size() == 2)
{
SensorType = atoi(sResults[0].c_str());
szAxesLabel = sResults[1];
}
sprintf(szData, "%g %s", atof(sValue.c_str()), szAxesLabel.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["SensorType"] = SensorType;
root["result"][ii]["SensorUnit"] = szAxesLabel;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string IconFile = "Custom";
if (CustomImage != 0)
{
std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage);
if (ittIcon != m_custom_light_icons_lookup.end())
{
IconFile = m_custom_light_icons[ittIcon->second].RootFile;
}
}
root["result"][ii]["Image"] = IconFile;
root["result"][ii]["TypeImg"] = IconFile;
}
else if (dSubType == sTypeFan)
{
sprintf(szData, "%d RPM", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Fan";
root["result"][ii]["TypeImg"] = "Fan";
}
else if (dSubType == sTypeSoundLevel)
{
sprintf(szData, "%d dB", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "Speaker";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dSubType == sTypeVoltage)
{
sprintf(szData, "%g V", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Voltage"] = atof(sValue.c_str());
}
else if (dSubType == sTypeCurrent)
{
sprintf(szData, "%g A", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Current"] = atof(sValue.c_str());
}
else if (dSubType == sTypeTextStatus)
{
root["result"][ii]["Data"] = sValue;
root["result"][ii]["TypeImg"] = "text";
root["result"][ii]["HaveTimeout"] = false;
root["result"][ii]["ShowNotifications"] = false;
}
else if (dSubType == sTypeAlert)
{
if (nValue > 4)
nValue = 4;
sprintf(szData, "Level: %d", nValue);
root["result"][ii]["Data"] = szData;
if (!sValue.empty())
root["result"][ii]["Data"] = sValue;
else
root["result"][ii]["Data"] = Get_Alert_Desc(nValue);
root["result"][ii]["TypeImg"] = "Alert";
root["result"][ii]["Level"] = nValue;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dSubType == sTypePressure)
{
sprintf(szData, "%.1f Bar", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "gauge";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Pressure"] = atof(sValue.c_str());
}
else if (dSubType == sTypeBaro)
{
std::vector<std::string> tstrarray;
StringSplit(sValue, ";", tstrarray);
if (tstrarray.empty())
continue;
sprintf(szData, "%g hPa", atof(tstrarray[0].c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "gauge";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
if (tstrarray.size() > 1)
{
root["result"][ii]["Barometer"] = atof(tstrarray[0].c_str());
int forecast = atoi(tstrarray[1].c_str());
root["result"][ii]["Forecast"] = forecast;
root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast);
}
}
else if (dSubType == sTypeZWaveClock)
{
std::vector<std::string> tstrarray;
StringSplit(sValue, ";", tstrarray);
int day = 0;
int hour = 0;
int minute = 0;
if (tstrarray.size() == 3)
{
day = atoi(tstrarray[0].c_str());
hour = atoi(tstrarray[1].c_str());
minute = atoi(tstrarray[2].c_str());
}
sprintf(szData, "%s %02d:%02d", ZWave_Clock_Days(day), hour, minute);
root["result"][ii]["DayTime"] = sValue;
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "clock";
}
else if (dSubType == sTypeZWaveThermostatMode)
{
strcpy(szData, "");
root["result"][ii]["Mode"] = nValue;
root["result"][ii]["TypeImg"] = "mode";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string modes = "";
//Add supported modes
#ifdef WITH_OPENZWAVE
if (pHardware)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
std::vector<std::string> vmodes = pZWave->GetSupportedThermostatModes(ID);
int smode = 0;
char szTmp[200];
for (const auto & itt : vmodes)
{
//Value supported
sprintf(szTmp, "%d;%s;", smode, itt.c_str());
modes += szTmp;
smode++;
}
if (!vmodes.empty())
{
if (nValue < (int)vmodes.size())
{
sprintf(szData, "%s", vmodes[nValue].c_str());
}
}
}
}
#endif
root["result"][ii]["Data"] = szData;
root["result"][ii]["Modes"] = modes;
}
else if (dSubType == sTypeZWaveThermostatFanMode)
{
sprintf(szData, "%s", ZWave_Thermostat_Fan_Modes[nValue]);
root["result"][ii]["Data"] = szData;
root["result"][ii]["Mode"] = nValue;
root["result"][ii]["TypeImg"] = "mode";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
//Add supported modes (add all for now)
bool bAddedSupportedModes = false;
std::string modes = "";
//Add supported modes
#ifdef WITH_OPENZWAVE
if (pHardware)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
modes = pZWave->GetSupportedThermostatFanModes(ID);
bAddedSupportedModes = !modes.empty();
}
}
#endif
if (!bAddedSupportedModes)
{
int smode = 0;
while (ZWave_Thermostat_Fan_Modes[smode] != NULL)
{
sprintf(szTmp, "%d;%s;", smode, ZWave_Thermostat_Fan_Modes[smode]);
modes += szTmp;
smode++;
}
}
root["result"][ii]["Modes"] = modes;
}
else if (dSubType == sTypeZWaveAlarm)
{
sprintf(szData, "Event: 0x%02X (%d)", nValue, nValue);
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "Alert";
root["result"][ii]["Level"] = nValue;
root["result"][ii]["HaveTimeout"] = false;
}
}
else if (dType == pTypeLux)
{
sprintf(szTmp, "%.0f Lux", atof(sValue.c_str()));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeWEIGHT)
{
sprintf(szTmp, "%g %s", m_sql.m_weightscale * atof(sValue.c_str()), m_sql.m_weightsign.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeUsage)
{
if (dSubType == sTypeElectric)
{
sprintf(szData, "%g Watt", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
}
else
{
root["result"][ii]["Data"] = sValue;
}
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeRFXSensor)
{
switch (dSubType)
{
case sTypeRFXSensorAD:
sprintf(szData, "%d mV", atoi(sValue.c_str()));
root["result"][ii]["TypeImg"] = "current";
break;
case sTypeRFXSensorVolt:
sprintf(szData, "%d mV", atoi(sValue.c_str()));
root["result"][ii]["TypeImg"] = "current";
break;
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeRego6XXValue)
{
switch (dSubType)
{
case sTypeRego6XXStatus:
{
std::string lstatus = "On";
if (atoi(sValue.c_str()) == 0)
{
lstatus = "Off";
}
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = false;
root["result"][ii]["MaxDimLevel"] = 0;
root["result"][ii]["HaveGroupCmd"] = false;
root["result"][ii]["TypeImg"] = "utility";
root["result"][ii]["SwitchTypeVal"] = STYPE_OnOff;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_OnOff);
sprintf(szData, "%d", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
if (CustomImage < static_cast<int>(m_custom_light_icons.size()))
root["result"][ii]["Image"] = m_custom_light_icons[CustomImage].RootFile;
else
root["result"][ii]["Image"] = "Light";
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
root["result"][ii]["Level"] = 0;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
}
break;
case sTypeRego6XXCounter:
{
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
}
root["result"][ii]["SwitchTypeVal"] = MTYPE_COUNTER;
root["result"][ii]["Counter"] = sValue;
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
break;
}
}
#ifdef ENABLE_PYTHON
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_PythonPlugin)
{
Plugins::CPlugin *pPlugin = (Plugins::CPlugin*)pHardware;
bHaveTimeout = pPlugin->HasNodeFailed(atoi(sd[2].c_str()));
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
#endif
root["result"][ii]["Timers"] = (bHasTimers == true) ? "true" : "false";
ii++;
}
}
}
void CWebServer::UploadFloorplanImage(WebEmSession & session, const request& req, std::string & redirect_uri)
{
redirect_uri = "/index.html";
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string planname = request::findValue(&req, "planname");
std::string scalefactor = request::findValue(&req, "scalefactor");
std::string imagefile = request::findValue(&req, "imagefile");
std::vector<std::vector<std::string> > result;
m_sql.safe_query("INSERT INTO Floorplans ([Name],[ScaleFactor]) VALUES('%s','%s')", planname.c_str(),scalefactor.c_str());
result = m_sql.safe_query("SELECT MAX(ID) FROM Floorplans");
if (!result.empty())
{
if (!m_sql.safe_UpdateBlobInTableWithID("Floorplans", "Image", result[0][0], imagefile))
_log.Log(LOG_ERROR, "SQL: Problem inserting floorplan image into database! ");
}
}
void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)
{
std::string idx = request::findValue(&req, "idx");
if (idx == "") {
return;
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%d", atol(idx.c_str()));
if (result.empty())
return;
reply::set_content(&rep, result[0][0].begin(), result[0][0].end());
std::string oname = "floorplan";
if (result[0][0].size() > 10)
{
if (result[0][0][0] == 'P')
oname += ".png";
else if (result[0][0][0] == -1)
oname += ".jpg";
else if (result[0][0][0] == 'B')
oname += ".bmp";
else if (result[0][0][0] == 'G')
oname += ".gif";
}
reply::add_header_attachment(&rep, oname);
}
void CWebServer::GetDatabaseBackup(WebEmSession & session, const request& req, reply & rep)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
#ifdef WIN32
std::string OutputFileName = szUserDataFolder + "backup.db";
#else
std::string OutputFileName = "/tmp/backup.db";
#endif
if (m_sql.BackupDatabase(OutputFileName))
{
std::string szAttachmentName = "domoticz.db";
std::string szVar;
if (m_sql.GetPreferencesVar("Title", szVar))
{
stdreplace(szVar, " ", "_");
stdreplace(szVar, "/", "_");
stdreplace(szVar, "\\", "_");
if (!szVar.empty()) {
szAttachmentName = szVar + ".db";
}
}
reply::set_content_from_file(&rep, OutputFileName, szAttachmentName, true);
}
}
void CWebServer::RType_DeleteDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteDevice";
m_sql.DeleteDevices(idx);
m_mainworker.m_scheduler.ReloadSchedules();
}
void CWebServer::RType_AddScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string name = request::findValue(&req, "name");
if (name.empty())
{
root["status"] = "ERR";
root["message"] = "No Scene Name specified!";
return;
}
std::string stype = request::findValue(&req, "scenetype");
if (stype.empty())
{
root["status"] = "ERR";
root["message"] = "No Scene Type specified!";
return;
}
if (m_sql.DoesSceneByNameExits(name) == true)
{
root["status"] = "ERR";
root["message"] = "A Scene with this Name already Exits!";
return;
}
root["status"] = "OK";
root["title"] = "AddScene";
m_sql.safe_query(
"INSERT INTO Scenes (Name,SceneType) VALUES ('%q',%d)",
name.c_str(),
atoi(stype.c_str())
);
if (m_sql.m_bEnableEventSystem)
{
m_mainworker.m_eventsystem.GetCurrentScenesGroups();
}
}
void CWebServer::RType_DeleteScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteScene";
m_sql.safe_query("DELETE FROM Scenes WHERE (ID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SceneDevices WHERE (SceneRowID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SceneTimers WHERE (SceneRowID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SceneLog WHERE (SceneRowID=='%q')", idx.c_str());
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.RemoveSingleState(ullidx, m_mainworker.m_eventsystem.REASON_SCENEGROUP);
}
void CWebServer::RType_UpdateScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string name = request::findValue(&req, "name");
std::string description = request::findValue(&req, "description");
if ((idx.empty()) || (name.empty()))
return;
std::string stype = request::findValue(&req, "scenetype");
if (stype.empty())
{
root["status"] = "ERR";
root["message"] = "No Scene Type specified!";
return;
}
std::string tmpstr = request::findValue(&req, "protected");
int iProtected = (tmpstr == "true") ? 1 : 0;
std::string onaction = base64_decode(request::findValue(&req, "onaction"));
std::string offaction = base64_decode(request::findValue(&req, "offaction"));
root["status"] = "OK";
root["title"] = "UpdateScene";
m_sql.safe_query("UPDATE Scenes SET Name='%q', Description='%q', SceneType=%d, Protected=%d, OnAction='%q', OffAction='%q' WHERE (ID == '%q')",
name.c_str(),
description.c_str(),
atoi(stype.c_str()),
iProtected,
onaction.c_str(),
offaction.c_str(),
idx.c_str()
);
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.WWWUpdateSingleState(ullidx, name, m_mainworker.m_eventsystem.REASON_SCENEGROUP);
}
bool compareIconsByName(const http::server::CWebServer::_tCustomIcon &a, const http::server::CWebServer::_tCustomIcon &b)
{
return a.Title < b.Title;
}
void CWebServer::RType_CustomLightIcons(WebEmSession & session, const request& req, Json::Value &root)
{
int ii = 0;
std::vector<_tCustomIcon> temp_custom_light_icons = m_custom_light_icons;
//Sort by name
std::sort(temp_custom_light_icons.begin(), temp_custom_light_icons.end(), compareIconsByName);
for (const auto & itt : temp_custom_light_icons)
{
root["result"][ii]["idx"] = itt.idx;
root["result"][ii]["imageSrc"] = itt.RootFile;
root["result"][ii]["text"] = itt.Title;
root["result"][ii]["description"] = itt.Description;
ii++;
}
root["status"] = "OK";
}
void CWebServer::RType_Plans(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Plans";
std::string sDisplayHidden = request::findValue(&req, "displayhidden");
bool bDisplayHidden = (sDisplayHidden == "1");
std::vector<std::vector<std::string> > result, result2;
result = m_sql.safe_query("SELECT ID, Name, [Order] FROM Plans ORDER BY [Order]");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string Name = sd[1];
bool bIsHidden = (Name[0] == '$');
if ((bDisplayHidden) || (!bIsHidden))
{
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = Name;
root["result"][ii]["Order"] = sd[2];
unsigned int totDevices = 0;
result2 = m_sql.safe_query("SELECT COUNT(*) FROM DeviceToPlansMap WHERE (PlanID=='%q')",
sd[0].c_str());
if (!result2.empty())
{
totDevices = (unsigned int)atoi(result2[0][0].c_str());
}
root["result"][ii]["Devices"] = totDevices;
ii++;
}
}
}
}
void CWebServer::RType_FloorPlans(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Floorplans";
std::vector<std::vector<std::string> > result, result2, result3;
result = m_sql.safe_query("SELECT Key, nValue, sValue FROM Preferences WHERE Key LIKE 'Floorplan%%'");
if (result.empty())
return;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string Key = sd[0];
int nValue = atoi(sd[1].c_str());
std::string sValue = sd[2];
if (Key == "FloorplanPopupDelay")
{
root["PopupDelay"] = nValue;
}
if (Key == "FloorplanFullscreenMode")
{
root["FullscreenMode"] = nValue;
}
if (Key == "FloorplanAnimateZoom")
{
root["AnimateZoom"] = nValue;
}
if (Key == "FloorplanShowSensorValues")
{
root["ShowSensorValues"] = nValue;
}
if (Key == "FloorplanShowSwitchValues")
{
root["ShowSwitchValues"] = nValue;
}
if (Key == "FloorplanShowSceneNames")
{
root["ShowSceneNames"] = nValue;
}
if (Key == "FloorplanRoomColour")
{
root["RoomColour"] = sValue;
}
if (Key == "FloorplanActiveOpacity")
{
root["ActiveRoomOpacity"] = nValue;
}
if (Key == "FloorplanInactiveOpacity")
{
root["InactiveRoomOpacity"] = nValue;
}
}
result2 = m_sql.safe_query("SELECT ID, Name, ScaleFactor, [Order] FROM Floorplans ORDER BY [Order]");
if (!result2.empty())
{
int ii = 0;
for (const auto & itt : result2)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
std::string ImageURL = "images/floorplans/plan?idx=" + sd[0];
root["result"][ii]["Image"] = ImageURL;
root["result"][ii]["ScaleFactor"] = sd[2];
root["result"][ii]["Order"] = sd[3];
unsigned int totPlans = 0;
result3 = m_sql.safe_query("SELECT COUNT(*) FROM Plans WHERE (FloorplanID=='%q')", sd[0].c_str());
if (!result3.empty())
{
totPlans = (unsigned int)atoi(result3[0][0].c_str());
}
root["result"][ii]["Plans"] = totPlans;
ii++;
}
}
}
void CWebServer::RType_Scenes(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Scenes";
root["AllowWidgetOrdering"] = m_sql.m_bAllowWidgetOrdering;
std::string sDisplayHidden = request::findValue(&req, "displayhidden");
bool bDisplayHidden = (sDisplayHidden == "1");
std::string sLastUpdate = request::findValue(&req, "lastupdate");
time_t LastUpdate = 0;
if (sLastUpdate != "")
{
std::stringstream sstr;
sstr << sLastUpdate;
sstr >> LastUpdate;
}
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
struct tm tLastUpdate;
localtime_r(&now, &tLastUpdate);
root["ActTime"] = static_cast<int>(now);
std::vector<std::vector<std::string> > result, result2;
result = m_sql.safe_query("SELECT ID, Name, Activators, Favorite, nValue, SceneType, LastUpdate, Protected, OnAction, OffAction, Description FROM Scenes ORDER BY [Order]");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string sName = sd[1];
if ((bDisplayHidden == false) && (sName[0] == '$'))
continue;
std::string sLastUpdate = sd[6].c_str();
if (LastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= LastUpdate)
continue;
}
unsigned char nValue = atoi(sd[4].c_str());
unsigned char scenetype = atoi(sd[5].c_str());
int iProtected = atoi(sd[7].c_str());
std::string onaction = base64_encode(sd[8]);
std::string offaction = base64_encode(sd[9]);
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sName;
root["result"][ii]["Description"] = sd[10];
root["result"][ii]["Favorite"] = atoi(sd[3].c_str());
root["result"][ii]["Protected"] = (iProtected != 0);
root["result"][ii]["OnAction"] = onaction;
root["result"][ii]["OffAction"] = offaction;
if (scenetype == 0)
{
root["result"][ii]["Type"] = "Scene";
}
else
{
root["result"][ii]["Type"] = "Group";
}
root["result"][ii]["LastUpdate"] = sLastUpdate;
if (nValue == 0)
root["result"][ii]["Status"] = "Off";
else if (nValue == 1)
root["result"][ii]["Status"] = "On";
else
root["result"][ii]["Status"] = "Mixed";
root["result"][ii]["Timers"] = (m_sql.HasSceneTimers(sd[0]) == true) ? "true" : "false";
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(1, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
ii++;
}
}
if (!m_mainworker.m_LastSunriseSet.empty())
{
std::vector<std::string> strarray;
StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray);
if (strarray.size() == 10)
{
char szTmp[100];
//strftime(szTmp, 80, "%b %d %Y %X", &tm1);
strftime(szTmp, 80, "%Y-%m-%d %X", &tm1);
root["ServerTime"] = szTmp;
root["Sunrise"] = strarray[0];
root["Sunset"] = strarray[1];
root["SunAtSouth"] = strarray[2];
root["CivTwilightStart"] = strarray[3];
root["CivTwilightEnd"] = strarray[4];
root["NautTwilightStart"] = strarray[5];
root["NautTwilightEnd"] = strarray[6];
root["AstrTwilightStart"] = strarray[7];
root["AstrTwilightEnd"] = strarray[8];
root["DayLength"] = strarray[9];
}
}
}
void CWebServer::RType_Hardware(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Hardware";
#ifdef WITH_OPENZWAVE
m_ZW_Hwidx = -1;
#endif
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout FROM Hardware ORDER BY ID ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
_eHardwareTypes hType = (_eHardwareTypes)atoi(sd[3].c_str());
if (hType == HTYPE_DomoticzInternal)
continue;
if (hType == HTYPE_RESERVED_FOR_YOU_1)
continue;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Enabled"] = (sd[2] == "1") ? "true" : "false";
root["result"][ii]["Type"] = hType;
root["result"][ii]["Address"] = sd[4];
root["result"][ii]["Port"] = atoi(sd[5].c_str());
root["result"][ii]["SerialPort"] = sd[6];
root["result"][ii]["Username"] = sd[7];
root["result"][ii]["Password"] = sd[8];
root["result"][ii]["Extra"] = sd[9];
if (hType == HTYPE_PythonPlugin) {
root["result"][ii]["Mode1"] = sd[10]; // Plugins can have non-numeric values in the Mode fields
root["result"][ii]["Mode2"] = sd[11];
root["result"][ii]["Mode3"] = sd[12];
root["result"][ii]["Mode4"] = sd[13];
root["result"][ii]["Mode5"] = sd[14];
root["result"][ii]["Mode6"] = sd[15];
}
else {
root["result"][ii]["Mode1"] = atoi(sd[10].c_str());
root["result"][ii]["Mode2"] = atoi(sd[11].c_str());
root["result"][ii]["Mode3"] = atoi(sd[12].c_str());
root["result"][ii]["Mode4"] = atoi(sd[13].c_str());
root["result"][ii]["Mode5"] = atoi(sd[14].c_str());
root["result"][ii]["Mode6"] = atoi(sd[15].c_str());
}
root["result"][ii]["DataTimeout"] = atoi(sd[16].c_str());
//Special case for openzwave (status for nodes queried)
CDomoticzHardwareBase *pHardware = m_mainworker.GetHardware(atoi(sd[0].c_str()));
if (pHardware != NULL)
{
if (
(pHardware->HwdType == HTYPE_RFXtrx315) ||
(pHardware->HwdType == HTYPE_RFXtrx433) ||
(pHardware->HwdType == HTYPE_RFXtrx868) ||
(pHardware->HwdType == HTYPE_RFXLAN)
)
{
CRFXBase *pMyHardware = reinterpret_cast<CRFXBase*>(pHardware);
if (!pMyHardware->m_Version.empty())
root["result"][ii]["version"] = pMyHardware->m_Version;
else
root["result"][ii]["version"] = sd[11];
root["result"][ii]["noiselvl"] = pMyHardware->m_NoiseLevel;
}
else if ((pHardware->HwdType == HTYPE_MySensorsUSB) || (pHardware->HwdType == HTYPE_MySensorsTCP) || (pHardware->HwdType == HTYPE_MySensorsMQTT))
{
MySensorsBase *pMyHardware = reinterpret_cast<MySensorsBase*>(pHardware);
root["result"][ii]["version"] = pMyHardware->GetGatewayVersion();
}
else if ((pHardware->HwdType == HTYPE_OpenThermGateway) || (pHardware->HwdType == HTYPE_OpenThermGatewayTCP))
{
OTGWBase *pMyHardware = reinterpret_cast<OTGWBase*>(pHardware);
root["result"][ii]["version"] = pMyHardware->m_Version;
}
else if ((pHardware->HwdType == HTYPE_RFLINKUSB) || (pHardware->HwdType == HTYPE_RFLINKTCP))
{
CRFLinkBase *pMyHardware = reinterpret_cast<CRFLinkBase*>(pHardware);
root["result"][ii]["version"] = pMyHardware->m_Version;
}
else
{
#ifdef WITH_OPENZWAVE
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pOZWHardware = reinterpret_cast<COpenZWave*>(pHardware);
root["result"][ii]["version"] = pOZWHardware->GetVersionLong();
root["result"][ii]["NodesQueried"] = (pOZWHardware->m_awakeNodesQueried || pOZWHardware->m_allNodesQueried);
}
#endif
}
}
ii++;
}
}
}
void CWebServer::RType_Devices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string rfilter = request::findValue(&req, "filter");
std::string order = request::findValue(&req, "order");
std::string rused = request::findValue(&req, "used");
std::string rid = request::findValue(&req, "rid");
std::string planid = request::findValue(&req, "plan");
std::string floorid = request::findValue(&req, "floor");
std::string sDisplayHidden = request::findValue(&req, "displayhidden");
std::string sFetchFavorites = request::findValue(&req, "favorite");
std::string sDisplayDisabled = request::findValue(&req, "displaydisabled");
bool bDisplayHidden = (sDisplayHidden == "1");
bool bFetchFavorites = (sFetchFavorites == "1");
int HideDisabledHardwareSensors = 0;
m_sql.GetPreferencesVar("HideDisabledHardwareSensors", HideDisabledHardwareSensors);
bool bDisabledDisabled = (HideDisabledHardwareSensors == 0);
if (sDisplayDisabled == "1")
bDisabledDisabled = true;
std::string sLastUpdate = request::findValue(&req, "lastupdate");
std::string hwidx = request::findValue(&req, "hwidx"); // OTO
time_t LastUpdate = 0;
if (sLastUpdate != "")
{
std::stringstream sstr;
sstr << sLastUpdate;
sstr >> LastUpdate;
}
root["status"] = "OK";
root["title"] = "Devices";
root["app_version"] = szAppVersion;
GetJSonDevices(root, rused, rfilter, order, rid, planid, floorid, bDisplayHidden, bDisabledDisabled, bFetchFavorites, LastUpdate, session.username, hwidx);
}
void CWebServer::RType_Users(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
urights = static_cast<int>(m_users[iUser].userrights);
}
if (urights < 2)
return;
root["status"] = "OK";
root["title"] = "Users";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Active, Username, Password, Rights, RemoteSharing, TabsEnabled FROM USERS ORDER BY ID ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Enabled"] = (sd[1] == "1") ? "true" : "false";
root["result"][ii]["Username"] = base64_decode(sd[2]);
root["result"][ii]["Password"] = sd[3];
root["result"][ii]["Rights"] = atoi(sd[4].c_str());
root["result"][ii]["RemoteSharing"] = atoi(sd[5].c_str());
root["result"][ii]["TabsEnabled"] = atoi(sd[6].c_str());
ii++;
}
}
}
void CWebServer::RType_Mobiles(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
urights = static_cast<int>(m_users[iUser].userrights);
}
if (urights < 2)
return;
root["status"] = "OK";
root["title"] = "Mobiles";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Active, Name, UUID, LastUpdate, DeviceType FROM MobileDevices ORDER BY Name ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Enabled"] = (sd[1] == "1") ? "true" : "false";
root["result"][ii]["Name"] = sd[2];
root["result"][ii]["UUID"] = sd[3];
root["result"][ii]["LastUpdate"] = sd[4];
root["result"][ii]["DeviceType"] = sd[5];
ii++;
}
}
}
void CWebServer::Cmd_SetSetpoint(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int iUser = -1;
int urights = 3;
if (bHaveUser)
{
iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
}
}
if (urights < 1)
return;
std::string idx = request::findValue(&req, "idx");
std::string setpoint = request::findValue(&req, "setpoint");
if (
(idx.empty()) ||
(setpoint.empty())
)
return;
root["status"] = "OK";
root["title"] = "SetSetpoint";
if (iUser != -1)
{
_log.Log(LOG_STATUS, "User: %s initiated a SetPoint command", m_users[iUser].Username.c_str());
}
m_mainworker.SetSetPoint(idx, static_cast<float>(atof(setpoint.c_str())));
}
void CWebServer::Cmd_GetSceneActivations(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetSceneActivations";
std::vector<std::vector<std::string> > result, result2;
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID==%q)", idx.c_str());
if (result.empty())
return;
int ii = 0;
std::string Activators = result[0][0];
int SceneType = atoi(result[0][1].c_str());
if (!Activators.empty())
{
//Get Activator device names
std::vector<std::string> arrayActivators;
StringSplit(Activators, ";", arrayActivators);
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
int sCode = 0;
if (arrayCode.size() == 2)
{
sCode = atoi(arrayCode[1].c_str());
}
result2 = m_sql.safe_query("SELECT Name, [Type], SubType, SwitchType FROM DeviceStatus WHERE (ID==%q)", sID.c_str());
if (!result2.empty())
{
std::vector<std::string> sd = result2[0];
std::string lstatus = "-";
if ((SceneType == 0) && (arrayCode.size() == 2))
{
unsigned char devType = (unsigned char)atoi(sd[1].c_str());
unsigned char subType = (unsigned char)atoi(sd[2].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(sd[3].c_str());
int nValue = sCode;
std::string sValue = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(devType, subType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
}
uint64_t dID = std::strtoull(sID.c_str(), nullptr, 10);
root["result"][ii]["idx"] = dID;
root["result"][ii]["name"] = sd[0];
root["result"][ii]["code"] = sCode;
root["result"][ii]["codestr"] = lstatus;
ii++;
}
}
}
}
void CWebServer::Cmd_AddSceneCode(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sceneidx = request::findValue(&req, "sceneidx");
std::string idx = request::findValue(&req, "idx");
std::string cmnd = request::findValue(&req, "cmnd");
if (
(sceneidx.empty()) ||
(idx.empty()) ||
(cmnd.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddSceneCode";
//First check if we do not already have this device as activation code
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID==%q)", sceneidx.c_str());
if (result.empty())
return;
std::string Activators = result[0][0];
unsigned char scenetype = atoi(result[0][1].c_str());
if (!Activators.empty())
{
//Get Activator device names
std::vector<std::string> arrayActivators;
StringSplit(Activators, ";", arrayActivators);
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
std::string sCode = "";
if (arrayCode.size() == 2)
{
sCode = arrayCode[1];
}
if (sID == idx)
{
if (scenetype == 1)
return; //Group does not work with separate codes, so already there
if (sCode == cmnd)
return; //same code, already there!
}
}
}
if (!Activators.empty())
Activators += ";";
Activators += idx;
if (scenetype == 0)
{
Activators += ":" + cmnd;
}
m_sql.safe_query("UPDATE Scenes SET Activators='%q' WHERE (ID==%q)", Activators.c_str(), sceneidx.c_str());
}
void CWebServer::Cmd_RemoveSceneCode(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sceneidx = request::findValue(&req, "sceneidx");
std::string idx = request::findValue(&req, "idx");
std::string code = request::findValue(&req, "code");
if (
(idx.empty()) ||
(sceneidx.empty()) ||
(code.empty())
)
return;
root["status"] = "OK";
root["title"] = "RemoveSceneCode";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID==%q)", sceneidx.c_str());
if (result.empty())
return;
std::string Activators = result[0][0];
int SceneType = atoi(result[0][1].c_str());
if (!Activators.empty())
{
//Get Activator device names
std::vector<std::string> arrayActivators;
StringSplit(Activators, ";", arrayActivators);
std::string newActivation = "";
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
std::string sCode = "";
if (arrayCode.size() == 2)
{
sCode = arrayCode[1];
}
bool bFound = false;
if (sID == idx)
{
if ((SceneType == 1) || (sCode.empty()))
{
bFound = true;
}
else
{
//Also check the code
bFound = (sCode == code);
}
}
if (!bFound)
{
if (!newActivation.empty())
newActivation += ";";
newActivation += sID;
if ((SceneType == 0) && (!sCode.empty()))
{
newActivation += ":" + sCode;
}
}
}
if (Activators != newActivation)
{
m_sql.safe_query("UPDATE Scenes SET Activators='%q' WHERE (ID==%q)", newActivation.c_str(), sceneidx.c_str());
}
}
}
void CWebServer::Cmd_ClearSceneCodes(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sceneidx = request::findValue(&req, "sceneidx");
if (sceneidx.empty())
return;
root["status"] = "OK";
root["title"] = "ClearSceneCode";
m_sql.safe_query("UPDATE Scenes SET Activators='' WHERE (ID==%q)", sceneidx.c_str());
}
void CWebServer::Cmd_GetSerialDevices(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetSerialDevices";
bool bUseDirectPath = false;
std::vector<std::string> serialports = GetSerialPorts(bUseDirectPath);
int ii = 0;
for (const auto & itt : serialports)
{
root["result"][ii]["name"] = itt;
root["result"][ii]["value"] = ii;
ii++;
}
}
void CWebServer::Cmd_GetDevicesList(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetDevicesList";
int ii = 0;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name FROM DeviceStatus WHERE (Used == 1) ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["name"] = sd[1];
root["result"][ii]["value"] = sd[0];
ii++;
}
}
}
void CWebServer::Post_UploadCustomIcon(WebEmSession & session, const request& req, reply & rep)
{
Json::Value root;
root["title"] = "UploadCustomIcon";
root["status"] = "ERROR";
root["error"] = "Invalid";
//Only admin user allowed
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string zipfile = request::findValue(&req, "file");
if (zipfile != "")
{
std::string ErrorMessage;
bool bOK = m_sql.InsertCustomIconFromZip(zipfile, ErrorMessage);
if (bOK)
{
root["status"] = "OK";
}
else
{
root["status"] = "ERROR";
root["error"] = ErrorMessage;
}
}
std::string jcallback = request::findValue(&req, "jsoncallback");
if (jcallback.size() == 0) {
reply::set_content(&rep, root.toStyledString());
return;
}
reply::set_content(&rep, "var data=" + root.toStyledString() + '\n' + jcallback + "(data);");
}
void CWebServer::Cmd_GetCustomIconSet(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetCustomIconSet";
int ii = 0;
for (const auto & itt : m_custom_light_icons)
{
if (itt.idx >= 100)
{
std::string IconFile16 = "images/" + itt.RootFile + ".png";
std::string IconFile48On = "images/" + itt.RootFile + "48_On.png";
std::string IconFile48Off = "images/" + itt.RootFile + "48_Off.png";
root["result"][ii]["idx"] = itt.idx - 100;
root["result"][ii]["Title"] = itt.Title;
root["result"][ii]["Description"] = itt.Description;
root["result"][ii]["IconFile16"] = IconFile16;
root["result"][ii]["IconFile48On"] = IconFile48On;
root["result"][ii]["IconFile48Off"] = IconFile48Off;
ii++;
}
}
}
void CWebServer::Cmd_DeleteCustomIcon(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
if (sidx.empty())
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "DeleteCustomIcon";
m_sql.safe_query("DELETE FROM CustomImages WHERE (ID == %d)", idx);
//Delete icons file from disk
for (const auto & itt : m_custom_light_icons)
{
if (itt.idx == idx + 100)
{
std::string IconFile16 = szWWWFolder + "/images/" + itt.RootFile + ".png";
std::string IconFile48On = szWWWFolder + "/images/" + itt.RootFile + "48_On.png";
std::string IconFile48Off = szWWWFolder + "/images/" + itt.RootFile + "48_Off.png";
std::remove(IconFile16.c_str());
std::remove(IconFile48On.c_str());
std::remove(IconFile48Off.c_str());
break;
}
}
ReloadCustomSwitchIcons();
}
void CWebServer::Cmd_UpdateCustomIcon(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string sname = request::findValue(&req, "name");
std::string sdescription = request::findValue(&req, "description");
if (
(sidx.empty()) ||
(sname.empty()) ||
(sdescription.empty())
)
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "UpdateCustomIcon";
m_sql.safe_query("UPDATE CustomImages SET Name='%q', Description='%q' WHERE (ID == %d)", sname.c_str(), sdescription.c_str(), idx);
ReloadCustomSwitchIcons();
}
void CWebServer::Cmd_RenameDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string sname = request::findValue(&req, "name");
if (
(sidx.empty()) ||
(sname.empty())
)
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "RenameDevice";
m_sql.safe_query("UPDATE DeviceStatus SET Name='%q' WHERE (ID == %d)", sname.c_str(), idx);
uint64_t ullidx = std::strtoull(sidx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.WWWUpdateSingleState(ullidx, sname, m_mainworker.m_eventsystem.REASON_DEVICE);
#ifdef ENABLE_PYTHON
// Notify plugin framework about the change
m_mainworker.m_pluginsystem.DeviceModified(idx);
#endif
}
void CWebServer::Cmd_RenameScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string sname = request::findValue(&req, "name");
if (
(sidx.empty()) ||
(sname.empty())
)
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "RenameScene";
m_sql.safe_query("UPDATE Scenes SET Name='%q' WHERE (ID == %d)", sname.c_str(), idx);
uint64_t ullidx = std::strtoull(sidx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.WWWUpdateSingleState(ullidx, sname, m_mainworker.m_eventsystem.REASON_SCENEGROUP);
}
void CWebServer::Cmd_SetUnused(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
if (sidx.empty())
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "SetUnused";
m_sql.safe_query("UPDATE DeviceStatus SET Used=0 WHERE (ID == %d)", idx);
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.RemoveSingleState(idx, m_mainworker.m_eventsystem.REASON_DEVICE);
#ifdef ENABLE_PYTHON
// Notify plugin framework about the change
m_mainworker.m_pluginsystem.DeviceModified(idx);
#endif
}
void CWebServer::Cmd_AddLogMessage(WebEmSession & session, const request& req, Json::Value &root)
{
std::string smessage = request::findValue(&req, "message");
if (smessage.empty())
return;
root["status"] = "OK";
root["title"] = "AddLogMessage";
_log.Log(LOG_STATUS, "%s", smessage.c_str());
}
void CWebServer::Cmd_ClearShortLog(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "ClearShortLog";
_log.Log(LOG_STATUS, "Clearing Short Log...");
m_sql.ClearShortLog();
_log.Log(LOG_STATUS, "Short Log Cleared!");
}
void CWebServer::Cmd_VacuumDatabase(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "VacuumDatabase";
m_sql.VacuumDatabase();
}
void CWebServer::Cmd_AddMobileDevice(WebEmSession & session, const request& req, Json::Value &root)
{
std::string suuid = request::findValue(&req, "uuid");
std::string ssenderid = request::findValue(&req, "senderid");
std::string sname = request::findValue(&req, "name");
std::string sdevtype = request::findValue(&req, "devicetype");
std::string sactive = request::findValue(&req, "active");
if (
(suuid.empty()) ||
(ssenderid.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddMobileDevice";
if (sactive.empty())
sactive = "1";
int iActive = (sactive == "1") ? 1 : 0;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, DeviceType FROM MobileDevices WHERE (UUID=='%q')", suuid.c_str());
if (result.empty())
{
//New
m_sql.safe_query("INSERT INTO MobileDevices (Active,UUID,SenderID,Name,DeviceType) VALUES (%d,'%q','%q','%q','%q')",
iActive,
suuid.c_str(),
ssenderid.c_str(),
sname.c_str(),
sdevtype.c_str());
}
else
{
//Update
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
m_sql.safe_query("UPDATE MobileDevices SET Active=%d, SenderID='%q', LastUpdate='%04d-%02d-%02d %02d:%02d:%02d' WHERE (UUID == '%q')",
iActive,
ssenderid.c_str(),
ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday, ltime.tm_hour, ltime.tm_min, ltime.tm_sec,
suuid.c_str()
);
std::string dname = result[0][1];
std::string ddevtype = result[0][2];
if (dname.empty() || ddevtype.empty())
{
m_sql.safe_query("UPDATE MobileDevices SET Name='%q', DeviceType='%q' WHERE (UUID == '%q')",
sname.c_str(), sdevtype.c_str(),
suuid.c_str()
);
}
}
}
void CWebServer::Cmd_UpdateMobileDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string enabled = request::findValue(&req, "enabled");
std::string name = request::findValue(&req, "name");
if (
(sidx.empty()) ||
(enabled.empty()) ||
(name.empty())
)
return;
uint64_t idx = std::strtoull(sidx.c_str(), nullptr, 10);
m_sql.safe_query("UPDATE MobileDevices SET Name='%q', Active=%d WHERE (ID==%" PRIu64 ")",
name.c_str(), (enabled == "true") ? 1 : 0, idx);
root["status"] = "OK";
root["title"] = "UpdateMobile";
}
void CWebServer::Cmd_DeleteMobileDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string suuid = request::findValue(&req, "uuid");
if (suuid.empty())
return;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM MobileDevices WHERE (UUID=='%q')", suuid.c_str());
if (result.empty())
return;
m_sql.safe_query("DELETE FROM MobileDevices WHERE (UUID == '%q')", suuid.c_str());
root["status"] = "OK";
root["title"] = "DeleteMobileDevice";
}
void CWebServer::RType_GetTransfers(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetTransfers";
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type, SubType FROM DeviceStatus WHERE (ID==%" PRIu64 ")",
idx);
if (!result.empty())
{
int dType = atoi(result[0][0].c_str());
if (
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_HUM)
)
{
result = m_sql.safe_query(
"SELECT ID, Name FROM DeviceStatus WHERE (Type=='%q') AND (ID!=%" PRIu64 ")",
result[0][0].c_str(), idx);
}
else
{
result = m_sql.safe_query(
"SELECT ID, Name FROM DeviceStatus WHERE (Type=='%q') AND (SubType=='%q') AND (ID!=%" PRIu64 ")",
result[0][0].c_str(), result[0][1].c_str(), idx);
}
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
ii++;
}
}
}
//Will transfer Newest sensor log to OLD sensor,
//then set the HardwareID/DeviceID/Unit/Name/Type/Subtype/Unit for the OLD sensor to the NEW sensor ID/Type/Subtype/Unit
//then delete the NEW sensor
void CWebServer::RType_TransferDevice(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sidx = request::findValue(&req, "idx");
if (sidx.empty())
return;
std::string newidx = request::findValue(&req, "newidx");
if (newidx.empty())
return;
std::vector<std::vector<std::string> > result;
//Check which device is newer
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
struct tm LastUpdateTime_A;
struct tm LastUpdateTime_B;
result = m_sql.safe_query(
"SELECT A.LastUpdate, B.LastUpdate FROM DeviceStatus as A, DeviceStatus as B WHERE (A.ID == '%q') AND (B.ID == '%q')",
sidx.c_str(), newidx.c_str());
if (result.empty())
return;
std::string sLastUpdate_A = result[0][0];
std::string sLastUpdate_B = result[0][1];
time_t timeA, timeB;
ParseSQLdatetime(timeA, LastUpdateTime_A, sLastUpdate_A, tm1.tm_isdst);
ParseSQLdatetime(timeB, LastUpdateTime_B, sLastUpdate_B, tm1.tm_isdst);
if (timeA < timeB)
{
//Swap idx with newidx
sidx.swap(newidx);
}
result = m_sql.safe_query(
"SELECT HardwareID, DeviceID, Unit, Name, Type, SubType, SignalLevel, BatteryLevel, nValue, sValue FROM DeviceStatus WHERE (ID == '%q')",
newidx.c_str());
if (result.empty())
return;
root["status"] = "OK";
root["title"] = "TransferDevice";
//transfer device logs (new to old)
m_sql.TransferDevice(newidx, sidx);
//now delete the NEW device
m_sql.DeleteDevices(newidx);
m_mainworker.m_scheduler.ReloadSchedules();
}
void CWebServer::RType_Notifications(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Notifications";
int ii = 0;
//Add known notification systems
for (const auto & ittNotifiers : m_notifications.m_notifiers)
{
root["notifiers"][ii]["name"] = ittNotifiers.first;
root["notifiers"][ii]["description"] = ittNotifiers.first;
ii++;
}
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<_tNotification> notifications = m_notifications.GetNotifications(idx);
if (notifications.size() > 0)
{
ii = 0;
for (const auto & itt : notifications)
{
root["result"][ii]["idx"] = itt.ID;
std::string sParams = itt.Params;
if (sParams.empty()) {
sParams = "S";
}
root["result"][ii]["Params"] = sParams;
root["result"][ii]["Priority"] = itt.Priority;
root["result"][ii]["SendAlways"] = itt.SendAlways;
root["result"][ii]["CustomMessage"] = itt.CustomMessage;
root["result"][ii]["ActiveSystems"] = itt.ActiveSystems;
ii++;
}
}
}
void CWebServer::RType_GetSharedUserDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetSharedUserDevices";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == '%q')", idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["DeviceRowIdx"] = sd[0];
ii++;
}
}
}
void CWebServer::RType_SetSharedUserDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
std::string userdevices = request::findValue(&req, "devices");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "SetSharedUserDevices";
std::vector<std::string> strarray;
StringSplit(userdevices, ";", strarray);
//First delete all devices for this user, then add the (new) onces
m_sql.safe_query("DELETE FROM SharedDevices WHERE (SharedUserID == '%q')", idx.c_str());
int nDevices = static_cast<int>(strarray.size());
for (int ii = 0; ii < nDevices; ii++)
{
m_sql.safe_query("INSERT INTO SharedDevices (SharedUserID,DeviceRowID) VALUES ('%q','%q')", idx.c_str(), strarray[ii].c_str());
}
LoadUsers();
}
void CWebServer::RType_SetUsed(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string deviceid = request::findValue(&req, "deviceid");
std::string name = request::findValue(&req, "name");
std::string description = request::findValue(&req, "description");
std::string sused = request::findValue(&req, "used");
std::string sswitchtype = request::findValue(&req, "switchtype");
std::string maindeviceidx = request::findValue(&req, "maindeviceidx");
std::string addjvalue = request::findValue(&req, "addjvalue");
std::string addjmulti = request::findValue(&req, "addjmulti");
std::string addjvalue2 = request::findValue(&req, "addjvalue2");
std::string addjmulti2 = request::findValue(&req, "addjmulti2");
std::string setPoint = request::findValue(&req, "setpoint");
std::string state = request::findValue(&req, "state");
std::string mode = request::findValue(&req, "mode");
std::string until = request::findValue(&req, "until");
std::string clock = request::findValue(&req, "clock");
std::string tmode = request::findValue(&req, "tmode");
std::string fmode = request::findValue(&req, "fmode");
std::string sCustomImage = request::findValue(&req, "customimage");
std::string strunit = request::findValue(&req, "unit");
std::string strParam1 = base64_decode(request::findValue(&req, "strparam1"));
std::string strParam2 = base64_decode(request::findValue(&req, "strparam2"));
std::string tmpstr = request::findValue(&req, "protected");
bool bHasstrParam1 = request::hasValue(&req, "strparam1");
int iProtected = (tmpstr == "true") ? 1 : 0;
std::string sOptions = base64_decode(request::findValue(&req, "options"));
std::string devoptions = CURLEncode::URLDecode(request::findValue(&req, "devoptions"));
std::string EnergyMeterMode = CURLEncode::URLDecode(request::findValue(&req, "EnergyMeterMode"));
char szTmp[200];
bool bHaveUser = (session.username != "");
int iUser = -1;
if (bHaveUser)
{
iUser = FindUser(session.username.c_str());
}
int switchtype = -1;
if (sswitchtype != "")
switchtype = atoi(sswitchtype.c_str());
if ((idx.empty()) || (sused.empty()))
return;
int used = (sused == "true") ? 1 : 0;
if (maindeviceidx != "")
used = 0;
int CustomImage = 0;
if (sCustomImage != "")
CustomImage = atoi(sCustomImage.c_str());
//Strip trailing spaces in 'name'
name = stdstring_trim(name);
//Strip trailing spaces in 'description'
description = stdstring_trim(description);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type,SubType,HardwareID FROM DeviceStatus WHERE (ID == '%q')", idx.c_str());
if (result.empty())
return;
std::vector<std::string> sd = result[0];
unsigned char dType = atoi(sd[0].c_str());
//unsigned char dSubType=atoi(sd[1].c_str());
int HwdID = atoi(sd[2].c_str());
std::string sHwdID = sd[2];
if (setPoint != "" || state != "")
{
double tempcelcius = atof(setPoint.c_str());
if (m_sql.m_tempunit == TEMPUNIT_F)
{
//Convert back to Celsius
tempcelcius = ConvertToCelsius(tempcelcius);
}
sprintf(szTmp, "%.2f", tempcelcius);
if (dType != pTypeEvohomeZone && dType != pTypeEvohomeWater)//sql update now done in setsetpoint for evohome devices
{
m_sql.safe_query("UPDATE DeviceStatus SET Used=%d, sValue='%q' WHERE (ID == '%q')",
used, szTmp, idx.c_str());
}
}
if (name.empty())
{
m_sql.safe_query("UPDATE DeviceStatus SET Used=%d WHERE (ID == '%q')",
used, idx.c_str());
}
else
{
if (switchtype == -1)
{
m_sql.safe_query("UPDATE DeviceStatus SET Used=%d, Name='%q', Description='%q' WHERE (ID == '%q')",
used, name.c_str(), description.c_str(), idx.c_str());
}
else
{
m_sql.safe_query(
"UPDATE DeviceStatus SET Used=%d, Name='%q', Description='%q', SwitchType=%d, CustomImage=%d WHERE (ID == '%q')",
used, name.c_str(), description.c_str(), switchtype, CustomImage, idx.c_str());
}
}
if (bHasstrParam1)
{
m_sql.safe_query("UPDATE DeviceStatus SET StrParam1='%q', StrParam2='%q' WHERE (ID == '%q')",
strParam1.c_str(), strParam2.c_str(), idx.c_str());
}
m_sql.safe_query("UPDATE DeviceStatus SET Protected=%d WHERE (ID == '%q')", iProtected, idx.c_str());
if (!setPoint.empty() || !state.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a SetPoint command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
if (dType == pTypeEvohomeWater)
m_mainworker.SetSetPoint(idx, (state == "On") ? 1.0f : 0.0f, mode, until);//FIXME float not guaranteed precise?
else if (dType == pTypeEvohomeZone)
m_mainworker.SetSetPoint(idx, static_cast<float>(atof(setPoint.c_str())), mode, until);
else
m_mainworker.SetSetPoint(idx, static_cast<float>(atof(setPoint.c_str())));
}
else if (!clock.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a SetClock command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
m_mainworker.SetClock(idx, clock);
}
else if (!tmode.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a Thermostat Mode command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
m_mainworker.SetZWaveThermostatMode(idx, atoi(tmode.c_str()));
}
else if (!fmode.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a Thermostat Fan Mode command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
m_mainworker.SetZWaveThermostatFanMode(idx, atoi(fmode.c_str()));
}
if (!strunit.empty())
{
bool bUpdateUnit = true;
#ifdef ENABLE_PYTHON
//check if HW is plugin
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type FROM Hardware WHERE (ID == %d)", HwdID);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
_eHardwareTypes Type = (_eHardwareTypes)atoi(sd[0].c_str());
if (Type == HTYPE_PythonPlugin)
{
bUpdateUnit = false;
_log.Log(LOG_ERROR, "CWebServer::RType_SetUsed: Not allowed to change unit of device owned by plugin %u!", HwdID);
}
}
#endif
if (bUpdateUnit)
{
m_sql.safe_query("UPDATE DeviceStatus SET Unit='%q' WHERE (ID == '%q')",
strunit.c_str(), idx.c_str());
}
}
//FIXME evohome ...we need the zone id to update the correct zone...but this should be ok as a generic call?
if (!deviceid.empty())
{
m_sql.safe_query("UPDATE DeviceStatus SET DeviceID='%q' WHERE (ID == '%q')",
deviceid.c_str(), idx.c_str());
}
if (!addjvalue.empty())
{
double faddjvalue = atof(addjvalue.c_str());
m_sql.safe_query("UPDATE DeviceStatus SET AddjValue=%f WHERE (ID == '%q')",
faddjvalue, idx.c_str());
}
if (!addjmulti.empty())
{
double faddjmulti = atof(addjmulti.c_str());
if (faddjmulti == 0)
faddjmulti = 1;
m_sql.safe_query("UPDATE DeviceStatus SET AddjMulti=%f WHERE (ID == '%q')",
faddjmulti, idx.c_str());
}
if (!addjvalue2.empty())
{
double faddjvalue2 = atof(addjvalue2.c_str());
m_sql.safe_query("UPDATE DeviceStatus SET AddjValue2=%f WHERE (ID == '%q')",
faddjvalue2, idx.c_str());
}
if (!addjmulti2.empty())
{
double faddjmulti2 = atof(addjmulti2.c_str());
if (faddjmulti2 == 0)
faddjmulti2 = 1;
m_sql.safe_query("UPDATE DeviceStatus SET AddjMulti2=%f WHERE (ID == '%q')",
faddjmulti2, idx.c_str());
}
if (!EnergyMeterMode.empty())
{
auto options = m_sql.GetDeviceOptions(idx);
options["EnergyMeterMode"] = EnergyMeterMode;
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_sql.SetDeviceOptions(ullidx, options);
}
if (!devoptions.empty())
{
m_sql.safe_query("UPDATE DeviceStatus SET Options='%q' WHERE (ID == '%q')", devoptions.c_str(), idx.c_str());
}
if (used == 0)
{
bool bRemoveSubDevices = (request::findValue(&req, "RemoveSubDevices") == "true");
if (bRemoveSubDevices)
{
//if this device was a slave device, remove it
m_sql.safe_query("DELETE FROM LightSubDevices WHERE (DeviceRowID == '%q')", idx.c_str());
}
m_sql.safe_query("DELETE FROM LightSubDevices WHERE (ParentID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM Timers WHERE (DeviceRowID == '%q')", idx.c_str());
}
// Save device options
if (!sOptions.empty())
{
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_sql.SetDeviceOptions(ullidx, m_sql.BuildDeviceOptions(sOptions, false));
}
if (maindeviceidx != "")
{
if (maindeviceidx != idx)
{
//this is a sub device for another light/switch
//first check if it is not already a sub device
result = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q') AND (ParentID =='%q')",
idx.c_str(), maindeviceidx.c_str());
if (result.empty())
{
//no it is not, add it
m_sql.safe_query(
"INSERT INTO LightSubDevices (DeviceRowID, ParentID) VALUES ('%q','%q')",
idx.c_str(),
maindeviceidx.c_str()
);
}
}
}
if ((used == 0) && (maindeviceidx.empty()))
{
//really remove it, including log etc
m_sql.DeleteDevices(idx);
}
else
{
#ifdef ENABLE_PYTHON
// Notify plugin framework about the change
m_mainworker.m_pluginsystem.DeviceModified(atoi(idx.c_str()));
#endif
}
if (!result.empty())
{
root["status"] = "OK";
root["title"] = "SetUsed";
}
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentStates();
}
void CWebServer::RType_Settings(WebEmSession & session, const request& req, Json::Value &root)
{
std::vector<std::vector<std::string> > result;
char szTmp[100];
result = m_sql.safe_query("SELECT Key, nValue, sValue FROM Preferences");
if (result.empty())
return;
root["status"] = "OK";
root["title"] = "settings";
#ifndef NOCLOUD
root["cloudenabled"] = true;
#else
root["cloudenabled"] = false;
#endif
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string Key = sd[0];
int nValue = atoi(sd[1].c_str());
std::string sValue = sd[2];
if (Key == "Location")
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
root["Location"]["Latitude"] = strarray[0];
root["Location"]["Longitude"] = strarray[1];
}
}
/* RK: notification settings */
if (m_notifications.IsInConfig(Key)) {
if (sValue.empty() && nValue > 0) {
root[Key] = nValue;
}
else {
root[Key] = sValue;
}
}
else if (Key == "DashboardType")
{
root["DashboardType"] = nValue;
}
else if (Key == "MobileType")
{
root["MobileType"] = nValue;
}
else if (Key == "LightHistoryDays")
{
root["LightHistoryDays"] = nValue;
}
else if (Key == "5MinuteHistoryDays")
{
root["ShortLogDays"] = nValue;
}
else if (Key == "ShortLogInterval")
{
root["ShortLogInterval"] = nValue;
}
else if (Key == "WebUserName")
{
root["WebUserName"] = base64_decode(sValue);
}
//else if (Key == "WebPassword")
//{
// root["WebPassword"] = sValue;
//}
else if (Key == "SecPassword")
{
root["SecPassword"] = sValue;
}
else if (Key == "ProtectionPassword")
{
root["ProtectionPassword"] = sValue;
}
else if (Key == "WebLocalNetworks")
{
root["WebLocalNetworks"] = sValue;
}
else if (Key == "WebRemoteProxyIPs")
{
root["WebRemoteProxyIPs"] = sValue;
}
else if (Key == "RandomTimerFrame")
{
root["RandomTimerFrame"] = nValue;
}
else if (Key == "MeterDividerEnergy")
{
root["EnergyDivider"] = nValue;
}
else if (Key == "MeterDividerGas")
{
root["GasDivider"] = nValue;
}
else if (Key == "MeterDividerWater")
{
root["WaterDivider"] = nValue;
}
else if (Key == "ElectricVoltage")
{
root["ElectricVoltage"] = nValue;
}
else if (Key == "CM113DisplayType")
{
root["CM113DisplayType"] = nValue;
}
else if (Key == "UseAutoUpdate")
{
root["UseAutoUpdate"] = nValue;
}
else if (Key == "UseAutoBackup")
{
root["UseAutoBackup"] = nValue;
}
else if (Key == "Rego6XXType")
{
root["Rego6XXType"] = nValue;
}
else if (Key == "CostEnergy")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergy"] = szTmp;
}
else if (Key == "CostEnergyT2")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergyT2"] = szTmp;
}
else if (Key == "CostEnergyR1")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergyR1"] = szTmp;
}
else if (Key == "CostEnergyR2")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergyR2"] = szTmp;
}
else if (Key == "CostGas")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostGas"] = szTmp;
}
else if (Key == "CostWater")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostWater"] = szTmp;
}
else if (Key == "ActiveTimerPlan")
{
root["ActiveTimerPlan"] = nValue;
}
else if (Key == "DoorbellCommand")
{
root["DoorbellCommand"] = nValue;
}
else if (Key == "SmartMeterType")
{
root["SmartMeterType"] = nValue;
}
else if (Key == "EnableTabFloorplans")
{
root["EnableTabFloorplans"] = nValue;
}
else if (Key == "EnableTabLights")
{
root["EnableTabLights"] = nValue;
}
else if (Key == "EnableTabTemp")
{
root["EnableTabTemp"] = nValue;
}
else if (Key == "EnableTabWeather")
{
root["EnableTabWeather"] = nValue;
}
else if (Key == "EnableTabUtility")
{
root["EnableTabUtility"] = nValue;
}
else if (Key == "EnableTabScenes")
{
root["EnableTabScenes"] = nValue;
}
else if (Key == "EnableTabCustom")
{
root["EnableTabCustom"] = nValue;
}
else if (Key == "NotificationSensorInterval")
{
root["NotificationSensorInterval"] = nValue;
}
else if (Key == "NotificationSwitchInterval")
{
root["NotificationSwitchInterval"] = nValue;
}
else if (Key == "RemoteSharedPort")
{
root["RemoteSharedPort"] = nValue;
}
else if (Key == "Language")
{
root["Language"] = sValue;
}
else if (Key == "Title")
{
root["Title"] = sValue;
}
else if (Key == "WindUnit")
{
root["WindUnit"] = nValue;
}
else if (Key == "TempUnit")
{
root["TempUnit"] = nValue;
}
else if (Key == "WeightUnit")
{
root["WeightUnit"] = nValue;
}
else if (Key == "AuthenticationMethod")
{
root["AuthenticationMethod"] = nValue;
}
else if (Key == "ReleaseChannel")
{
root["ReleaseChannel"] = nValue;
}
else if (Key == "RaspCamParams")
{
root["RaspCamParams"] = sValue;
}
else if (Key == "UVCParams")
{
root["UVCParams"] = sValue;
}
else if (Key == "AcceptNewHardware")
{
root["AcceptNewHardware"] = nValue;
}
else if (Key == "HideDisabledHardwareSensors")
{
root["HideDisabledHardwareSensors"] = nValue;
}
else if (Key == "ShowUpdateEffect")
{
root["ShowUpdateEffect"] = nValue;
}
else if (Key == "DegreeDaysBaseTemperature")
{
root["DegreeDaysBaseTemperature"] = sValue;
}
else if (Key == "EnableEventScriptSystem")
{
root["EnableEventScriptSystem"] = nValue;
}
else if (Key == "DisableDzVentsSystem")
{
root["DisableDzVentsSystem"] = nValue;
}
else if (Key == "DzVentsLogLevel")
{
root["DzVentsLogLevel"] = nValue;
}
else if (Key == "LogEventScriptTrigger")
{
root["LogEventScriptTrigger"] = nValue;
}
else if (Key == "(1WireSensorPollPeriod")
{
root["1WireSensorPollPeriod"] = nValue;
}
else if (Key == "(1WireSwitchPollPeriod")
{
root["1WireSwitchPollPeriod"] = nValue;
}
else if (Key == "SecOnDelay")
{
root["SecOnDelay"] = nValue;
}
else if (Key == "AllowWidgetOrdering")
{
root["AllowWidgetOrdering"] = nValue;
}
else if (Key == "FloorplanPopupDelay")
{
root["FloorplanPopupDelay"] = nValue;
}
else if (Key == "FloorplanFullscreenMode")
{
root["FloorplanFullscreenMode"] = nValue;
}
else if (Key == "FloorplanAnimateZoom")
{
root["FloorplanAnimateZoom"] = nValue;
}
else if (Key == "FloorplanShowSensorValues")
{
root["FloorplanShowSensorValues"] = nValue;
}
else if (Key == "FloorplanShowSwitchValues")
{
root["FloorplanShowSwitchValues"] = nValue;
}
else if (Key == "FloorplanShowSceneNames")
{
root["FloorplanShowSceneNames"] = nValue;
}
else if (Key == "FloorplanRoomColour")
{
root["FloorplanRoomColour"] = sValue;
}
else if (Key == "FloorplanActiveOpacity")
{
root["FloorplanActiveOpacity"] = nValue;
}
else if (Key == "FloorplanInactiveOpacity")
{
root["FloorplanInactiveOpacity"] = nValue;
}
else if (Key == "SensorTimeout")
{
root["SensorTimeout"] = nValue;
}
else if (Key == "BatteryLowNotification")
{
root["BatterLowLevel"] = nValue;
}
else if (Key == "WebTheme")
{
root["WebTheme"] = sValue;
}
#ifndef NOCLOUD
else if (Key == "MyDomoticzInstanceId") {
root["MyDomoticzInstanceId"] = sValue;
}
else if (Key == "MyDomoticzUserId") {
root["MyDomoticzUserId"] = sValue;
}
else if (Key == "MyDomoticzPassword") {
root["MyDomoticzPassword"] = sValue;
}
else if (Key == "MyDomoticzSubsystems") {
root["MyDomoticzSubsystems"] = nValue;
}
#endif
else if (Key == "MyDomoticzSubsystems") {
root["MyDomoticzSubsystems"] = nValue;
}
else if (Key == "SendErrorsAsNotification") {
root["SendErrorsAsNotification"] = nValue;
}
else if (Key == "DeltaTemperatureLog") {
root[Key] = sValue;
}
else if (Key == "IFTTTEnabled") {
root["IFTTTEnabled"] = nValue;
}
else if (Key == "IFTTTAPI") {
root["IFTTTAPI"] = sValue;
}
}
}
void CWebServer::RType_LightLog(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
//First get Device Type/SubType
result = m_sql.safe_query("SELECT Type, SubType, SwitchType, Options FROM DeviceStatus WHERE (ID == %" PRIu64 ")",
idx);
if (result.empty())
return;
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(result[0][2].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(result[0][3].c_str());
if (
(dType != pTypeLighting1) &&
(dType != pTypeLighting2) &&
(dType != pTypeLighting3) &&
(dType != pTypeLighting4) &&
(dType != pTypeLighting5) &&
(dType != pTypeLighting6) &&
(dType != pTypeFan) &&
(dType != pTypeColorSwitch) &&
(dType != pTypeSecurity1) &&
(dType != pTypeSecurity2) &&
(dType != pTypeEvohome) &&
(dType != pTypeEvohomeRelay) &&
(dType != pTypeCurtain) &&
(dType != pTypeBlinds) &&
(dType != pTypeRFY) &&
(dType != pTypeRego6XXValue) &&
(dType != pTypeChime) &&
(dType != pTypeThermostat2) &&
(dType != pTypeThermostat3) &&
(dType != pTypeThermostat4) &&
(dType != pTypeRemote) &&
(dType != pTypeGeneralSwitch) &&
(dType != pTypeHomeConfort) &&
(dType != pTypeFS20) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)))
)
return; //no light device! we should not be here!
root["status"] = "OK";
root["title"] = "LightLog";
result = m_sql.safe_query("SELECT ROWID, nValue, sValue, Date FROM LightingLog WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date DESC", idx);
if (!result.empty())
{
std::map<std::string, std::string> selectorStatuses;
if (switchtype == STYPE_Selector) {
GetSelectorSwitchStatuses(options, selectorStatuses);
}
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int nValue = atoi(sd[1].c_str());
std::string sValue = sd[2];
//skip 0-values in log for MediaPlayers
if ((switchtype == STYPE_Media) && (sValue == "0")) continue;
root["result"][ii]["idx"] = sd[0];
//add light details
std::string lstatus = "";
std::string ldata = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveSelector = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
if (switchtype == STYPE_Media) {
lstatus = sValue;
ldata = lstatus;
}
else if (switchtype == STYPE_Selector)
{
if (ii == 0) {
bHaveSelector = true;
maxDimLevel = selectorStatuses.size();
}
if (!selectorStatuses.empty()) {
std::string sLevel = selectorStatuses[sValue];
ldata = sLevel;
lstatus = "Set Level: " + sLevel;
llevel = atoi(sValue.c_str());
}
}
else {
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
ldata = lstatus;
}
if (ii == 0)
{
root["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["HaveGroupCmd"] = bHaveGroupCmd;
root["HaveSelector"] = bHaveSelector;
}
root["result"][ii]["Date"] = sd[3];
root["result"][ii]["Data"] = ldata;
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["Level"] = llevel;
ii++;
}
}
}
void CWebServer::RType_TextLog(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
root["status"] = "OK";
root["title"] = "TextLog";
result = m_sql.safe_query("SELECT ROWID, sValue, Date FROM LightingLog WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date DESC",
idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Date"] = sd[2];
root["result"][ii]["Data"] = sd[1];
ii++;
}
}
}
void CWebServer::RType_SceneLog(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
root["status"] = "OK";
root["title"] = "SceneLog";
result = m_sql.safe_query("SELECT ROWID, nValue, Date FROM SceneLog WHERE (SceneRowID==%" PRIu64 ") ORDER BY Date DESC", idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int nValue = atoi(sd[1].c_str());
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Date"] = sd[2];
root["result"][ii]["Data"] = (nValue == 0) ? "Off" : "On";
ii++;
}
}
}
void CWebServer::RType_HandleGraph(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
char szTmp[300];
std::string sensor = request::findValue(&req, "sensor");
if (sensor == "")
return;
std::string srange = request::findValue(&req, "range");
if (srange == "")
return;
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
result = m_sql.safe_query("SELECT Type, SubType, SwitchType, AddjValue, AddjMulti, AddjValue2, Options FROM DeviceStatus WHERE (ID == %" PRIu64 ")",
idx);
if (result.empty())
return;
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
_eMeterType metertype = (_eMeterType)atoi(result[0][2].c_str());
if (
(dType == pTypeP1Power) ||
(dType == pTypeENERGY) ||
(dType == pTypePOWER) ||
(dType == pTypeCURRENTENERGY) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
metertype = MTYPE_ENERGY;
}
else if (dType == pTypeP1Gas)
metertype = MTYPE_GAS;
else if ((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))
metertype = MTYPE_COUNTER;
// Special case of managed counter: Usage instead of Value in Meter table, and we don't want to calculate last value
bool bIsManagedCounter = (dType == pTypeGeneral) && (dSubType == sTypeManagedCounter);
double AddjValue = atof(result[0][3].c_str());
double AddjMulti = atof(result[0][4].c_str());
double AddjValue2 = atof(result[0][5].c_str());
std::string sOptions = result[0][6].c_str();
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sOptions);
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::string dbasetable = "";
if (srange == "day") {
if (sensor == "temp")
dbasetable = "Temperature";
else if (sensor == "rain")
dbasetable = "Rain";
else if (sensor == "Percentage")
dbasetable = "Percentage";
else if (sensor == "fan")
dbasetable = "Fan";
else if (sensor == "counter")
{
if ((dType == pTypeP1Power) || (dType == pTypeCURRENT) || (dType == pTypeCURRENTENERGY))
{
dbasetable = "MultiMeter";
}
else
{
dbasetable = "Meter";
}
}
else if ((sensor == "wind") || (sensor == "winddir"))
dbasetable = "Wind";
else if (sensor == "uv")
dbasetable = "UV";
else
return;
}
else
{
//week,year,month
if (sensor == "temp")
dbasetable = "Temperature_Calendar";
else if (sensor == "rain")
dbasetable = "Rain_Calendar";
else if (sensor == "Percentage")
dbasetable = "Percentage_Calendar";
else if (sensor == "fan")
dbasetable = "Fan_Calendar";
else if (sensor == "counter")
{
if (
(dType == pTypeP1Power) ||
(dType == pTypeCURRENT) ||
(dType == pTypeCURRENTENERGY) ||
(dType == pTypeAirQuality) ||
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture)) ||
((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel)) ||
(dType == pTypeLux) ||
(dType == pTypeWEIGHT) ||
(dType == pTypeUsage)
)
dbasetable = "MultiMeter_Calendar";
else
dbasetable = "Meter_Calendar";
}
else if ((sensor == "wind") || (sensor == "winddir"))
dbasetable = "Wind_Calendar";
else if (sensor == "uv")
dbasetable = "UV_Calendar";
else
return;
}
unsigned char tempsign = m_sql.m_tempsign[0];
int iPrev;
if (srange == "day")
{
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Temperature, Chill, Humidity, Barometer, Date, SetPoint FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) ||
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
(dType == pTypeThermostat1) ||
(dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) ||
(dType == pTypeEvohomeWater)
)
{
double tvalue = ConvertTemperature(atof(sd[0].c_str()), tempsign);
root["result"][ii]["te"] = tvalue;
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double tvalue = ConvertTemperature(atof(sd[1].c_str()), tempsign);
root["result"][ii]["ch"] = tvalue;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[2];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[3];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double se = ConvertTemperature(atof(sd[5].c_str()), tempsign);
root["result"][ii]["se"] = se;
}
ii++;
}
}
}
else if (sensor == "Percentage") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Percentage, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (sensor == "fan") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Speed, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (sensor == "counter")
{
if (dType == pTypeP1Power)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Value4, Value5, Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveDeliverd = false;
bool bHaveFirstValue = false;
long long lastUsage1, lastUsage2, lastDeliv1, lastDeliv2;
time_t lastTime = 0;
long long firstUsage1, firstUsage2, firstDeliv1, firstDeliv2;
int nMeterType = 0;
m_sql.GetPreferencesVar("SmartMeterType", nMeterType);
int lastDay = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
if (nMeterType == 0)
{
long long actUsage1 = std::strtoll(sd[0].c_str(), nullptr, 10);
long long actUsage2 = std::strtoll(sd[4].c_str(), nullptr, 10);
long long actDeliv1 = std::strtoll(sd[1].c_str(), nullptr, 10);
long long actDeliv2 = std::strtoll(sd[5].c_str(), nullptr, 10);
actDeliv1 = (actDeliv1 < 10) ? 0 : actDeliv1;
actDeliv2 = (actDeliv2 < 10) ? 0 : actDeliv2;
std::string stime = sd[6];
struct tm ntime;
time_t atime;
ParseSQLdatetime(atime, ntime, stime, -1);
if (lastDay != ntime.tm_mday)
{
lastDay = ntime.tm_mday;
firstUsage1 = actUsage1;
firstUsage2 = actUsage2;
firstDeliv1 = actDeliv1;
firstDeliv2 = actDeliv2;
}
if (bHaveFirstValue)
{
long curUsage1 = (long)(actUsage1 - lastUsage1);
long curUsage2 = (long)(actUsage2 - lastUsage2);
long curDeliv1 = (long)(actDeliv1 - lastDeliv1);
long curDeliv2 = (long)(actDeliv2 - lastDeliv2);
if ((curUsage1 < 0) || (curUsage1 > 100000))
curUsage1 = 0;
if ((curUsage2 < 0) || (curUsage2 > 100000))
curUsage2 = 0;
if ((curDeliv1 < 0) || (curDeliv1 > 100000))
curDeliv1 = 0;
if ((curDeliv2 < 0) || (curDeliv2 > 100000))
curDeliv2 = 0;
float tdiff = static_cast<float>(difftime(atime, lastTime));
if (tdiff == 0)
tdiff = 1;
float tlaps = 3600.0f / tdiff;
curUsage1 *= int(tlaps);
curUsage2 *= int(tlaps);
curDeliv1 *= int(tlaps);
curDeliv2 *= int(tlaps);
root["result"][ii]["d"] = sd[6].substr(0, 16);
if ((curDeliv1 != 0) || (curDeliv2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%ld", curUsage1);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%ld", curUsage2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%ld", curDeliv1);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%ld", curDeliv2);
root["result"][ii]["r2"] = szTmp;
long pUsage1 = (long)(actUsage1 - firstUsage1);
long pUsage2 = (long)(actUsage2 - firstUsage2);
sprintf(szTmp, "%ld", pUsage1 + pUsage2);
root["result"][ii]["eu"] = szTmp;
if (bHaveDeliverd)
{
long pDeliv1 = (long)(actDeliv1 - firstDeliv1);
long pDeliv2 = (long)(actDeliv2 - firstDeliv2);
sprintf(szTmp, "%ld", pDeliv1 + pDeliv2);
root["result"][ii]["eg"] = szTmp;
}
ii++;
}
else
{
bHaveFirstValue = true;
if ((ntime.tm_hour != 0) && (ntime.tm_min != 0))
{
struct tm ltime;
localtime_r(&atime, &tm1);
getNoon(atime, ltime, ntime.tm_year + 1900, ntime.tm_mon + 1, ntime.tm_mday - 1); // We're only interested in finding the date
int year = ltime.tm_year + 1900;
int mon = ltime.tm_mon + 1;
int day = ltime.tm_mday;
sprintf(szTmp, "%04d-%02d-%02d", year, mon, day);
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query(
"SELECT Counter1, Counter2, Counter3, Counter4 FROM Multimeter_Calendar WHERE (DeviceRowID==%" PRIu64 ") AND (Date=='%q')",
idx, szTmp);
if (!result2.empty())
{
std::vector<std::string> sd = result2[0];
firstUsage1 = std::strtoll(sd[0].c_str(), nullptr, 10);
firstDeliv1 = std::strtoll(sd[1].c_str(), nullptr, 10);
firstUsage2 = std::strtoll(sd[2].c_str(), nullptr, 10);
firstDeliv2 = std::strtoll(sd[3].c_str(), nullptr, 10);
lastDay = ntime.tm_mday;
}
}
}
lastUsage1 = actUsage1;
lastUsage2 = actUsage2;
lastDeliv1 = actDeliv1;
lastDeliv2 = actDeliv2;
lastTime = atime;
}
else
{
//this meter has no decimals, so return the use peaks
root["result"][ii]["d"] = sd[6].substr(0, 16);
if (sd[3] != "0")
bHaveDeliverd = true;
root["result"][ii]["v"] = sd[2];
root["result"][ii]["r1"] = sd[3];
ii++;
}
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (dType == pTypeAirQuality)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["co2"] = sd[0];
ii++;
}
}
}
else if ((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness)))
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
float fValue = float(atof(sd[0].c_str())) / vdiv;
if (metertype == 1)
fValue *= 0.6214f;
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue);
else
sprintf(szTmp, "%.1f", fValue);
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
else if ((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (dType == pTypeLux)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["lux"] = sd[0];
ii++;
}
}
}
else if (dType == pTypeWEIGHT)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[0].c_str()) / 10.0f);
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
else if (dType == pTypeUsage)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["u"] = atof(sd[0].c_str()) / 10.0f;
ii++;
}
}
}
else if (dType == pTypeCURRENT)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
if (fval1 != 0)
bHaveL1 = true;
if (fval2 != 0)
bHaveL2 = true;
if (fval3 != 0)
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if (dType == pTypeCURRENTENERGY)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
if (fval1 != 0)
bHaveL1 = true;
if (fval2 != 0)
bHaveL2 = true;
if (fval3 != 0)
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if ((dType == pTypeENERGY) || (dType == pTypePOWER) || (dType == pTypeYouLess) || ((dType == pTypeGeneral) && (dSubType == sTypeKwh)))
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
//First check if we had any usage in the short log, if not, its probably a meter without usage
bool bHaveUsage = true;
result = m_sql.safe_query("SELECT MIN([Usage]), MAX([Usage]) FROM %s WHERE (DeviceRowID==%" PRIu64 ")", dbasetable.c_str(), idx);
if (!result.empty())
{
long long minValue = std::strtoll(result[0][0].c_str(), nullptr, 10);
long long maxValue = std::strtoll(result[0][1].c_str(), nullptr, 10);
if ((minValue == 0) && (maxValue == 0))
{
bHaveUsage = false;
}
}
int ii = 0;
result = m_sql.safe_query("SELECT Value,[Usage], Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
int method = 0;
std::string sMethod = request::findValue(&req, "method");
if (sMethod.size() > 0)
method = atoi(sMethod.c_str());
if (bHaveUsage == false)
method = 0;
if ((dType == pTypeYouLess) && ((metertype == MTYPE_ENERGY) || (metertype == MTYPE_ENERGY_GENERATED)))
method = 1;
if (method != 0)
{
//realtime graph
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
divider /= 100.0f;
}
root["method"] = method;
bool bHaveFirstValue = false;
bool bHaveFirstRealValue = false;
float FirstValue = 0;
long long ulFirstRealValue = 0;
long long ulFirstValue = 0;
long long ulLastValue = 0;
std::string LastDateTime = "";
time_t lastTime = 0;
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator itt;
for (itt = result.begin(); itt!=result.end(); ++itt)
{
std::vector<std::string> sd = *itt;
//If method == 1, provide BOTH hourly and instant usage for combined graph
{
//bars / hour
std::string actDateTimeHour = sd[2].substr(0, 13);
long long actValue = std::strtoll(sd[0].c_str(), nullptr, 10);
if (actValue >= ulLastValue)
ulLastValue = actValue;
if (actDateTimeHour != LastDateTime || ((method == 1) && (itt + 1 == result.end())))
{
if (bHaveFirstValue)
{
//root["result"][ii]["d"] = LastDateTime + (method == 1 ? ":30" : ":00");
//^^ not necessarily bad, but is currently inconsistent with all other day graphs
root["result"][ii]["d"] = LastDateTime + ":00";
long long ulTotalValue = ulLastValue - ulFirstValue;
if (ulTotalValue == 0)
{
//Could be the P1 Gas Meter, only transmits one every 1 a 2 hours
ulTotalValue = ulLastValue - ulFirstRealValue;
}
ulFirstRealValue = ulLastValue;
float TotalValue = float(ulTotalValue);
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii][method == 1 ? "eu" : "v"] = szTmp;
ii++;
}
LastDateTime = actDateTimeHour;
bHaveFirstValue = false;
}
if (!bHaveFirstValue)
{
ulFirstValue = ulLastValue;
bHaveFirstValue = true;
}
if (!bHaveFirstRealValue)
{
bHaveFirstRealValue = true;
ulFirstRealValue = ulLastValue;
}
}
if (method == 1)
{
long long actValue = std::strtoll(sd[1].c_str(), nullptr, 10);
root["result"][ii]["d"] = sd[2].substr(0, 16);
float TotalValue = float(actValue);
if ((dType == pTypeGeneral) && (dSubType == sTypeKwh))
TotalValue /= 10.0f;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
}
else
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int ii = 0;
bool bHaveFirstValue = false;
bool bHaveFirstRealValue = false;
float FirstValue = 0;
unsigned long long ulFirstRealValue = 0;
unsigned long long ulFirstValue = 0;
unsigned long long ulLastValue = 0;
std::string LastDateTime = "";
time_t lastTime = 0;
if (bIsManagedCounter) {
result = m_sql.safe_query("SELECT Usage, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
bHaveFirstValue = true;
bHaveFirstRealValue = true;
}
else {
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
}
int method = 0;
std::string sMethod = request::findValue(&req, "method");
if (sMethod.size() > 0)
method = atoi(sMethod.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
if (method == 0)
{
//bars / hour
unsigned long long actValue = std::strtoull(sd[0].c_str(), nullptr, 10);
std::string actDateTimeHour = sd[1].substr(0, 13);
if (actDateTimeHour != LastDateTime)
{
if (bHaveFirstValue)
{
struct tm ntime;
time_t atime;
if (actDateTimeHour.size() == 10)
actDateTimeHour += " 00";
constructTime(atime, ntime,
atoi(actDateTimeHour.substr(0, 4).c_str()),
atoi(actDateTimeHour.substr(5, 2).c_str()),
atoi(actDateTimeHour.substr(8, 2).c_str()),
atoi(actDateTimeHour.substr(11, 2).c_str()) - 1,
0, 0, -1);
char szTime[50];
sprintf(szTime, "%04d-%02d-%02d %02d:00", ntime.tm_year + 1900, ntime.tm_mon + 1, ntime.tm_mday, ntime.tm_hour);
root["result"][ii]["d"] = szTime;
//float TotalValue = float(actValue - ulFirstValue);
//prevents graph from going crazy if the meter counter resets
float TotalValue = (actValue >= ulFirstValue) ? float(actValue - ulFirstValue) : actValue;
//if (TotalValue != 0)
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
if (!bIsManagedCounter) {
ulFirstValue = actValue;
}
LastDateTime = actDateTimeHour;
}
if (!bHaveFirstValue)
{
ulFirstValue = actValue;
bHaveFirstValue = true;
}
ulLastValue = actValue;
}
else
{
//realtime graph
unsigned long long actValue = std::strtoull(sd[0].c_str(), nullptr, 10);
std::string stime = sd[1];
struct tm ntime;
time_t atime;
ParseSQLdatetime(atime, ntime, stime, -1);
if (bHaveFirstRealValue)
{
long long curValue = actValue - ulLastValue;
float tdiff = static_cast<float>(difftime(atime, lastTime));
if (tdiff == 0)
tdiff = 1;
float tlaps = 3600.0f / tdiff;
curValue *= int(tlaps);
root["result"][ii]["d"] = sd[1].substr(0, 16);
float TotalValue = float(curValue);
//if (TotalValue != 0)
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
else
bHaveFirstRealValue = true;
if (!bIsManagedCounter) {
ulLastValue = actValue;
}
lastTime = atime;
}
}
}
if ((!bIsManagedCounter) && (bHaveFirstValue) && (method == 0))
{
//add last value
root["result"][ii]["d"] = LastDateTime + ":00";
unsigned long long ulTotalValue = ulLastValue - ulFirstValue;
float TotalValue = float(ulTotalValue);
//if (TotalValue != 0)
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int LastHour = -1;
float LastTotalPreviousHour = -1;
float LastValue = -1;
std::string LastDate = "";
result = m_sql.safe_query("SELECT Total, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float ActTotal = static_cast<float>(atof(sd[0].c_str()));
int Hour = atoi(sd[1].substr(11, 2).c_str());
if (Hour != LastHour)
{
if (LastHour != -1)
{
int NextCalculatedHour = (LastHour + 1) % 24;
if (Hour != NextCalculatedHour)
{
//Looks like we have a GAP somewhere, finish the last hour
root["result"][ii]["d"] = LastDate;
double mmval = ActTotal - LastValue;
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
else
{
root["result"][ii]["d"] = sd[1].substr(0, 16);
double mmval = ActTotal - LastTotalPreviousHour;
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
LastHour = Hour;
LastTotalPreviousHour = ActTotal;
}
LastValue = ActTotal;
LastDate = sd[1];
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Direction, Speed, Gust, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[1].c_str());
int intGust = atoi(sd[2].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
}
else if (sensor == "winddir") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Direction, Speed, Gust FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
std::map<int, int> _directions;
int wdirtabletemp[17][8];
std::string szLegendLabels[7];
int ii = 0;
int totalvalues = 0;
//init dir list
int idir;
for (idir = 0; idir < 360 + 1; idir++)
_directions[idir] = 0;
for (ii = 0; ii < 17; ii++)
{
for (int jj = 0; jj < 8; jj++)
{
wdirtabletemp[ii][jj] = 0;
}
}
if (m_sql.m_windunit == WINDUNIT_MS)
{
szLegendLabels[0] = "< 0.5 " + m_sql.m_windsign;
szLegendLabels[1] = "0.5-2 " + m_sql.m_windsign;
szLegendLabels[2] = "2-4 " + m_sql.m_windsign;
szLegendLabels[3] = "4-6 " + m_sql.m_windsign;
szLegendLabels[4] = "6-8 " + m_sql.m_windsign;
szLegendLabels[5] = "8-10 " + m_sql.m_windsign;
szLegendLabels[6] = "> 10" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_KMH)
{
szLegendLabels[0] = "< 2 " + m_sql.m_windsign;
szLegendLabels[1] = "2-4 " + m_sql.m_windsign;
szLegendLabels[2] = "4-6 " + m_sql.m_windsign;
szLegendLabels[3] = "6-10 " + m_sql.m_windsign;
szLegendLabels[4] = "10-20 " + m_sql.m_windsign;
szLegendLabels[5] = "20-36 " + m_sql.m_windsign;
szLegendLabels[6] = "> 36" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_MPH)
{
szLegendLabels[0] = "< 3 " + m_sql.m_windsign;
szLegendLabels[1] = "3-7 " + m_sql.m_windsign;
szLegendLabels[2] = "7-12 " + m_sql.m_windsign;
szLegendLabels[3] = "12-18 " + m_sql.m_windsign;
szLegendLabels[4] = "18-24 " + m_sql.m_windsign;
szLegendLabels[5] = "24-46 " + m_sql.m_windsign;
szLegendLabels[6] = "> 46" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_Knots)
{
szLegendLabels[0] = "< 3 " + m_sql.m_windsign;
szLegendLabels[1] = "3-7 " + m_sql.m_windsign;
szLegendLabels[2] = "7-17 " + m_sql.m_windsign;
szLegendLabels[3] = "17-27 " + m_sql.m_windsign;
szLegendLabels[4] = "27-34 " + m_sql.m_windsign;
szLegendLabels[5] = "34-41 " + m_sql.m_windsign;
szLegendLabels[6] = "> 41" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_Beaufort)
{
szLegendLabels[0] = "< 2 " + m_sql.m_windsign;
szLegendLabels[1] = "2-4 " + m_sql.m_windsign;
szLegendLabels[2] = "4-6 " + m_sql.m_windsign;
szLegendLabels[3] = "6-8 " + m_sql.m_windsign;
szLegendLabels[4] = "8-10 " + m_sql.m_windsign;
szLegendLabels[5] = "10-12 " + m_sql.m_windsign;
szLegendLabels[6] = "> 12" + m_sql.m_windsign;
}
else {
//Todo !
szLegendLabels[0] = "< 0.5 " + m_sql.m_windsign;
szLegendLabels[1] = "0.5-2 " + m_sql.m_windsign;
szLegendLabels[2] = "2-4 " + m_sql.m_windsign;
szLegendLabels[3] = "4-6 " + m_sql.m_windsign;
szLegendLabels[4] = "6-8 " + m_sql.m_windsign;
szLegendLabels[5] = "8-10 " + m_sql.m_windsign;
szLegendLabels[6] = "> 10" + m_sql.m_windsign;
}
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float fdirection = static_cast<float>(atof(sd[0].c_str()));
if (fdirection >= 360)
fdirection = 0;
int direction = int(fdirection);
float speedOrg = static_cast<float>(atof(sd[1].c_str()));
float gustOrg = static_cast<float>(atof(sd[2].c_str()));
if ((gustOrg == 0) && (speedOrg != 0))
gustOrg = speedOrg;
if (gustOrg == 0)
continue; //no direction if wind is still
float speed = speedOrg * m_sql.m_windscale;
float gust = gustOrg * m_sql.m_windscale;
int bucket = int(fdirection / 22.5f);
int speedpos = 0;
if (m_sql.m_windunit == WINDUNIT_MS)
{
if (gust < 0.5f) speedpos = 0;
else if (gust < 2.0f) speedpos = 1;
else if (gust < 4.0f) speedpos = 2;
else if (gust < 6.0f) speedpos = 3;
else if (gust < 8.0f) speedpos = 4;
else if (gust < 10.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_KMH)
{
if (gust < 2.0f) speedpos = 0;
else if (gust < 4.0f) speedpos = 1;
else if (gust < 6.0f) speedpos = 2;
else if (gust < 10.0f) speedpos = 3;
else if (gust < 20.0f) speedpos = 4;
else if (gust < 36.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_MPH)
{
if (gust < 3.0f) speedpos = 0;
else if (gust < 7.0f) speedpos = 1;
else if (gust < 12.0f) speedpos = 2;
else if (gust < 18.0f) speedpos = 3;
else if (gust < 24.0f) speedpos = 4;
else if (gust < 46.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_Knots)
{
if (gust < 3.0f) speedpos = 0;
else if (gust < 7.0f) speedpos = 1;
else if (gust < 17.0f) speedpos = 2;
else if (gust < 27.0f) speedpos = 3;
else if (gust < 34.0f) speedpos = 4;
else if (gust < 41.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_Beaufort)
{
float gustms = gustOrg * 0.1f;
int iBeaufort = MStoBeaufort(gustms);
if (iBeaufort < 2) speedpos = 0;
else if (iBeaufort < 4) speedpos = 1;
else if (iBeaufort < 6) speedpos = 2;
else if (iBeaufort < 8) speedpos = 3;
else if (iBeaufort < 10) speedpos = 4;
else if (iBeaufort < 12) speedpos = 5;
else speedpos = 6;
}
else
{
//Still todo !
if (gust < 0.5f) speedpos = 0;
else if (gust < 2.0f) speedpos = 1;
else if (gust < 4.0f) speedpos = 2;
else if (gust < 6.0f) speedpos = 3;
else if (gust < 8.0f) speedpos = 4;
else if (gust < 10.0f) speedpos = 5;
else speedpos = 6;
}
wdirtabletemp[bucket][speedpos]++;
_directions[direction]++;
totalvalues++;
}
for (int jj = 0; jj < 7; jj++)
{
root["result_speed"][jj]["label"] = szLegendLabels[jj];
for (ii = 0; ii < 16; ii++)
{
float svalue = 0;
if (totalvalues > 0)
{
svalue = (100.0f / totalvalues)*wdirtabletemp[ii][jj];
}
sprintf(szTmp, "%.2f", svalue);
root["result_speed"][jj]["sp"][ii] = szTmp;
}
}
ii = 0;
for (idir = 0; idir < 360 + 1; idir++)
{
if (_directions[idir] != 0)
{
root["result"][ii]["dig"] = idir;
float percentage = 0;
if (totalvalues > 0)
{
percentage = (float(100.0 / float(totalvalues))*float(_directions[idir]));
}
sprintf(szTmp, "%.2f", percentage);
root["result"][ii]["div"] = szTmp;
ii++;
}
}
}
}
}//day
else if (srange == "week")
{
if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
char szDateStart[40];
char szDateEnd[40];
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
//Subtract one week
time_t weekbefore;
struct tm tm2;
getNoon(weekbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday - 7); // We only want the date
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
result = m_sql.safe_query("SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
//add today (have to calculate it)
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd);
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
double total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
total_real *= AddjMulti;
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
else if (sensor == "counter")
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
char szDateStart[40];
char szDateEnd[40];
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
//Subtract one week
time_t weekbefore;
struct tm tm2;
getNoon(weekbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday - 7); // We only want the date
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
int ii = 0;
if (dType == pTypeP1Power)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value5,Value6,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
std::string szValueUsage1 = sd[0];
std::string szValueDeliv1 = sd[1];
std::string szValueUsage2 = sd[2];
std::string szValueDeliv2 = sd[3];
float fUsage1 = (float)(atof(szValueUsage1.c_str()));
float fUsage2 = (float)(atof(szValueUsage2.c_str()));
float fDeliv1 = (float)(atof(szValueDeliv1.c_str()));
float fDeliv2 = (float)(atof(szValueDeliv2.c_str()));
fDeliv1 = (fDeliv1 < 10) ? 0 : fDeliv1;
fDeliv2 = (fDeliv2 < 10) ? 0 : fDeliv2;
if ((fDeliv1 != 0) || (fDeliv2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage1 / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage2 / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv1 / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv2 / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else
{
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_COUNTER:
//value already set above!
break;
default:
szValue = "0";
break;
}
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
//add today (have to calculate it)
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2), MAX(Value2),MIN(Value5), MAX(Value5), MIN(Value6), MAX(Value6) FROM MultiMeter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage_1, total_real_usage_2;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv_1, total_real_deliv_2;
bool bHaveDeliverd = false;
total_real_usage_1 = total_max_usage_1 - total_min_usage_1;
total_real_usage_2 = total_max_usage_2 - total_min_usage_2;
total_real_deliv_1 = total_max_deliv_1 - total_min_deliv_1;
total_real_deliv_2 = total_max_deliv_2 - total_min_deliv_2;
if ((total_real_deliv_1 != 0) || (total_real_deliv_2 != 0))
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%llu", total_real_usage_1);
std::string szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_usage_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_COUNTER:
//value already set above!
break;
default:
szValue = "0";
break;
}
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
}//week
else if ((srange == "month") || (srange == "year"))
{
char szDateStart[40];
char szDateEnd[40];
char szDateStartPrev[40];
char szDateEndPrev[40];
std::string sactmonth = request::findValue(&req, "actmonth");
std::string sactyear = request::findValue(&req, "actyear");
int actMonth = atoi(sactmonth.c_str());
int actYear = atoi(sactyear.c_str());
if ((sactmonth != "") && (sactyear != ""))
{
sprintf(szDateStart, "%04d-%02d-%02d", actYear, actMonth, 1);
sprintf(szDateStartPrev, "%04d-%02d-%02d", actYear - 1, actMonth, 1);
actMonth++;
if (actMonth == 13)
{
actMonth = 1;
actYear++;
}
sprintf(szDateEnd, "%04d-%02d-%02d", actYear, actMonth, 1);
sprintf(szDateEndPrev, "%04d-%02d-%02d", actYear - 1, actMonth, 1);
}
else if (sactyear != "")
{
sprintf(szDateStart, "%04d-%02d-%02d", actYear, 1, 1);
sprintf(szDateStartPrev, "%04d-%02d-%02d", actYear - 1, 1, 1);
actYear++;
sprintf(szDateEnd, "%04d-%02d-%02d", actYear, 1, 1);
sprintf(szDateEndPrev, "%04d-%02d-%02d", actYear - 1, 1, 1);
}
else
{
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
sprintf(szDateEndPrev, "%04d-%02d-%02d", tm1.tm_year + 1900 - 1, tm1.tm_mon + 1, tm1.tm_mday);
struct tm tm2;
if (srange == "month")
{
//Subtract one month
time_t monthbefore;
getNoon(monthbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon, tm1.tm_mday);
}
else
{
//Subtract one year
time_t yearbefore;
getNoon(yearbefore, tm2, tm1.tm_year + 1900 - 1, tm1.tm_mon + 1, tm1.tm_mday);
}
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
sprintf(szDateStartPrev, "%04d-%02d-%02d", tm2.tm_year + 1900 - 1, tm2.tm_mon + 1, tm2.tm_mday);
}
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
//Actual Year
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Temp_Avg, Date, SetPoint_Min,"
" SetPoint_Max, SetPoint_Avg "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[7].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
bool bOK = true;
if (dType == pTypeWIND)
{
bOK = ((dSubType != sTypeWINDNoTemp) && (dSubType != sTypeWINDNoTempNoChill));
}
if (bOK)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sm = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[10].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MIN(Temperature), MAX(Temperature),"
" MIN(Chill), MAX(Chill), AVG(Humidity),"
" AVG(Barometer), AVG(Temperature), MIN(SetPoint),"
" MAX(SetPoint), AVG(SetPoint) "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
if (
((dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sx = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sm = ConvertTemperature(atof(sd[7].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[9].c_str()), tempsign);
root["result"][ii]["se"] = se;
root["result"][ii]["sm"] = sm;
root["result"][ii]["sx"] = sx;
}
ii++;
}
//Previous Year
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Temp_Avg, Date, SetPoint_Min,"
" SetPoint_Max, SetPoint_Avg "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[7].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
{
bool bOK = true;
if (dType == pTypeWIND)
{
bOK = ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp));
}
if (bOK)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["resultprev"][iPrev]["te"] = te;
root["resultprev"][iPrev]["tm"] = tm;
root["resultprev"][iPrev]["ta"] = ta;
}
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["resultprev"][iPrev]["ch"] = ch;
root["resultprev"][iPrev]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["resultprev"][iPrev]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
else
root["resultprev"][iPrev]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sx = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sm = ConvertTemperature(atof(sd[7].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[9].c_str()), tempsign);
root["resultprev"][iPrev]["se"] = se;
root["resultprev"][iPrev]["sm"] = sm;
root["resultprev"][iPrev]["sx"] = sx;
}
iPrev++;
}
}
}
else if (sensor == "Percentage") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Percentage_Min, Percentage_Max, Percentage_Avg, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_avg"] = sd[2];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MIN(Percentage), MAX(Percentage), AVG(Percentage) FROM Percentage WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_avg"] = sd[2];
ii++;
}
}
else if (sensor == "fan") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Speed_Min, Speed_Max, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_min"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query("SELECT MIN(Speed), MAX(Speed) FROM Fan WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_min"] = sd[0];
ii++;
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MAX(Level) FROM UV WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["uvi"] = sd[0];
ii++;
}
//Previous Year
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
root["resultprev"][iPrev]["uvi"] = sd[0];
iPrev++;
}
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
//add today (have to calculate it)
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd);
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
double total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
total_real *= AddjMulti;
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
//Previous Year
result = m_sql.safe_query(
"SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["resultprev"][iPrev]["mm"] = szTmp;
iPrev++;
}
}
}
else if (sensor == "counter") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int nValue = 0;
std::string sValue = "";
result = m_sql.safe_query("SELECT nValue, sValue FROM DeviceStatus WHERE (ID==%" PRIu64 ")",
idx);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
nValue = atoi(sd[0].c_str());
sValue = sd[1];
}
int ii = 0;
iPrev = 0;
if (dType == pTypeP1Power)
{
//Actual Year
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date,"
" Counter1, Counter2, Counter3, Counter4 "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
double counter_1 = atof(sd[5].c_str());
double counter_2 = atof(sd[6].c_str());
double counter_3 = atof(sd[7].c_str());
double counter_4 = atof(sd[8].c_str());
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage_1 = static_cast<float>(atof(szUsage1.c_str()));
float fUsage_2 = static_cast<float>(atof(szUsage2.c_str()));
float fDeliv_1 = static_cast<float>(atof(szDeliv1.c_str()));
float fDeliv_2 = static_cast<float>(atof(szDeliv2.c_str()));
fDeliv_1 = (fDeliv_1 < 10) ? 0 : fDeliv_1;
fDeliv_2 = (fDeliv_2 < 10) ? 0 : fDeliv_2;
if ((fDeliv_1 != 0) || (fDeliv_2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage_1 / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage_2 / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_1 / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_2 / divider);
root["result"][ii]["r2"] = szTmp;
if (counter_1 != 0)
{
sprintf(szTmp, "%.3f", (counter_1 - fUsage_1) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c1"] = szTmp;
if (counter_2 != 0)
{
sprintf(szTmp, "%.3f", (counter_2 - fDeliv_1) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c2"] = szTmp;
if (counter_3 != 0)
{
sprintf(szTmp, "%.3f", (counter_3 - fUsage_2) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c3"] = szTmp;
if (counter_4 != 0)
{
sprintf(szTmp, "%.3f", (counter_4 - fDeliv_2) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c4"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
//Previous Year
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
bool bHaveDeliverd = false;
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[4].substr(0, 16);
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage_1 = static_cast<float>(atof(szUsage1.c_str()));
float fUsage_2 = static_cast<float>(atof(szUsage2.c_str()));
float fDeliv_1 = static_cast<float>(atof(szDeliv1.c_str()));
float fDeliv_2 = static_cast<float>(atof(szDeliv2.c_str()));
if ((fDeliv_1 != 0) || (fDeliv_2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage_1 / divider);
root["resultprev"][iPrev]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage_2 / divider);
root["resultprev"][iPrev]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_1 / divider);
root["resultprev"][iPrev]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_2 / divider);
root["resultprev"][iPrev]["r2"] = szTmp;
iPrev++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (dType == pTypeAirQuality)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["co2_min"] = sd[0];
root["result"][ii]["co2_max"] = sd[1];
root["result"][ii]["co2_avg"] = sd[2];
ii++;
}
}
result = m_sql.safe_query("SELECT Value2,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
root["resultprev"][iPrev]["co2_max"] = sd[0];
iPrev++;
}
}
}
else if (
((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness))) ||
((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
ii++;
}
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float fValue1 = float(atof(sd[0].c_str())) / vdiv;
float fValue2 = float(atof(sd[1].c_str())) / vdiv;
float fValue3 = float(atof(sd[2].c_str())) / vdiv;
root["result"][ii]["d"] = sd[3].substr(0, 16);
if (metertype == 1)
{
fValue1 *= 0.6214f;
fValue2 *= 0.6214f;
}
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
sprintf(szTmp, "%.3f", fValue1);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.3f", fValue2);
root["result"][ii]["v_max"] = szTmp;
if (fValue3 != 0)
{
sprintf(szTmp, "%.3f", fValue3);
root["result"][ii]["v_avg"] = szTmp;
}
}
else
{
sprintf(szTmp, "%.1f", fValue1);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", fValue2);
root["result"][ii]["v_max"] = szTmp;
if (fValue3 != 0)
{
sprintf(szTmp, "%.1f", fValue3);
root["result"][ii]["v_avg"] = szTmp;
}
}
ii++;
}
}
}
else if (dType == pTypeLux)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2,Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["lux_min"] = sd[0];
root["result"][ii]["lux_max"] = sd[1];
root["result"][ii]["lux_avg"] = sd[2];
ii++;
}
}
}
else if (dType == pTypeWEIGHT)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[0].c_str()) / 10.0f);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[1].c_str()) / 10.0f);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
}
else if (dType == pTypeUsage)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["u_min"] = atof(sd[0].c_str()) / 10.0f;
root["result"][ii]["u_max"] = atof(sd[1].c_str()) / 10.0f;
ii++;
}
}
}
else if (dType == pTypeCURRENT)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Value4,Value5,Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
float fval4 = static_cast<float>(atof(sd[3].c_str()) / 10.0f);
float fval5 = static_cast<float>(atof(sd[4].c_str()) / 10.0f);
float fval6 = static_cast<float>(atof(sd[5].c_str()) / 10.0f);
if ((fval1 != 0) || (fval2 != 0))
bHaveL1 = true;
if ((fval3 != 0) || (fval4 != 0))
bHaveL2 = true;
if ((fval5 != 0) || (fval6 != 0))
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%.1f", fval4);
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%.1f", fval5);
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%.1f", fval6);
root["result"][ii]["v6"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%d", int(fval4*voltage));
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%d", int(fval5*voltage));
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%d", int(fval6*voltage));
root["result"][ii]["v6"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if (dType == pTypeCURRENTENERGY)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Value4,Value5,Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
//CM180i
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
float fval4 = static_cast<float>(atof(sd[3].c_str()) / 10.0f);
float fval5 = static_cast<float>(atof(sd[4].c_str()) / 10.0f);
float fval6 = static_cast<float>(atof(sd[5].c_str()) / 10.0f);
if ((fval1 != 0) || (fval2 != 0))
bHaveL1 = true;
if ((fval3 != 0) || (fval4 != 0))
bHaveL2 = true;
if ((fval5 != 0) || (fval6 != 0))
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%.1f", fval4);
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%.1f", fval5);
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%.1f", fval6);
root["result"][ii]["v6"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%d", int(fval4*voltage));
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%d", int(fval5*voltage));
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%d", int(fval6*voltage));
root["result"][ii]["v6"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else
{
if (dType == pTypeP1Gas)
{
//Add last counter value
sprintf(szTmp, "%.3f", atof(sValue.c_str()) / 1000.0);
root["counter"] = szTmp;
}
else if (dType == pTypeENERGY)
{
size_t spos = sValue.find(";");
if (spos != std::string::npos)
{
float fvalue = static_cast<float>(atof(sValue.substr(spos + 1).c_str()));
sprintf(szTmp, "%.3f", fvalue / (divider / 100.0f));
root["counter"] = szTmp;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeKwh))
{
size_t spos = sValue.find(";");
if (spos != std::string::npos)
{
float fvalue = static_cast<float>(atof(sValue.substr(spos + 1).c_str()));
sprintf(szTmp, "%.3f", fvalue / divider);
root["counter"] = szTmp;
}
}
else if (dType == pTypeRFXMeter)
{
//Add last counter value
float fvalue = static_cast<float>(atof(sValue.c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", AddjValue + (fvalue / divider));
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", AddjValue + (fvalue / divider));
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", AddjValue + (fvalue / divider));
break;
default:
strcpy(szTmp, "");
break;
}
root["counter"] = szTmp;
}
else if (dType == pTypeYouLess)
{
std::vector<std::string> results;
StringSplit(sValue, ";", results);
if (results.size() == 2)
{
//Add last counter value
float fvalue = static_cast<float>(atof(results[0].c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", fvalue / divider);
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", fvalue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", fvalue / divider);
break;
default:
strcpy(szTmp, "");
break;
}
root["counter"] = szTmp;
}
}
else if (!bIsManagedCounter)
{
//Add last counter value
sprintf(szTmp, "%d", atoi(sValue.c_str()));
root["counter"] = szTmp;
}
else
{
root["counter"] = "0";
}
//Actual Year
result = m_sql.safe_query("SELECT Value, Date, Counter FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
double fcounter = atof(sd[2].c_str());
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.3f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.2f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.3f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.0f", AddjValue + ((fcounter - atof(szValue.c_str()))));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
}
ii++;
}
}
//Past Year
result = m_sql.safe_query("SELECT Value, Date, Counter FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["resultprev"][iPrev]["v"] = szTmp;
break;
}
iPrev++;
}
}
}
//add today (have to calculate it)
if ((sactmonth != "") || (sactyear != ""))
{
struct tm loctime;
time_t now = mytime(NULL);
localtime_r(&now, &loctime);
if ((sactmonth != "") && (sactyear != ""))
{
bool bIsThisMonth = (atoi(sactyear.c_str()) == loctime.tm_year + 1900) && (atoi(sactmonth.c_str()) == loctime.tm_mon + 1);
if (bIsThisMonth)
{
sprintf(szDateEnd, "%04d-%02d-%02d", loctime.tm_year + 1900, loctime.tm_mon + 1, loctime.tm_mday);
}
}
else if (sactyear != "")
{
bool bIsThisYear = (atoi(sactyear.c_str()) == loctime.tm_year + 1900);
if (bIsThisYear)
{
sprintf(szDateEnd, "%04d-%02d-%02d", loctime.tm_year + 1900, loctime.tm_mon + 1, loctime.tm_mday);
}
}
}
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2),"
" MAX(Value2), MIN(Value5), MAX(Value5),"
" MIN(Value6), MAX(Value6) "
"FROM MultiMeter WHERE (DeviceRowID=%" PRIu64 ""
" AND Date>='%q')",
idx, szDateEnd);
bool bHaveDeliverd = false;
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage_1, total_real_usage_2;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv_1, total_real_deliv_2;
total_real_usage_1 = total_max_usage_1 - total_min_usage_1;
total_real_usage_2 = total_max_usage_2 - total_min_usage_2;
total_real_deliv_1 = total_max_deliv_1 - total_min_deliv_1;
total_real_deliv_2 = total_max_deliv_2 - total_min_deliv_2;
if ((total_real_deliv_1 != 0) || (total_real_deliv_2 != 0))
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
std::string szValue;
sprintf(szTmp, "%llu", total_real_usage_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_usage_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
else if (dType == pTypeAirQuality)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value), AVG(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["co2_min"] = result[0][0];
root["result"][ii]["co2_max"] = result[0][1];
root["result"][ii]["co2_avg"] = result[0][2];
ii++;
}
}
else if (
((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness))) ||
((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_min"] = result[0][0];
root["result"][ii]["v_max"] = result[0][1];
ii++;
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
float fValue1 = float(atof(result[0][0].c_str())) / vdiv;
float fValue2 = float(atof(result[0][1].c_str())) / vdiv;
if (metertype == 1)
{
fValue1 *= 0.6214f;
fValue2 *= 0.6214f;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue1);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue1);
else
sprintf(szTmp, "%.1f", fValue1);
root["result"][ii]["v_min"] = szTmp;
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue2);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue2);
else
sprintf(szTmp, "%.1f", fValue2);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
else if (dType == pTypeLux)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value), AVG(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["lux_min"] = result[0][0];
root["result"][ii]["lux_max"] = result[0][1];
root["result"][ii]["lux_avg"] = result[0][2];
ii++;
}
}
else if (dType == pTypeWEIGHT)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%.1f", m_sql.m_weightscale* atof(result[0][0].c_str()) / 10.0f);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(result[0][1].c_str()) / 10.0f);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
else if (dType == pTypeUsage)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["u_min"] = atof(result[0][0].c_str()) / 10.0f;
root["result"][ii]["u_max"] = atof(result[0][1].c_str()) / 10.0f;
ii++;
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
root["result"][ii]["d"] = szDateEnd;
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
{
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
std::vector<std::string> mresults;
StringSplit(sValue, ";", mresults);
if (mresults.size() == 2)
{
sValue = mresults[1];
}
if (dType == pTypeENERGY)
sprintf(szTmp, "%.3f", AddjValue + (((atof(sValue.c_str())*100.0f) - atof(szValue.c_str())) / divider));
else
sprintf(szTmp, "%.3f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
}
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.2f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.0f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str()))));
root["result"][ii]["c"] = szTmp;
break;
}
ii++;
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int ii = 0;
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[5].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT AVG(Direction), MIN(Speed), MAX(Speed),"
" MIN(Gust), MAX(Gust) "
"FROM Wind WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY Date ASC",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
//Previous Year
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[5].substr(0, 16);
root["resultprev"][iPrev]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["resultprev"][iPrev]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["resultprev"][iPrev]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["resultprev"][iPrev]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["resultprev"][iPrev]["gu"] = szTmp;
}
iPrev++;
}
}
}
}//month or year
else if ((srange.substr(0, 1) == "2") && (srange.substr(10, 1) == "T") && (srange.substr(11, 1) == "2")) // custom range 2013-01-01T2013-12-31
{
std::string szDateStart = srange.substr(0, 10);
std::string szDateEnd = srange.substr(11, 10);
std::string sgraphtype = request::findValue(&req, "graphtype");
std::string sgraphTemp = request::findValue(&req, "graphTemp");
std::string sgraphChill = request::findValue(&req, "graphChill");
std::string sgraphHum = request::findValue(&req, "graphHum");
std::string sgraphBaro = request::findValue(&req, "graphBaro");
std::string sgraphDew = request::findValue(&req, "graphDew");
std::string sgraphSet = request::findValue(&req, "graphSet");
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
bool sendTemp = false;
bool sendChill = false;
bool sendHum = false;
bool sendBaro = false;
bool sendDew = false;
bool sendSet = false;
if ((sgraphTemp == "true") &&
((dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
)
{
sendTemp = true;
}
if ((sgraphSet == "true") &&
((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))) //FIXME cheat for water setpoint is just on or off
{
sendSet = true;
}
if ((sgraphChill == "true") &&
(((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp)))
)
{
sendChill = true;
}
if ((sgraphHum == "true") &&
((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
)
{
sendHum = true;
}
if ((sgraphBaro == "true") && (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
))
{
sendBaro = true;
}
if ((sgraphDew == "true") && ((dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO)))
{
sendDew = true;
}
if (sgraphtype == "1")
{
// Need to get all values of the end date so 23:59:59 is appended to the date string
result = m_sql.safe_query(
"SELECT Temperature, Chill, Humidity, Barometer,"
" Date, DewPoint, SetPoint "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q' AND Date<='%q 23:59:59') ORDER BY Date ASC",
idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4];//.substr(0,16);
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[1].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[2];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[3];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[5].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double se = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["se"] = se;
}
ii++;
}
}
}
else
{
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Date, DewPoint, Temp_Avg,"
" SetPoint_Min, SetPoint_Max, SetPoint_Avg "
"FROM Temperature_Calendar "
"WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[8].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[4];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[7].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double sm = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[10].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[11].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
char szTmp[1024];
sprintf(szTmp, "%.1f %.1f %.1f", sm, se, sx);
_log.Log(LOG_STATUS, "%s", szTmp);
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MIN(Temperature), MAX(Temperature),"
" MIN(Chill), MAX(Chill), AVG(Humidity),"
" AVG(Barometer), MIN(DewPoint), AVG(Temperature),"
" MIN(SetPoint), MAX(SetPoint), AVG(SetPoint) "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[7].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[4];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double sm = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[10].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
}
ii++;
}
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MAX(Level) FROM UV WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Total, Rate, Date FROM %s "
"WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["mm"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd.c_str());
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
float total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
else if (sensor == "counter") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int ii = 0;
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage = (float)(atof(szUsage1.c_str()) + atof(szUsage2.c_str()));
float fDeliv = (float)(atof(szDeliv1.c_str()) + atof(szDeliv2.c_str()));
if (fDeliv != 0)
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv / divider);
root["result"][ii]["v2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else
{
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
}
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
//add today (have to calculate it)
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2),"
" MAX(Value2),MIN(Value5), MAX(Value5),"
" MIN(Value6), MAX(Value6) "
"FROM MultiMeter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
bool bHaveDeliverd = false;
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv;
total_real_usage = (total_max_usage_1 + total_max_usage_2) - (total_min_usage_1 + total_min_usage_2);
total_real_deliv = (total_max_deliv_1 + total_max_deliv_2) - (total_min_deliv_1 + total_min_deliv_2);
if (total_real_deliv != 0)
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%llu", total_real_usage);
std::string szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
ii++;
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
}
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int ii = 0;
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[5].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT AVG(Direction), MIN(Speed), MAX(Speed), MIN(Gust), MAX(Gust) FROM Wind WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY Date ASC",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
}//custom range
}
/**
* Retrieve user session from store, without remote host.
*/
const WebEmStoredSession CWebServer::GetSession(const std::string & sessionId) {
//_log.Log(LOG_STATUS, "SessionStore : get...");
WebEmStoredSession session;
if (sessionId.empty()) {
_log.Log(LOG_ERROR, "SessionStore : cannot get session without id.");
}
else {
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT SessionID, Username, AuthToken, ExpirationDate FROM UserSessions WHERE SessionID = '%q'",
sessionId.c_str());
if (!result.empty()) {
session.id = result[0][0].c_str();
session.username = base64_decode(result[0][1]);
session.auth_token = result[0][2].c_str();
std::string sExpirationDate = result[0][3];
time_t now = mytime(NULL);
struct tm tExpirationDate;
ParseSQLdatetime(session.expires, tExpirationDate, sExpirationDate);
// RemoteHost is not used to restore the session
// LastUpdate is not used to restore the session
}
}
return session;
}
/**
* Save user session.
*/
void CWebServer::StoreSession(const WebEmStoredSession & session) {
//_log.Log(LOG_STATUS, "SessionStore : store...");
if (session.id.empty()) {
_log.Log(LOG_ERROR, "SessionStore : cannot store session without id.");
return;
}
char szExpires[30];
struct tm ltime;
localtime_r(&session.expires, <ime);
strftime(szExpires, sizeof(szExpires), "%Y-%m-%d %H:%M:%S", <ime);
std::string remote_host = (session.remote_host.size() <= 50) ? // IPv4 : 15, IPv6 : (39|45)
session.remote_host : session.remote_host.substr(0, 50);
WebEmStoredSession storedSession = GetSession(session.id);
if (storedSession.id.empty()) {
m_sql.safe_query(
"INSERT INTO UserSessions (SessionID, Username, AuthToken, ExpirationDate, RemoteHost) VALUES ('%q', '%q', '%q', '%q', '%q')",
session.id.c_str(),
base64_encode(session.username).c_str(),
session.auth_token.c_str(),
szExpires,
remote_host.c_str());
}
else {
m_sql.safe_query(
"UPDATE UserSessions set AuthToken = '%q', ExpirationDate = '%q', RemoteHost = '%q', LastUpdate = datetime('now', 'localtime') WHERE SessionID = '%q'",
session.auth_token.c_str(),
szExpires,
remote_host.c_str(),
session.id.c_str());
}
}
/**
* Remove user session and expired sessions.
*/
void CWebServer::RemoveSession(const std::string & sessionId) {
//_log.Log(LOG_STATUS, "SessionStore : remove...");
if (sessionId.empty()) {
return;
}
m_sql.safe_query(
"DELETE FROM UserSessions WHERE SessionID = '%q'",
sessionId.c_str());
}
/**
* Remove all expired user sessions.
*/
void CWebServer::CleanSessions() {
//_log.Log(LOG_STATUS, "SessionStore : clean...");
m_sql.safe_query(
"DELETE FROM UserSessions WHERE ExpirationDate < datetime('now', 'localtime')");
}
/**
* Delete all user's session, except the session used to modify the username or password.
* username must have been hashed
*
* Note : on the WebUserName modification, this method will not delete the session, but the session will be deleted anyway
* because the username will be unknown (see cWebemRequestHandler::checkAuthToken).
*/
void CWebServer::RemoveUsersSessions(const std::string& username, const WebEmSession & exceptSession) {
m_sql.safe_query("DELETE FROM UserSessions WHERE (Username=='%q') and (SessionID!='%q')", username.c_str(), exceptSession.id.c_str());
}
} //server
}//http
| ./CrossVul/dataset_final_sorted/CWE-89/cpp/good_762_0 |
crossvul-cpp_data_bad_762_0 | #include "stdafx.h"
#include "WebServer.h"
#include "WebServerHelper.h"
#include <boost/bind.hpp>
#include <iostream>
#include <fstream>
#include "mainworker.h"
#include "Helper.h"
#include "localtime_r.h"
#include "EventSystem.h"
#include "dzVents.h"
#include "../httpclient/HTTPClient.h"
#include "../hardware/hardwaretypes.h"
#include "../hardware/1Wire.h"
#include "../hardware/OTGWBase.h"
#ifdef WITH_OPENZWAVE
#include "../hardware/OpenZWave.h"
#endif
#include "../hardware/EnOceanESP2.h"
#include "../hardware/EnOceanESP3.h"
#include "../hardware/Wunderground.h"
#include "../hardware/DarkSky.h"
#include "../hardware/AccuWeather.h"
#include "../hardware/OpenWeatherMap.h"
#include "../hardware/Kodi.h"
#include "../hardware/Limitless.h"
#include "../hardware/LogitechMediaServer.h"
#include "../hardware/MySensorsBase.h"
#include "../hardware/RFXBase.h"
#include "../hardware/RFLinkBase.h"
#include "../hardware/SysfsGpio.h"
#include "../hardware/HEOS.h"
#include "../hardware/eHouseTCP.h"
#include "../hardware/USBtin.h"
#include "../hardware/USBtin_MultiblocV8.h"
#ifdef WITH_GPIO
#include "../hardware/Gpio.h"
#include "../hardware/GpioPin.h"
#endif // WITH_GPIO
#include "../hardware/Tellstick.h"
#include "../webserver/Base64.h"
#include "../smtpclient/SMTPClient.h"
#include "../json/json.h"
#include "Logger.h"
#include "SQLHelper.h"
#include "../push/BasePush.h"
#include <algorithm>
#ifdef ENABLE_PYTHON
#include "../hardware/plugins/Plugins.h"
#endif
#ifndef WIN32
#include <sys/utsname.h>
#include <dirent.h>
#else
#include "../msbuild/WindowsHelper.h"
#include "dirent_windows.h"
#endif
#include "../notifications/NotificationHelper.h"
#include "../main/LuaHandler.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#define round(a) ( int ) ( a + .5 )
extern std::string szUserDataFolder;
extern std::string szWWWFolder;
extern std::string szAppVersion;
extern std::string szAppHash;
extern std::string szAppDate;
extern std::string szPyVersion;
extern bool g_bUseUpdater;
extern time_t m_StartTime;
extern bool g_bDontCacheWWW;
struct _tGuiLanguage {
const char* szShort;
const char* szLong;
};
static const _tGuiLanguage guiLanguage[] =
{
{ "en", "English" },
{ "sq", "Albanian" },
{ "ar", "Arabic" },
{ "bs", "Bosnian" },
{ "bg", "Bulgarian" },
{ "ca", "Catalan" },
{ "zh", "Chinese" },
{ "cs", "Czech" },
{ "da", "Danish" },
{ "nl", "Dutch" },
{ "et", "Estonian" },
{ "de", "German" },
{ "el", "Greek" },
{ "fr", "French" },
{ "fi", "Finnish" },
{ "he", "Hebrew" },
{ "hu", "Hungarian" },
{ "is", "Icelandic" },
{ "it", "Italian" },
{ "lt", "Lithuanian" },
{ "lv", "Latvian" },
{ "mk", "Macedonian" },
{ "no", "Norwegian" },
{ "fa", "Persian" },
{ "pl", "Polish" },
{ "pt", "Portuguese" },
{ "ro", "Romanian" },
{ "ru", "Russian" },
{ "sr", "Serbian" },
{ "sk", "Slovak" },
{ "sl", "Slovenian" },
{ "es", "Spanish" },
{ "sv", "Swedish" },
{ "zh_TW", "Taiwanese" },
{ "tr", "Turkish" },
{ "uk", "Ukrainian" },
{ NULL, NULL }
};
extern http::server::CWebServerHelper m_webservers;
namespace http {
namespace server {
CWebServer::CWebServer(void) : session_store()
{
m_pWebEm = NULL;
m_bDoStop = false;
#ifdef WITH_OPENZWAVE
m_ZW_Hwidx = -1;
#endif
}
CWebServer::~CWebServer(void)
{
// RK, we call StopServer() instead of just deleting m_pWebEm. The Do_Work thread might still be accessing that object
StopServer();
}
void CWebServer::Do_Work()
{
bool exception_thrown = false;
while (!m_bDoStop)
{
exception_thrown = false;
try {
if (m_pWebEm) {
m_pWebEm->Run();
}
}
catch (std::exception& e) {
_log.Log(LOG_ERROR, "WebServer(%s) exception occurred : '%s'", m_server_alias.c_str(), e.what());
exception_thrown = true;
}
catch (...) {
_log.Log(LOG_ERROR, "WebServer(%s) unknown exception occurred", m_server_alias.c_str());
exception_thrown = true;
}
if (exception_thrown) {
_log.Log(LOG_STATUS, "WebServer(%s) restart server in 5 seconds", m_server_alias.c_str());
sleep_milliseconds(5000); // prevents from an exception flood
continue;
}
break;
}
_log.Log(LOG_STATUS, "WebServer(%s) stopped", m_server_alias.c_str());
}
void CWebServer::ReloadCustomSwitchIcons()
{
m_custom_light_icons.clear();
m_custom_light_icons_lookup.clear();
std::string sLine = "";
//First get them from the switch_icons.txt file
std::ifstream infile;
std::string switchlightsfile = szWWWFolder + "/switch_icons.txt";
infile.open(switchlightsfile.c_str());
if (infile.is_open())
{
int index = 0;
while (!infile.eof())
{
getline(infile, sLine);
if (sLine.size() != 0)
{
std::vector<std::string> results;
StringSplit(sLine, ";", results);
if (results.size() == 3)
{
_tCustomIcon cImage;
cImage.idx = index++;
cImage.RootFile = results[0];
cImage.Title = results[1];
cImage.Description = results[2];
m_custom_light_icons.push_back(cImage);
m_custom_light_icons_lookup[cImage.idx] = m_custom_light_icons.size() - 1;
}
}
}
infile.close();
}
//Now get them from the database (idx 100+)
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID,Base,Name,Description FROM CustomImages");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int ID = atoi(sd[0].c_str());
_tCustomIcon cImage;
cImage.idx = 100 + ID;
cImage.RootFile = sd[1];
cImage.Title = sd[2];
cImage.Description = sd[3];
std::string IconFile16 = cImage.RootFile + ".png";
std::string IconFile48On = cImage.RootFile + "48_On.png";
std::string IconFile48Off = cImage.RootFile + "48_Off.png";
std::map<std::string, std::string> _dbImageFiles;
_dbImageFiles["IconSmall"] = szWWWFolder + "/images/" + IconFile16;
_dbImageFiles["IconOn"] = szWWWFolder + "/images/" + IconFile48On;
_dbImageFiles["IconOff"] = szWWWFolder + "/images/" + IconFile48Off;
//Check if files are on disk, else add them
for (const auto & iItt : _dbImageFiles)
{
std::string TableField = iItt.first;
std::string IconFile = iItt.second;
if (!file_exist(IconFile.c_str()))
{
//Does not exists, extract it from the database and add it
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_queryBlob("SELECT %s FROM CustomImages WHERE ID=%d", TableField.c_str(), ID);
if (!result2.empty())
{
std::ofstream file;
file.open(IconFile.c_str(), std::ios::out | std::ios::binary);
if (!file.is_open())
return;
file << result2[0][0];
file.close();
}
}
}
m_custom_light_icons.push_back(cImage);
m_custom_light_icons_lookup[cImage.idx] = m_custom_light_icons.size() - 1;
ii++;
}
}
}
bool CWebServer::StartServer(server_settings & settings, const std::string & serverpath, const bool bIgnoreUsernamePassword)
{
m_server_alias = (settings.is_secure() == true) ? "SSL" : "HTTP";
if (!settings.is_enabled())
return true;
ReloadCustomSwitchIcons();
int tries = 0;
bool exception = false;
//_log.Log(LOG_STATUS, "CWebServer::StartServer() : settings : %s", settings.to_string().c_str());
do {
try {
exception = false;
m_pWebEm = new http::server::cWebem(settings, serverpath.c_str());
}
catch (std::exception& e) {
exception = true;
switch (tries) {
case 0:
settings.listening_address = "::";
break;
case 1:
settings.listening_address = "0.0.0.0";
break;
case 2:
_log.Log(LOG_ERROR, "WebServer(%s) startup failed on address %s with port: %s: %s", m_server_alias.c_str(), settings.listening_address.c_str(), settings.listening_port.c_str(), e.what());
if (atoi(settings.listening_port.c_str()) < 1024)
_log.Log(LOG_ERROR, "WebServer(%s) check privileges for opening ports below 1024", m_server_alias.c_str());
else
_log.Log(LOG_ERROR, "WebServer(%s) check if no other application is using port: %s", m_server_alias.c_str(), settings.listening_port.c_str());
return false;
}
tries++;
}
} while (exception);
_log.Log(LOG_STATUS, "WebServer(%s) started on address: %s with port %s", m_server_alias.c_str(), settings.listening_address.c_str(), settings.listening_port.c_str());
m_pWebEm->SetDigistRealm("Domoticz.com");
m_pWebEm->SetSessionStore(this);
if (!bIgnoreUsernamePassword)
{
LoadUsers();
std::string WebLocalNetworks;
int nValue;
if (m_sql.GetPreferencesVar("WebLocalNetworks", nValue, WebLocalNetworks))
{
std::vector<std::string> strarray;
StringSplit(WebLocalNetworks, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddLocalNetworks(itt);
//add local hostname
m_pWebEm->AddLocalNetworks("");
}
}
std::string WebRemoteProxyIPs;
int nValue;
if (m_sql.GetPreferencesVar("WebRemoteProxyIPs", nValue, WebRemoteProxyIPs))
{
std::vector<std::string> strarray;
StringSplit(WebRemoteProxyIPs, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddRemoteProxyIPs(itt);
}
//register callbacks
m_pWebEm->RegisterIncludeCode("switchtypes", boost::bind(&CWebServer::DisplaySwitchTypesCombo, this, _1));
m_pWebEm->RegisterIncludeCode("metertypes", boost::bind(&CWebServer::DisplayMeterTypesCombo, this, _1));
m_pWebEm->RegisterIncludeCode("timertypes", boost::bind(&CWebServer::DisplayTimerTypesCombo, this, _1));
m_pWebEm->RegisterIncludeCode("combolanguage", boost::bind(&CWebServer::DisplayLanguageCombo, this, _1));
m_pWebEm->RegisterPageCode("/json.htm", boost::bind(&CWebServer::GetJSonPage, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/uploadcustomicon", boost::bind(&CWebServer::Post_UploadCustomIcon, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/html5.appcache", boost::bind(&CWebServer::GetAppCache, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/camsnapshot.jpg", boost::bind(&CWebServer::GetCameraSnapshot, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/backupdatabase.php", boost::bind(&CWebServer::GetDatabaseBackup, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/raspberry.cgi", boost::bind(&CWebServer::GetInternalCameraSnapshot, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/uvccapture.cgi", boost::bind(&CWebServer::GetInternalCameraSnapshot, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/images/floorplans/plan", boost::bind(&CWebServer::GetFloorplanImage, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("storesettings", boost::bind(&CWebServer::PostSettings, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setrfxcommode", boost::bind(&CWebServer::SetRFXCOMMode, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("rfxupgradefirmware", boost::bind(&CWebServer::RFXComUpgradeFirmware, this, _1, _2, _3));
RegisterCommandCode("rfxfirmwaregetpercentage", boost::bind(&CWebServer::Cmd_RFXComGetFirmwarePercentage, this, _1, _2, _3), true);
m_pWebEm->RegisterActionCode("setrego6xxtype", boost::bind(&CWebServer::SetRego6XXType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("sets0metertype", boost::bind(&CWebServer::SetS0MeterType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setlimitlesstype", boost::bind(&CWebServer::SetLimitlessType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("uploadfloorplanimage", boost::bind(&CWebServer::UploadFloorplanImage, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setopenthermsettings", boost::bind(&CWebServer::SetOpenThermSettings, this, _1, _2, _3));
RegisterCommandCode("sendopenthermcommand", boost::bind(&CWebServer::Cmd_SendOpenThermCommand, this, _1, _2, _3), true);
m_pWebEm->RegisterActionCode("reloadpiface", boost::bind(&CWebServer::ReloadPiFace, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("setcurrentcostmetertype", boost::bind(&CWebServer::SetCurrentCostUSBType, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("restoredatabase", boost::bind(&CWebServer::RestoreDatabase, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("sbfspotimportolddata", boost::bind(&CWebServer::SBFSpotImportOldData, this, _1, _2, _3));
m_pWebEm->RegisterActionCode("event_create", boost::bind(&CWebServer::EventCreate, this, _1, _2, _3));
RegisterCommandCode("getlanguage", boost::bind(&CWebServer::Cmd_GetLanguage, this, _1, _2, _3), true);
RegisterCommandCode("getthemes", boost::bind(&CWebServer::Cmd_GetThemes, this, _1, _2, _3), true);
RegisterCommandCode("gettitle", boost::bind(&CWebServer::Cmd_GetTitle, this, _1, _2, _3), true);
RegisterCommandCode("logincheck", boost::bind(&CWebServer::Cmd_LoginCheck, this, _1, _2, _3), true);
RegisterCommandCode("getversion", boost::bind(&CWebServer::Cmd_GetVersion, this, _1, _2, _3), true);
RegisterCommandCode("getlog", boost::bind(&CWebServer::Cmd_GetLog, this, _1, _2, _3));
RegisterCommandCode("clearlog", boost::bind(&CWebServer::Cmd_ClearLog, this, _1, _2, _3));
RegisterCommandCode("getauth", boost::bind(&CWebServer::Cmd_GetAuth, this, _1, _2, _3), true);
RegisterCommandCode("getuptime", boost::bind(&CWebServer::Cmd_GetUptime, this, _1, _2, _3), true);
RegisterCommandCode("gethardwaretypes", boost::bind(&CWebServer::Cmd_GetHardwareTypes, this, _1, _2, _3));
RegisterCommandCode("addhardware", boost::bind(&CWebServer::Cmd_AddHardware, this, _1, _2, _3));
RegisterCommandCode("updatehardware", boost::bind(&CWebServer::Cmd_UpdateHardware, this, _1, _2, _3));
RegisterCommandCode("deletehardware", boost::bind(&CWebServer::Cmd_DeleteHardware, this, _1, _2, _3));
RegisterCommandCode("addcamera", boost::bind(&CWebServer::Cmd_AddCamera, this, _1, _2, _3));
RegisterCommandCode("updatecamera", boost::bind(&CWebServer::Cmd_UpdateCamera, this, _1, _2, _3));
RegisterCommandCode("deletecamera", boost::bind(&CWebServer::Cmd_DeleteCamera, this, _1, _2, _3));
RegisterCommandCode("wolgetnodes", boost::bind(&CWebServer::Cmd_WOLGetNodes, this, _1, _2, _3));
RegisterCommandCode("woladdnode", boost::bind(&CWebServer::Cmd_WOLAddNode, this, _1, _2, _3));
RegisterCommandCode("wolupdatenode", boost::bind(&CWebServer::Cmd_WOLUpdateNode, this, _1, _2, _3));
RegisterCommandCode("wolremovenode", boost::bind(&CWebServer::Cmd_WOLRemoveNode, this, _1, _2, _3));
RegisterCommandCode("wolclearnodes", boost::bind(&CWebServer::Cmd_WOLClearNodes, this, _1, _2, _3));
RegisterCommandCode("mysensorsgetnodes", boost::bind(&CWebServer::Cmd_MySensorsGetNodes, this, _1, _2, _3));
RegisterCommandCode("mysensorsgetchilds", boost::bind(&CWebServer::Cmd_MySensorsGetChilds, this, _1, _2, _3));
RegisterCommandCode("mysensorsupdatenode", boost::bind(&CWebServer::Cmd_MySensorsUpdateNode, this, _1, _2, _3));
RegisterCommandCode("mysensorsremovenode", boost::bind(&CWebServer::Cmd_MySensorsRemoveNode, this, _1, _2, _3));
RegisterCommandCode("mysensorsremovechild", boost::bind(&CWebServer::Cmd_MySensorsRemoveChild, this, _1, _2, _3));
RegisterCommandCode("mysensorsupdatechild", boost::bind(&CWebServer::Cmd_MySensorsUpdateChild, this, _1, _2, _3));
RegisterCommandCode("pingersetmode", boost::bind(&CWebServer::Cmd_PingerSetMode, this, _1, _2, _3));
RegisterCommandCode("pingergetnodes", boost::bind(&CWebServer::Cmd_PingerGetNodes, this, _1, _2, _3));
RegisterCommandCode("pingeraddnode", boost::bind(&CWebServer::Cmd_PingerAddNode, this, _1, _2, _3));
RegisterCommandCode("pingerupdatenode", boost::bind(&CWebServer::Cmd_PingerUpdateNode, this, _1, _2, _3));
RegisterCommandCode("pingerremovenode", boost::bind(&CWebServer::Cmd_PingerRemoveNode, this, _1, _2, _3));
RegisterCommandCode("pingerclearnodes", boost::bind(&CWebServer::Cmd_PingerClearNodes, this, _1, _2, _3));
RegisterCommandCode("kodisetmode", boost::bind(&CWebServer::Cmd_KodiSetMode, this, _1, _2, _3));
RegisterCommandCode("kodigetnodes", boost::bind(&CWebServer::Cmd_KodiGetNodes, this, _1, _2, _3));
RegisterCommandCode("kodiaddnode", boost::bind(&CWebServer::Cmd_KodiAddNode, this, _1, _2, _3));
RegisterCommandCode("kodiupdatenode", boost::bind(&CWebServer::Cmd_KodiUpdateNode, this, _1, _2, _3));
RegisterCommandCode("kodiremovenode", boost::bind(&CWebServer::Cmd_KodiRemoveNode, this, _1, _2, _3));
RegisterCommandCode("kodiclearnodes", boost::bind(&CWebServer::Cmd_KodiClearNodes, this, _1, _2, _3));
RegisterCommandCode("kodimediacommand", boost::bind(&CWebServer::Cmd_KodiMediaCommand, this, _1, _2, _3));
RegisterCommandCode("panasonicsetmode", boost::bind(&CWebServer::Cmd_PanasonicSetMode, this, _1, _2, _3));
RegisterCommandCode("panasonicgetnodes", boost::bind(&CWebServer::Cmd_PanasonicGetNodes, this, _1, _2, _3));
RegisterCommandCode("panasonicaddnode", boost::bind(&CWebServer::Cmd_PanasonicAddNode, this, _1, _2, _3));
RegisterCommandCode("panasonicupdatenode", boost::bind(&CWebServer::Cmd_PanasonicUpdateNode, this, _1, _2, _3));
RegisterCommandCode("panasonicremovenode", boost::bind(&CWebServer::Cmd_PanasonicRemoveNode, this, _1, _2, _3));
RegisterCommandCode("panasonicclearnodes", boost::bind(&CWebServer::Cmd_PanasonicClearNodes, this, _1, _2, _3));
RegisterCommandCode("panasonicmediacommand", boost::bind(&CWebServer::Cmd_PanasonicMediaCommand, this, _1, _2, _3));
RegisterCommandCode("heossetmode", boost::bind(&CWebServer::Cmd_HEOSSetMode, this, _1, _2, _3));
RegisterCommandCode("heosmediacommand", boost::bind(&CWebServer::Cmd_HEOSMediaCommand, this, _1, _2, _3));
RegisterCommandCode("onkyoeiscpcommand", boost::bind(&CWebServer::Cmd_OnkyoEiscpCommand, this, _1, _2, _3));
RegisterCommandCode("bleboxsetmode", boost::bind(&CWebServer::Cmd_BleBoxSetMode, this, _1, _2, _3));
RegisterCommandCode("bleboxgetnodes", boost::bind(&CWebServer::Cmd_BleBoxGetNodes, this, _1, _2, _3));
RegisterCommandCode("bleboxaddnode", boost::bind(&CWebServer::Cmd_BleBoxAddNode, this, _1, _2, _3));
RegisterCommandCode("bleboxremovenode", boost::bind(&CWebServer::Cmd_BleBoxRemoveNode, this, _1, _2, _3));
RegisterCommandCode("bleboxclearnodes", boost::bind(&CWebServer::Cmd_BleBoxClearNodes, this, _1, _2, _3));
RegisterCommandCode("bleboxautosearchingnodes", boost::bind(&CWebServer::Cmd_BleBoxAutoSearchingNodes, this, _1, _2, _3));
RegisterCommandCode("bleboxupdatefirmware", boost::bind(&CWebServer::Cmd_BleBoxUpdateFirmware, this, _1, _2, _3));
RegisterCommandCode("lmssetmode", boost::bind(&CWebServer::Cmd_LMSSetMode, this, _1, _2, _3));
RegisterCommandCode("lmsgetnodes", boost::bind(&CWebServer::Cmd_LMSGetNodes, this, _1, _2, _3));
RegisterCommandCode("lmsgetplaylists", boost::bind(&CWebServer::Cmd_LMSGetPlaylists, this, _1, _2, _3));
RegisterCommandCode("lmsmediacommand", boost::bind(&CWebServer::Cmd_LMSMediaCommand, this, _1, _2, _3));
RegisterCommandCode("lmsdeleteunuseddevices", boost::bind(&CWebServer::Cmd_LMSDeleteUnusedDevices, this, _1, _2, _3));
RegisterCommandCode("savefibarolinkconfig", boost::bind(&CWebServer::Cmd_SaveFibaroLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getfibarolinkconfig", boost::bind(&CWebServer::Cmd_GetFibaroLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getfibarolinks", boost::bind(&CWebServer::Cmd_GetFibaroLinks, this, _1, _2, _3));
RegisterCommandCode("savefibarolink", boost::bind(&CWebServer::Cmd_SaveFibaroLink, this, _1, _2, _3));
RegisterCommandCode("deletefibarolink", boost::bind(&CWebServer::Cmd_DeleteFibaroLink, this, _1, _2, _3));
RegisterCommandCode("saveinfluxlinkconfig", boost::bind(&CWebServer::Cmd_SaveInfluxLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getinfluxlinkconfig", boost::bind(&CWebServer::Cmd_GetInfluxLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getinfluxlinks", boost::bind(&CWebServer::Cmd_GetInfluxLinks, this, _1, _2, _3));
RegisterCommandCode("saveinfluxlink", boost::bind(&CWebServer::Cmd_SaveInfluxLink, this, _1, _2, _3));
RegisterCommandCode("deleteinfluxlink", boost::bind(&CWebServer::Cmd_DeleteInfluxLink, this, _1, _2, _3));
RegisterCommandCode("savehttplinkconfig", boost::bind(&CWebServer::Cmd_SaveHttpLinkConfig, this, _1, _2, _3));
RegisterCommandCode("gethttplinkconfig", boost::bind(&CWebServer::Cmd_GetHttpLinkConfig, this, _1, _2, _3));
RegisterCommandCode("gethttplinks", boost::bind(&CWebServer::Cmd_GetHttpLinks, this, _1, _2, _3));
RegisterCommandCode("savehttplink", boost::bind(&CWebServer::Cmd_SaveHttpLink, this, _1, _2, _3));
RegisterCommandCode("deletehttplink", boost::bind(&CWebServer::Cmd_DeleteHttpLink, this, _1, _2, _3));
RegisterCommandCode("savegooglepubsublinkconfig", boost::bind(&CWebServer::Cmd_SaveGooglePubSubLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getgooglepubsublinkconfig", boost::bind(&CWebServer::Cmd_GetGooglePubSubLinkConfig, this, _1, _2, _3));
RegisterCommandCode("getgooglepubsublinks", boost::bind(&CWebServer::Cmd_GetGooglePubSubLinks, this, _1, _2, _3));
RegisterCommandCode("savegooglepubsublink", boost::bind(&CWebServer::Cmd_SaveGooglePubSubLink, this, _1, _2, _3));
RegisterCommandCode("deletegooglepubsublink", boost::bind(&CWebServer::Cmd_DeleteGooglePubSubLink, this, _1, _2, _3));
RegisterCommandCode("getdevicevalueoptions", boost::bind(&CWebServer::Cmd_GetDeviceValueOptions, this, _1, _2, _3));
RegisterCommandCode("getdevicevalueoptionwording", boost::bind(&CWebServer::Cmd_GetDeviceValueOptionWording, this, _1, _2, _3));
RegisterCommandCode("adduservariable", boost::bind(&CWebServer::Cmd_AddUserVariable, this, _1, _2, _3));
RegisterCommandCode("updateuservariable", boost::bind(&CWebServer::Cmd_UpdateUserVariable, this, _1, _2, _3));
RegisterCommandCode("deleteuservariable", boost::bind(&CWebServer::Cmd_DeleteUserVariable, this, _1, _2, _3));
RegisterCommandCode("getuservariables", boost::bind(&CWebServer::Cmd_GetUserVariables, this, _1, _2, _3));
RegisterCommandCode("getuservariable", boost::bind(&CWebServer::Cmd_GetUserVariable, this, _1, _2, _3));
RegisterCommandCode("allownewhardware", boost::bind(&CWebServer::Cmd_AllowNewHardware, this, _1, _2, _3));
RegisterCommandCode("addplan", boost::bind(&CWebServer::Cmd_AddPlan, this, _1, _2, _3));
RegisterCommandCode("updateplan", boost::bind(&CWebServer::Cmd_UpdatePlan, this, _1, _2, _3));
RegisterCommandCode("deleteplan", boost::bind(&CWebServer::Cmd_DeletePlan, this, _1, _2, _3));
RegisterCommandCode("getunusedplandevices", boost::bind(&CWebServer::Cmd_GetUnusedPlanDevices, this, _1, _2, _3));
RegisterCommandCode("addplanactivedevice", boost::bind(&CWebServer::Cmd_AddPlanActiveDevice, this, _1, _2, _3));
RegisterCommandCode("getplandevices", boost::bind(&CWebServer::Cmd_GetPlanDevices, this, _1, _2, _3));
RegisterCommandCode("deleteplandevice", boost::bind(&CWebServer::Cmd_DeletePlanDevice, this, _1, _2, _3));
RegisterCommandCode("setplandevicecoords", boost::bind(&CWebServer::Cmd_SetPlanDeviceCoords, this, _1, _2, _3));
RegisterCommandCode("deleteallplandevices", boost::bind(&CWebServer::Cmd_DeleteAllPlanDevices, this, _1, _2, _3));
RegisterCommandCode("changeplanorder", boost::bind(&CWebServer::Cmd_ChangePlanOrder, this, _1, _2, _3));
RegisterCommandCode("changeplandeviceorder", boost::bind(&CWebServer::Cmd_ChangePlanDeviceOrder, this, _1, _2, _3));
RegisterCommandCode("gettimerplans", boost::bind(&CWebServer::Cmd_GetTimerPlans, this, _1, _2, _3));
RegisterCommandCode("addtimerplan", boost::bind(&CWebServer::Cmd_AddTimerPlan, this, _1, _2, _3));
RegisterCommandCode("updatetimerplan", boost::bind(&CWebServer::Cmd_UpdateTimerPlan, this, _1, _2, _3));
RegisterCommandCode("deletetimerplan", boost::bind(&CWebServer::Cmd_DeleteTimerPlan, this, _1, _2, _3));
RegisterCommandCode("duplicatetimerplan", boost::bind(&CWebServer::Cmd_DuplicateTimerPlan, this, _1, _2, _3));
RegisterCommandCode("getactualhistory", boost::bind(&CWebServer::Cmd_GetActualHistory, this, _1, _2, _3));
RegisterCommandCode("getnewhistory", boost::bind(&CWebServer::Cmd_GetNewHistory, this, _1, _2, _3));
RegisterCommandCode("getconfig", boost::bind(&CWebServer::Cmd_GetConfig, this, _1, _2, _3), true);
RegisterCommandCode("sendnotification", boost::bind(&CWebServer::Cmd_SendNotification, this, _1, _2, _3));
RegisterCommandCode("emailcamerasnapshot", boost::bind(&CWebServer::Cmd_EmailCameraSnapshot, this, _1, _2, _3));
RegisterCommandCode("udevice", boost::bind(&CWebServer::Cmd_UpdateDevice, this, _1, _2, _3));
RegisterCommandCode("udevices", boost::bind(&CWebServer::Cmd_UpdateDevices, this, _1, _2, _3));
RegisterCommandCode("thermostatstate", boost::bind(&CWebServer::Cmd_SetThermostatState, this, _1, _2, _3));
RegisterCommandCode("system_shutdown", boost::bind(&CWebServer::Cmd_SystemShutdown, this, _1, _2, _3));
RegisterCommandCode("system_reboot", boost::bind(&CWebServer::Cmd_SystemReboot, this, _1, _2, _3));
RegisterCommandCode("execute_script", boost::bind(&CWebServer::Cmd_ExcecuteScript, this, _1, _2, _3));
RegisterCommandCode("getcosts", boost::bind(&CWebServer::Cmd_GetCosts, this, _1, _2, _3));
RegisterCommandCode("checkforupdate", boost::bind(&CWebServer::Cmd_CheckForUpdate, this, _1, _2, _3));
RegisterCommandCode("downloadupdate", boost::bind(&CWebServer::Cmd_DownloadUpdate, this, _1, _2, _3));
RegisterCommandCode("downloadready", boost::bind(&CWebServer::Cmd_DownloadReady, this, _1, _2, _3));
RegisterCommandCode("deletedatapoint", boost::bind(&CWebServer::Cmd_DeleteDatePoint, this, _1, _2, _3));
RegisterCommandCode("setactivetimerplan", boost::bind(&CWebServer::Cmd_SetActiveTimerPlan, this, _1, _2, _3));
RegisterCommandCode("addtimer", boost::bind(&CWebServer::Cmd_AddTimer, this, _1, _2, _3));
RegisterCommandCode("updatetimer", boost::bind(&CWebServer::Cmd_UpdateTimer, this, _1, _2, _3));
RegisterCommandCode("deletetimer", boost::bind(&CWebServer::Cmd_DeleteTimer, this, _1, _2, _3));
RegisterCommandCode("enabletimer", boost::bind(&CWebServer::Cmd_EnableTimer, this, _1, _2, _3));
RegisterCommandCode("disabletimer", boost::bind(&CWebServer::Cmd_DisableTimer, this, _1, _2, _3));
RegisterCommandCode("cleartimers", boost::bind(&CWebServer::Cmd_ClearTimers, this, _1, _2, _3));
RegisterCommandCode("addscenetimer", boost::bind(&CWebServer::Cmd_AddSceneTimer, this, _1, _2, _3));
RegisterCommandCode("updatescenetimer", boost::bind(&CWebServer::Cmd_UpdateSceneTimer, this, _1, _2, _3));
RegisterCommandCode("deletescenetimer", boost::bind(&CWebServer::Cmd_DeleteSceneTimer, this, _1, _2, _3));
RegisterCommandCode("enablescenetimer", boost::bind(&CWebServer::Cmd_EnableSceneTimer, this, _1, _2, _3));
RegisterCommandCode("disablescenetimer", boost::bind(&CWebServer::Cmd_DisableSceneTimer, this, _1, _2, _3));
RegisterCommandCode("clearscenetimers", boost::bind(&CWebServer::Cmd_ClearSceneTimers, this, _1, _2, _3));
RegisterCommandCode("getsceneactivations", boost::bind(&CWebServer::Cmd_GetSceneActivations, this, _1, _2, _3));
RegisterCommandCode("addscenecode", boost::bind(&CWebServer::Cmd_AddSceneCode, this, _1, _2, _3));
RegisterCommandCode("removescenecode", boost::bind(&CWebServer::Cmd_RemoveSceneCode, this, _1, _2, _3));
RegisterCommandCode("clearscenecodes", boost::bind(&CWebServer::Cmd_ClearSceneCodes, this, _1, _2, _3));
RegisterCommandCode("renamescene", boost::bind(&CWebServer::Cmd_RenameScene, this, _1, _2, _3));
RegisterCommandCode("setsetpoint", boost::bind(&CWebServer::Cmd_SetSetpoint, this, _1, _2, _3));
RegisterCommandCode("addsetpointtimer", boost::bind(&CWebServer::Cmd_AddSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("updatesetpointtimer", boost::bind(&CWebServer::Cmd_UpdateSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("deletesetpointtimer", boost::bind(&CWebServer::Cmd_DeleteSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("enablesetpointtimer", boost::bind(&CWebServer::Cmd_EnableSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("disablesetpointtimer", boost::bind(&CWebServer::Cmd_DisableSetpointTimer, this, _1, _2, _3));
RegisterCommandCode("clearsetpointtimers", boost::bind(&CWebServer::Cmd_ClearSetpointTimers, this, _1, _2, _3));
RegisterCommandCode("serial_devices", boost::bind(&CWebServer::Cmd_GetSerialDevices, this, _1, _2, _3));
RegisterCommandCode("devices_list", boost::bind(&CWebServer::Cmd_GetDevicesList, this, _1, _2, _3));
RegisterCommandCode("devices_list_onoff", boost::bind(&CWebServer::Cmd_GetDevicesListOnOff, this, _1, _2, _3));
RegisterCommandCode("registerhue", boost::bind(&CWebServer::Cmd_PhilipsHueRegister, this, _1, _2, _3));
RegisterCommandCode("getcustomiconset", boost::bind(&CWebServer::Cmd_GetCustomIconSet, this, _1, _2, _3));
RegisterCommandCode("deletecustomicon", boost::bind(&CWebServer::Cmd_DeleteCustomIcon, this, _1, _2, _3));
RegisterCommandCode("updatecustomicon", boost::bind(&CWebServer::Cmd_UpdateCustomIcon, this, _1, _2, _3));
RegisterCommandCode("renamedevice", boost::bind(&CWebServer::Cmd_RenameDevice, this, _1, _2, _3));
RegisterCommandCode("setunused", boost::bind(&CWebServer::Cmd_SetUnused, this, _1, _2, _3));
RegisterCommandCode("addlogmessage", boost::bind(&CWebServer::Cmd_AddLogMessage, this, _1, _2, _3));
RegisterCommandCode("clearshortlog", boost::bind(&CWebServer::Cmd_ClearShortLog, this, _1, _2, _3));
RegisterCommandCode("vacuumdatabase", boost::bind(&CWebServer::Cmd_VacuumDatabase, this, _1, _2, _3));
RegisterCommandCode("addmobiledevice", boost::bind(&CWebServer::Cmd_AddMobileDevice, this, _1, _2, _3));
RegisterCommandCode("updatemobiledevice", boost::bind(&CWebServer::Cmd_UpdateMobileDevice, this, _1, _2, _3));
RegisterCommandCode("deletemobiledevice", boost::bind(&CWebServer::Cmd_DeleteMobileDevice, this, _1, _2, _3));
RegisterCommandCode("addyeelight", boost::bind(&CWebServer::Cmd_AddYeeLight, this, _1, _2, _3));
RegisterCommandCode("addArilux", boost::bind(&CWebServer::Cmd_AddArilux, this, _1, _2, _3));
RegisterRType("graph", boost::bind(&CWebServer::RType_HandleGraph, this, _1, _2, _3));
RegisterRType("lightlog", boost::bind(&CWebServer::RType_LightLog, this, _1, _2, _3));
RegisterRType("textlog", boost::bind(&CWebServer::RType_TextLog, this, _1, _2, _3));
RegisterRType("scenelog", boost::bind(&CWebServer::RType_SceneLog, this, _1, _2, _3));
RegisterRType("settings", boost::bind(&CWebServer::RType_Settings, this, _1, _2, _3));
RegisterRType("events", boost::bind(&CWebServer::RType_Events, this, _1, _2, _3));
RegisterRType("hardware", boost::bind(&CWebServer::RType_Hardware, this, _1, _2, _3));
RegisterRType("devices", boost::bind(&CWebServer::RType_Devices, this, _1, _2, _3));
RegisterRType("deletedevice", boost::bind(&CWebServer::RType_DeleteDevice, this, _1, _2, _3));
RegisterRType("cameras", boost::bind(&CWebServer::RType_Cameras, this, _1, _2, _3));
RegisterRType("cameras_user", boost::bind(&CWebServer::RType_CamerasUser, this, _1, _2, _3));
RegisterRType("users", boost::bind(&CWebServer::RType_Users, this, _1, _2, _3));
RegisterRType("mobiles", boost::bind(&CWebServer::RType_Mobiles, this, _1, _2, _3));
RegisterRType("timers", boost::bind(&CWebServer::RType_Timers, this, _1, _2, _3));
RegisterRType("scenetimers", boost::bind(&CWebServer::RType_SceneTimers, this, _1, _2, _3));
RegisterRType("setpointtimers", boost::bind(&CWebServer::RType_SetpointTimers, this, _1, _2, _3));
RegisterRType("gettransfers", boost::bind(&CWebServer::RType_GetTransfers, this, _1, _2, _3));
RegisterRType("transferdevice", boost::bind(&CWebServer::RType_TransferDevice, this, _1, _2, _3));
RegisterRType("notifications", boost::bind(&CWebServer::RType_Notifications, this, _1, _2, _3));
RegisterRType("schedules", boost::bind(&CWebServer::RType_Schedules, this, _1, _2, _3));
RegisterRType("getshareduserdevices", boost::bind(&CWebServer::RType_GetSharedUserDevices, this, _1, _2, _3));
RegisterRType("setshareduserdevices", boost::bind(&CWebServer::RType_SetSharedUserDevices, this, _1, _2, _3));
RegisterRType("setused", boost::bind(&CWebServer::RType_SetUsed, this, _1, _2, _3));
RegisterRType("scenes", boost::bind(&CWebServer::RType_Scenes, this, _1, _2, _3));
RegisterRType("addscene", boost::bind(&CWebServer::RType_AddScene, this, _1, _2, _3));
RegisterRType("deletescene", boost::bind(&CWebServer::RType_DeleteScene, this, _1, _2, _3));
RegisterRType("updatescene", boost::bind(&CWebServer::RType_UpdateScene, this, _1, _2, _3));
RegisterRType("createvirtualsensor", boost::bind(&CWebServer::RType_CreateMappedSensor, this, _1, _2, _3));
RegisterRType("createdevice", boost::bind(&CWebServer::RType_CreateDevice, this, _1, _2, _3));
RegisterRType("createevohomesensor", boost::bind(&CWebServer::RType_CreateEvohomeSensor, this, _1, _2, _3));
RegisterRType("bindevohome", boost::bind(&CWebServer::RType_BindEvohome, this, _1, _2, _3));
RegisterRType("createrflinkdevice", boost::bind(&CWebServer::RType_CreateRFLinkDevice, this, _1, _2, _3));
RegisterRType("custom_light_icons", boost::bind(&CWebServer::RType_CustomLightIcons, this, _1, _2, _3));
RegisterRType("plans", boost::bind(&CWebServer::RType_Plans, this, _1, _2, _3));
RegisterRType("floorplans", boost::bind(&CWebServer::RType_FloorPlans, this, _1, _2, _3));
#ifdef WITH_OPENZWAVE
//ZWave
RegisterCommandCode("updatezwavenode", boost::bind(&CWebServer::Cmd_ZWaveUpdateNode, this, _1, _2, _3));
RegisterCommandCode("deletezwavenode", boost::bind(&CWebServer::Cmd_ZWaveDeleteNode, this, _1, _2, _3));
RegisterCommandCode("zwaveinclude", boost::bind(&CWebServer::Cmd_ZWaveInclude, this, _1, _2, _3));
RegisterCommandCode("zwaveexclude", boost::bind(&CWebServer::Cmd_ZWaveExclude, this, _1, _2, _3));
RegisterCommandCode("zwaveisnodeincluded", boost::bind(&CWebServer::Cmd_ZWaveIsNodeIncluded, this, _1, _2, _3));
RegisterCommandCode("zwaveisnodeexcluded", boost::bind(&CWebServer::Cmd_ZWaveIsNodeExcluded, this, _1, _2, _3));
RegisterCommandCode("zwavesoftreset", boost::bind(&CWebServer::Cmd_ZWaveSoftReset, this, _1, _2, _3));
RegisterCommandCode("zwavehardreset", boost::bind(&CWebServer::Cmd_ZWaveHardReset, this, _1, _2, _3));
RegisterCommandCode("zwavenetworkheal", boost::bind(&CWebServer::Cmd_ZWaveNetworkHeal, this, _1, _2, _3));
RegisterCommandCode("zwavenodeheal", boost::bind(&CWebServer::Cmd_ZWaveNodeHeal, this, _1, _2, _3));
RegisterCommandCode("zwavenetworkinfo", boost::bind(&CWebServer::Cmd_ZWaveNetworkInfo, this, _1, _2, _3));
RegisterCommandCode("zwaveremovegroupnode", boost::bind(&CWebServer::Cmd_ZWaveRemoveGroupNode, this, _1, _2, _3));
RegisterCommandCode("zwaveaddgroupnode", boost::bind(&CWebServer::Cmd_ZWaveAddGroupNode, this, _1, _2, _3));
RegisterCommandCode("zwavegroupinfo", boost::bind(&CWebServer::Cmd_ZWaveGroupInfo, this, _1, _2, _3));
RegisterCommandCode("zwavecancel", boost::bind(&CWebServer::Cmd_ZWaveCancel, this, _1, _2, _3));
RegisterCommandCode("applyzwavenodeconfig", boost::bind(&CWebServer::Cmd_ApplyZWaveNodeConfig, this, _1, _2, _3));
RegisterCommandCode("requestzwavenodeconfig", boost::bind(&CWebServer::Cmd_ZWaveRequestNodeConfig, this, _1, _2, _3));
RegisterCommandCode("zwavestatecheck", boost::bind(&CWebServer::Cmd_ZWaveStateCheck, this, _1, _2, _3));
RegisterCommandCode("zwavereceiveconfigurationfromothercontroller", boost::bind(&CWebServer::Cmd_ZWaveReceiveConfigurationFromOtherController, this, _1, _2, _3));
RegisterCommandCode("zwavesendconfigurationtosecondcontroller", boost::bind(&CWebServer::Cmd_ZWaveSendConfigurationToSecondaryController, this, _1, _2, _3));
RegisterCommandCode("zwavetransferprimaryrole", boost::bind(&CWebServer::Cmd_ZWaveTransferPrimaryRole, this, _1, _2, _3));
RegisterCommandCode("zwavestartusercodeenrollmentmode", boost::bind(&CWebServer::Cmd_ZWaveSetUserCodeEnrollmentMode, this, _1, _2, _3));
RegisterCommandCode("zwavegetusercodes", boost::bind(&CWebServer::Cmd_ZWaveGetNodeUserCodes, this, _1, _2, _3));
RegisterCommandCode("zwaveremoveusercode", boost::bind(&CWebServer::Cmd_ZWaveRemoveUserCode, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/zwavegetconfig.php", boost::bind(&CWebServer::ZWaveGetConfigFile, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/poll.xml", boost::bind(&CWebServer::ZWaveCPPollXml, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/cp.html", boost::bind(&CWebServer::ZWaveCPIndex, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/confparmpost.html", boost::bind(&CWebServer::ZWaveCPNodeGetConf, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/refreshpost.html", boost::bind(&CWebServer::ZWaveCPNodeGetValues, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/valuepost.html", boost::bind(&CWebServer::ZWaveCPNodeSetValue, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/buttonpost.html", boost::bind(&CWebServer::ZWaveCPNodeSetButton, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/admpost.html", boost::bind(&CWebServer::ZWaveCPAdminCommand, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/nodepost.html", boost::bind(&CWebServer::ZWaveCPNodeChange, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/savepost.html", boost::bind(&CWebServer::ZWaveCPSaveConfig, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/thpost.html", boost::bind(&CWebServer::ZWaveCPTestHeal, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/topopost.html", boost::bind(&CWebServer::ZWaveCPGetTopo, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/statpost.html", boost::bind(&CWebServer::ZWaveCPGetStats, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/grouppost.html", boost::bind(&CWebServer::ZWaveCPSetGroup, this, _1, _2, _3));
m_pWebEm->RegisterPageCode("/ozwcp/scenepost.html", boost::bind(&CWebServer::ZWaveCPSceneCommand, this, _1, _2, _3));
//
//pollpost.html
//scenepost.html
//thpost.html
RegisterRType("openzwavenodes", boost::bind(&CWebServer::RType_OpenZWaveNodes, this, _1, _2, _3));
#endif
RegisterCommandCode("tellstickApplySettings", boost::bind(&CWebServer::Cmd_TellstickApplySettings, this, _1, _2, _3));
m_pWebEm->RegisterWhitelistURLString("/html5.appcache");
m_pWebEm->RegisterWhitelistURLString("/images/floorplans/plan");
//Start normal worker thread
m_bDoStop = false;
m_thread = std::make_shared<std::thread>(&CWebServer::Do_Work, this);
std::string server_name = "WebServer_" + settings.listening_port;
SetThreadName(m_thread->native_handle(), server_name.c_str());
return (m_thread != nullptr);
}
void CWebServer::StopServer()
{
m_bDoStop = true;
try
{
if (m_pWebEm == NULL)
return;
m_pWebEm->Stop();
if (m_thread) {
m_thread->join();
m_thread.reset();
}
delete m_pWebEm;
m_pWebEm = NULL;
}
catch (...)
{
}
}
void CWebServer::SetWebCompressionMode(const _eWebCompressionMode gzmode)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetWebCompressionMode(gzmode);
}
void CWebServer::SetAuthenticationMethod(const _eAuthenticationMethod amethod)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetAuthenticationMethod(amethod);
}
void CWebServer::SetWebTheme(const std::string &themename)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetWebTheme(themename);
}
void CWebServer::SetWebRoot(const std::string &webRoot)
{
if (m_pWebEm == NULL)
return;
m_pWebEm->SetWebRoot(webRoot);
}
void CWebServer::RegisterCommandCode(const char* idname, webserver_response_function ResponseFunction, bool bypassAuthentication)
{
m_webcommands.insert(std::pair<std::string, webserver_response_function >(std::string(idname), ResponseFunction));
if (bypassAuthentication)
{
m_pWebEm->RegisterWhitelistURLString(idname);
}
}
void CWebServer::RegisterRType(const char* idname, webserver_response_function ResponseFunction)
{
m_webrtypes.insert(std::pair<std::string, webserver_response_function >(std::string(idname), ResponseFunction));
}
void CWebServer::HandleRType(const std::string &rtype, WebEmSession & session, const request& req, Json::Value &root)
{
std::map < std::string, webserver_response_function >::iterator pf = m_webrtypes.find(rtype);
if (pf != m_webrtypes.end())
{
pf->second(session, req, root);
}
}
void CWebServer::GetAppCache(WebEmSession & session, const request& req, reply & rep)
{
std::string response = "";
if (g_bDontCacheWWW)
{
return;
}
//Return the appcache file (dynamically generated)
std::string sLine;
std::string filename = szWWWFolder + "/html5.appcache";
std::string sWebTheme = "default";
m_sql.GetPreferencesVar("WebTheme", sWebTheme);
//Get Dynamic Theme Files
std::map<std::string, int> _ThemeFiles;
GetDirFilesRecursive(szWWWFolder + "/styles/" + sWebTheme + "/", _ThemeFiles);
//Get Dynamic Floorplan Images from database
std::map<std::string, int> _FloorplanFiles;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM Floorplans ORDER BY [Order]");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ImageURL = "images/floorplans/plan?idx=" + sd[0];
_FloorplanFiles[ImageURL] = 1;
}
}
std::ifstream is(filename.c_str());
if (is)
{
while (!is.eof())
{
getline(is, sLine);
if (!sLine.empty())
{
if (sLine.find("#BuildHash") != std::string::npos)
{
stdreplace(sLine, "#BuildHash", szAppHash);
}
else if (sLine.find("#ThemeFiles") != std::string::npos)
{
response += "#Theme=" + sWebTheme + '\n';
//Add all theme files
for (const auto & itt : _ThemeFiles)
{
std::string tfname = itt.first.substr(szWWWFolder.size() + 1);
stdreplace(tfname, "styles/" + sWebTheme, "acttheme");
response += tfname + '\n';
}
continue;
}
else if (sLine.find("#Floorplans") != std::string::npos)
{
//Add all floorplans
for (const auto & itt : _FloorplanFiles)
{
std::string tfname = itt.first;
response += tfname + '\n';
}
continue;
}
else if (sLine.find("#SwitchIcons") != std::string::npos)
{
//Add database switch icons
for (const auto & itt : m_custom_light_icons)
{
if (itt.idx >= 100)
{
std::string IconFile16 = itt.RootFile + ".png";
std::string IconFile48On = itt.RootFile + "48_On.png";
std::string IconFile48Off = itt.RootFile + "48_Off.png";
response += "images/" + CURLEncode::URLEncode(IconFile16) + '\n';
response += "images/" + CURLEncode::URLEncode(IconFile48On) + '\n';
response += "images/" + CURLEncode::URLEncode(IconFile48Off) + '\n';
}
}
}
}
response += sLine + '\n';
}
}
reply::set_content(&rep, response);
}
void CWebServer::GetJSonPage(WebEmSession & session, const request& req, reply & rep)
{
Json::Value root;
root["status"] = "ERR";
std::string rtype = request::findValue(&req, "type");
if (rtype == "command")
{
std::string cparam = request::findValue(&req, "param");
if (cparam.empty())
{
cparam = request::findValue(&req, "dparam");
if (cparam.empty())
{
goto exitjson;
}
}
if (cparam == "dologout")
{
session.forcelogin = true;
root["status"] = "OK";
root["title"] = "Logout";
goto exitjson;
}
_log.Debug(DEBUG_WEBSERVER, "WEBS GetJSon :%s :%s ", cparam.c_str(), req.uri.c_str());
HandleCommand(cparam, session, req, root);
} //(rtype=="command")
else {
HandleRType(rtype, session, req, root);
}
exitjson:
std::string jcallback = request::findValue(&req, "jsoncallback");
if (jcallback.size() == 0) {
reply::set_content(&rep, root.toStyledString());
return;
}
reply::set_content(&rep, "var data=" + root.toStyledString() + '\n' + jcallback + "(data);");
}
void CWebServer::Cmd_GetLanguage(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sValue;
if (m_sql.GetPreferencesVar("Language", sValue))
{
root["status"] = "OK";
root["title"] = "GetLanguage";
root["language"] = sValue;
}
}
void CWebServer::Cmd_GetThemes(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetThemes";
m_mainworker.GetAvailableWebThemes();
int ii = 0;
for (const auto & itt : m_mainworker.m_webthemes)
{
root["result"][ii]["theme"] = itt;
ii++;
}
}
void CWebServer::Cmd_GetTitle(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sValue;
root["status"] = "OK";
root["title"] = "GetTitle";
if (m_sql.GetPreferencesVar("Title", sValue))
root["Title"] = sValue;
else
root["Title"] = "Domoticz";
}
void CWebServer::Cmd_LoginCheck(WebEmSession & session, const request& req, Json::Value &root)
{
std::string tmpusrname = request::findValue(&req, "username");
std::string tmpusrpass = request::findValue(&req, "password");
if (
(tmpusrname.empty()) ||
(tmpusrpass.empty())
)
return;
std::string rememberme = request::findValue(&req, "rememberme");
std::string usrname;
std::string usrpass;
if (request_handler::url_decode(tmpusrname, usrname))
{
if (request_handler::url_decode(tmpusrpass, usrpass))
{
usrname = base64_decode(usrname);
int iUser = FindUser(usrname.c_str());
if (iUser == -1) {
// log brute force attack
_log.Log(LOG_ERROR, "Failed login attempt from %s for user '%s' !", session.remote_host.c_str(), usrname.c_str());
return;
}
if (m_users[iUser].Password != usrpass) {
// log brute force attack
_log.Log(LOG_ERROR, "Failed login attempt from %s for '%s' !", session.remote_host.c_str(), m_users[iUser].Username.c_str());
return;
}
_log.Log(LOG_STATUS, "Login successful from %s for user '%s'", session.remote_host.c_str(), m_users[iUser].Username.c_str());
root["status"] = "OK";
root["version"] = szAppVersion;
root["title"] = "logincheck";
session.isnew = true;
session.username = m_users[iUser].Username;
session.rights = m_users[iUser].userrights;
session.rememberme = (rememberme == "true");
root["user"] = session.username;
root["rights"] = session.rights;
}
}
}
void CWebServer::Cmd_GetHardwareTypes(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "GetHardwareTypes";
std::map<std::string, int> _htypes;
for (int ii = 0; ii < HTYPE_END; ii++)
{
bool bDoAdd = true;
#ifndef _DEBUG
#ifdef WIN32
if (
(ii == HTYPE_RaspberryBMP085) ||
(ii == HTYPE_RaspberryHTU21D) ||
(ii == HTYPE_RaspberryTSL2561) ||
(ii == HTYPE_RaspberryPCF8574) ||
(ii == HTYPE_RaspberryBME280) ||
(ii == HTYPE_RaspberryMCP23017)
)
{
bDoAdd = false;
}
else
{
#ifndef WITH_LIBUSB
if (
(ii == HTYPE_VOLCRAFTCO20) ||
(ii == HTYPE_TE923)
)
{
bDoAdd = false;
}
#endif
}
#endif
#endif
#ifndef WITH_OPENZWAVE
if (ii == HTYPE_OpenZWave)
bDoAdd = false;
#endif
#ifndef WITH_GPIO
if (ii == HTYPE_RaspberryGPIO)
{
bDoAdd = false;
}
if (ii == HTYPE_SysfsGpio)
{
bDoAdd = false;
}
#endif
if (ii == HTYPE_PythonPlugin)
bDoAdd = false;
if (bDoAdd)
_htypes[Hardware_Type_Desc(ii)] = ii;
}
//return a sorted hardware list
int ii = 0;
for (const auto & itt : _htypes)
{
root["result"][ii]["idx"] = itt.second;
root["result"][ii]["name"] = itt.first;
ii++;
}
#ifdef ENABLE_PYTHON
// Append Plugin list as well
PluginList(root["result"]);
#endif
}
void CWebServer::Cmd_AddHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string name = CURLEncode::URLDecode(request::findValue(&req, "name"));
std::string senabled = request::findValue(&req, "enabled");
std::string shtype = request::findValue(&req, "htype");
std::string address = request::findValue(&req, "address");
std::string sport = request::findValue(&req, "port");
std::string username = CURLEncode::URLDecode(request::findValue(&req, "username"));
std::string password = CURLEncode::URLDecode(request::findValue(&req, "password"));
std::string extra = CURLEncode::URLDecode(request::findValue(&req, "extra"));
std::string sdatatimeout = request::findValue(&req, "datatimeout");
if (
(name.empty()) ||
(senabled.empty()) ||
(shtype.empty())
)
return;
_eHardwareTypes htype = (_eHardwareTypes)atoi(shtype.c_str());
int iDataTimeout = atoi(sdatatimeout.c_str());
int mode1 = 0;
int mode2 = 0;
int mode3 = 0;
int mode4 = 0;
int mode5 = 0;
int mode6 = 0;
int port = atoi(sport.c_str());
std::string mode1Str = request::findValue(&req, "Mode1");
if (!mode1Str.empty()) {
mode1 = atoi(mode1Str.c_str());
}
std::string mode2Str = request::findValue(&req, "Mode2");
if (!mode2Str.empty()) {
mode2 = atoi(mode2Str.c_str());
}
std::string mode3Str = request::findValue(&req, "Mode3");
if (!mode3Str.empty()) {
mode3 = atoi(mode3Str.c_str());
}
std::string mode4Str = request::findValue(&req, "Mode4");
if (!mode4Str.empty()) {
mode4 = atoi(mode4Str.c_str());
}
std::string mode5Str = request::findValue(&req, "Mode5");
if (!mode5Str.empty()) {
mode5 = atoi(mode5Str.c_str());
}
std::string mode6Str = request::findValue(&req, "Mode6");
if (!mode6Str.empty()) {
mode6 = atoi(mode6Str.c_str());
}
if (IsSerialDevice(htype))
{
//USB/System
if (sport.empty())
return; //need to have a serial port
if (htype == HTYPE_TeleinfoMeter) {
// Teleinfo always has decimals. Chances to have a P1 and a Teleinfo device on the same
// Domoticz instance are very low as both are national standards (NL and FR)
m_sql.UpdatePreferencesVar("SmartMeterType", 0);
}
}
else if (IsNetworkDevice(htype))
{
//Lan
if (address.empty() || port == 0)
return;
if (htype == HTYPE_MySensorsMQTT || htype == HTYPE_MQTT) {
std::string modeqStr = request::findValue(&req, "mode1");
if (!modeqStr.empty()) {
mode1 = atoi(modeqStr.c_str());
}
}
if (htype == HTYPE_ECODEVICES) {
// EcoDevices always have decimals. Chances to have a P1 and a EcoDevice/Teleinfo device on the same
// Domoticz instance are very low as both are national standards (NL and FR)
m_sql.UpdatePreferencesVar("SmartMeterType", 0);
}
}
else if (htype == HTYPE_DomoticzInternal) {
// DomoticzInternal cannot be added manually
return;
}
else if (htype == HTYPE_Domoticz) {
//Remote Domoticz
if (address.empty() || port == 0)
return;
}
else if (htype == HTYPE_TE923) {
//all fine here!
}
else if (htype == HTYPE_VOLCRAFTCO20) {
//all fine here!
}
else if (htype == HTYPE_System) {
//There should be only one
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM Hardware WHERE (Type==%d)", HTYPE_System);
if (!result.empty())
return;
}
else if (htype == HTYPE_1WIRE) {
//all fine here!
}
else if (htype == HTYPE_Rtl433) {
//all fine here!
}
else if (htype == HTYPE_Pinger) {
//all fine here!
}
else if (htype == HTYPE_Kodi) {
//all fine here!
}
else if (htype == HTYPE_PanasonicTV) {
// all fine here!
}
else if (htype == HTYPE_LogitechMediaServer) {
//all fine here!
}
else if (htype == HTYPE_RaspberryBMP085) {
//all fine here!
}
else if (htype == HTYPE_RaspberryHTU21D) {
//all fine here!
}
else if (htype == HTYPE_RaspberryTSL2561) {
//all fine here!
}
else if (htype == HTYPE_RaspberryBME280) {
//all fine here!
}
else if (htype == HTYPE_RaspberryMCP23017) {
//all fine here!
}
else if (htype == HTYPE_Dummy) {
//all fine here!
}
else if (htype == HTYPE_Tellstick) {
//all fine here!
}
else if (htype == HTYPE_EVOHOME_SCRIPT || htype == HTYPE_EVOHOME_SERIAL || htype == HTYPE_EVOHOME_WEB || htype == HTYPE_EVOHOME_TCP) {
//all fine here!
}
else if (htype == HTYPE_PiFace) {
//all fine here!
}
else if (htype == HTYPE_HTTPPOLLER) {
//all fine here!
}
else if (htype == HTYPE_BleBox) {
//all fine here!
}
else if (htype == HTYPE_HEOS) {
//all fine here!
}
else if (htype == HTYPE_Yeelight) {
//all fine here!
}
else if (htype == HTYPE_XiaomiGateway) {
//all fine here!
}
else if (htype == HTYPE_Arilux) {
//all fine here!
}
else if (htype == HTYPE_USBtinGateway) {
//All fine here
}
else if (
(htype == HTYPE_Wunderground) ||
(htype == HTYPE_DarkSky) ||
(htype == HTYPE_AccuWeather) ||
(htype == HTYPE_OpenWeatherMap) ||
(htype == HTYPE_ICYTHERMOSTAT) ||
(htype == HTYPE_TOONTHERMOSTAT) ||
(htype == HTYPE_AtagOne) ||
(htype == HTYPE_PVOUTPUT_INPUT) ||
(htype == HTYPE_NEST) ||
(htype == HTYPE_ANNATHERMOSTAT) ||
(htype == HTYPE_THERMOSMART) ||
(htype == HTYPE_Tado) ||
(htype == HTYPE_Netatmo)
)
{
if (
(username.empty()) ||
(password.empty())
)
return;
}
else if (htype == HTYPE_SolarEdgeAPI)
{
if (
(username.empty())
)
return;
}
else if (htype == HTYPE_Nest_OAuthAPI) {
if (
(username == "") &&
(extra == "||")
)
return;
}
else if (htype == HTYPE_SBFSpot) {
if (username.empty())
return;
}
else if (htype == HTYPE_HARMONY_HUB) {
if (
(address.empty() || port == 0)
)
return;
}
else if (htype == HTYPE_Philips_Hue) {
if (
(username.empty()) ||
(address.empty() || port == 0)
)
return;
if (port == 0)
port = 80;
}
else if (htype == HTYPE_WINDDELEN) {
std::string mill_id = request::findValue(&req, "Mode1");
if (
(mill_id.empty()) ||
(sport.empty())
)
return;
mode1 = atoi(mill_id.c_str());
}
else if (htype == HTYPE_Honeywell) {
//all fine here!
}
else if (htype == HTYPE_RaspberryGPIO) {
//all fine here!
}
else if (htype == HTYPE_SysfsGpio) {
//all fine here!
}
else if (htype == HTYPE_OpenWebNetTCP) {
//All fine here
}
else if (htype == HTYPE_Daikin) {
//All fine here
}
else if (htype == HTYPE_GoodweAPI) {
if (username.empty())
return;
}
else if (htype == HTYPE_PythonPlugin) {
//All fine here
}
else if (htype == HTYPE_RaspberryPCF8574) {
//All fine here
}
else if (htype == HTYPE_OpenWebNetUSB) {
//All fine here
}
else if (htype == HTYPE_IntergasInComfortLAN2RF) {
//All fine here
}
else if (htype == HTYPE_EnphaseAPI) {
//All fine here
}
else if (htype == HTYPE_EcoCompteur) {
//all fine here!
}
else
return;
root["status"] = "OK";
root["title"] = "AddHardware";
std::vector<std::vector<std::string> > result;
if (htype == HTYPE_Domoticz)
{
if (password.size() != 32)
{
password = GenerateMD5Hash(password);
}
}
else if ((htype == HTYPE_S0SmartMeterUSB) || (htype == HTYPE_S0SmartMeterTCP))
{
extra = "0;1000;0;1000;0;1000;0;1000;0;1000";
}
else if (htype == HTYPE_Pinger)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_Kodi)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_PanasonicTV)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_LogitechMediaServer)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_HEOS)
{
mode1 = 30;
mode2 = 1000;
}
else if (htype == HTYPE_Tellstick)
{
mode1 = 4;
mode2 = 500;
}
if (htype == HTYPE_HTTPPOLLER) {
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q','%q','%q','%q', '%q', '%q', '%q', '%q', %d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1Str.c_str(), mode2Str.c_str(), mode3Str.c_str(), mode4Str.c_str(), mode5Str.c_str(), mode6Str.c_str(),
iDataTimeout
);
}
else if (htype == HTYPE_PythonPlugin) {
sport = request::findValue(&req, "serialport");
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q','%q','%q','%q', '%q', '%q', '%q', '%q', %d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1Str.c_str(), mode2Str.c_str(), mode3Str.c_str(), mode4Str.c_str(), mode5Str.c_str(), mode6Str.c_str(),
iDataTimeout
);
}
else if (
(htype == HTYPE_RFXtrx433)||
(htype == HTYPE_RFXtrx868)
)
{
//No Extra field here, handled in CWebServer::SetRFXCOMMode
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q',%d,%d,%d,%d,%d,%d,%d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout
);
extra = "0";
}
else {
m_sql.safe_query(
"INSERT INTO Hardware (Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout) VALUES ('%q',%d, %d,'%q',%d,'%q','%q','%q','%q',%d,%d,%d,%d,%d,%d,%d)",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout
);
}
//add the device for real in our system
result = m_sql.safe_query("SELECT MAX(ID) FROM Hardware");
if (!result.empty())
{
std::vector<std::string> sd = result[0];
int ID = atoi(sd[0].c_str());
root["idx"] = sd[0].c_str(); // OTO output the created ID for easier management on the caller side (if automated)
m_mainworker.AddHardwareFromParams(ID, name, (senabled == "true") ? true : false, htype, address, port, sport, username, password, extra, mode1, mode2, mode3, mode4, mode5, mode6, iDataTimeout, true);
}
}
void CWebServer::Cmd_UpdateHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string name = CURLEncode::URLDecode(request::findValue(&req, "name"));
std::string senabled = request::findValue(&req, "enabled");
std::string shtype = request::findValue(&req, "htype");
std::string address = request::findValue(&req, "address");
std::string sport = request::findValue(&req, "port");
std::string username = CURLEncode::URLDecode(request::findValue(&req, "username"));
std::string password = CURLEncode::URLDecode(request::findValue(&req, "password"));
std::string extra = CURLEncode::URLDecode(request::findValue(&req, "extra"));
std::string sdatatimeout = request::findValue(&req, "datatimeout");
if (
(name.empty()) ||
(senabled.empty()) ||
(shtype.empty())
)
return;
int mode1 = atoi(request::findValue(&req, "Mode1").c_str());
int mode2 = atoi(request::findValue(&req, "Mode2").c_str());
int mode3 = atoi(request::findValue(&req, "Mode3").c_str());
int mode4 = atoi(request::findValue(&req, "Mode4").c_str());
int mode5 = atoi(request::findValue(&req, "Mode5").c_str());
int mode6 = atoi(request::findValue(&req, "Mode6").c_str());
bool bEnabled = (senabled == "true") ? true : false;
_eHardwareTypes htype = (_eHardwareTypes)atoi(shtype.c_str());
int iDataTimeout = atoi(sdatatimeout.c_str());
int port = atoi(sport.c_str());
bool bIsSerial = false;
if (IsSerialDevice(htype))
{
//USB/System
bIsSerial = true;
if (bEnabled)
{
if (sport.empty())
return; //need to have a serial port
}
}
else if (
(htype == HTYPE_RFXLAN) || (htype == HTYPE_P1SmartMeterLAN) ||
(htype == HTYPE_YouLess) || (htype == HTYPE_OpenThermGatewayTCP) || (htype == HTYPE_LimitlessLights) ||
(htype == HTYPE_SolarEdgeTCP) || (htype == HTYPE_WOL) || (htype == HTYPE_S0SmartMeterTCP) || (htype == HTYPE_ECODEVICES) || (htype == HTYPE_Mochad) ||
(htype == HTYPE_MySensorsTCP) || (htype == HTYPE_MySensorsMQTT) || (htype == HTYPE_MQTT) || (htype == HTYPE_TTN_MQTT) || (htype == HTYPE_FRITZBOX) || (htype == HTYPE_ETH8020) || (htype == HTYPE_Sterbox) ||
(htype == HTYPE_KMTronicTCP) || (htype == HTYPE_KMTronicUDP) || (htype == HTYPE_SOLARMAXTCP) || (htype == HTYPE_RelayNet) || (htype == HTYPE_SatelIntegra) || (htype == HTYPE_eHouseTCP) || (htype == HTYPE_RFLINKTCP) ||
(htype == HTYPE_Comm5TCP || (htype == HTYPE_Comm5SMTCP) || (htype == HTYPE_CurrentCostMeterLAN)) ||
(htype == HTYPE_NefitEastLAN) || (htype == HTYPE_DenkoviHTTPDevices) || (htype == HTYPE_DenkoviTCPDevices) || (htype == HTYPE_Ec3kMeterTCP) || (htype == HTYPE_MultiFun) || (htype == HTYPE_ZIBLUETCP) || (htype == HTYPE_OnkyoAVTCP)
) {
//Lan
if (address.empty())
return;
}
else if (htype == HTYPE_DomoticzInternal) {
// DomoticzInternal cannot be updated
return;
}
else if (htype == HTYPE_Domoticz) {
//Remote Domoticz
if (address.empty())
return;
}
else if (htype == HTYPE_System) {
//There should be only one, and with this ID
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM Hardware WHERE (Type==%d)", HTYPE_System);
if (!result.empty())
{
int hID = atoi(result[0][0].c_str());
int aID = atoi(idx.c_str());
if (hID != aID)
return;
}
}
else if (htype == HTYPE_TE923) {
//All fine here
}
else if (htype == HTYPE_VOLCRAFTCO20) {
//All fine here
}
else if (htype == HTYPE_1WIRE) {
//All fine here
}
else if (htype == HTYPE_Pinger) {
//All fine here
}
else if (htype == HTYPE_Kodi) {
//All fine here
}
else if (htype == HTYPE_PanasonicTV) {
//All fine here
}
else if (htype == HTYPE_LogitechMediaServer) {
//All fine here
}
else if (htype == HTYPE_RaspberryBMP085) {
//All fine here
}
else if (htype == HTYPE_RaspberryHTU21D) {
//All fine here
}
else if (htype == HTYPE_RaspberryTSL2561) {
//All fine here
}
else if (htype == HTYPE_RaspberryBME280) {
//All fine here
}
else if (htype == HTYPE_RaspberryMCP23017) {
//all fine here!
}
else if (htype == HTYPE_Dummy) {
//All fine here
}
else if (htype == HTYPE_EVOHOME_SCRIPT || htype == HTYPE_EVOHOME_SERIAL || htype == HTYPE_EVOHOME_WEB || htype == HTYPE_EVOHOME_TCP) {
//All fine here
}
else if (htype == HTYPE_PiFace) {
//All fine here
}
else if (htype == HTYPE_HTTPPOLLER) {
//all fine here!
}
else if (htype == HTYPE_BleBox) {
//All fine here
}
else if (htype == HTYPE_HEOS) {
//All fine here
}
else if (htype == HTYPE_Yeelight) {
//All fine here
}
else if (htype == HTYPE_XiaomiGateway) {
//All fine here
}
else if (htype == HTYPE_Arilux) {
//All fine here
}
else if (htype == HTYPE_USBtinGateway) {
//All fine here
}
else if (
(htype == HTYPE_Wunderground) ||
(htype == HTYPE_DarkSky) ||
(htype == HTYPE_AccuWeather) ||
(htype == HTYPE_OpenWeatherMap) ||
(htype == HTYPE_ICYTHERMOSTAT) ||
(htype == HTYPE_TOONTHERMOSTAT) ||
(htype == HTYPE_AtagOne) ||
(htype == HTYPE_PVOUTPUT_INPUT) ||
(htype == HTYPE_NEST) ||
(htype == HTYPE_ANNATHERMOSTAT) ||
(htype == HTYPE_THERMOSMART) ||
(htype == HTYPE_Tado) ||
(htype == HTYPE_Netatmo)
)
{
if (
(username.empty()) ||
(password.empty())
)
return;
}
else if (htype == HTYPE_SolarEdgeAPI)
{
if (
(username.empty())
)
return;
}
else if (htype == HTYPE_Nest_OAuthAPI) {
if (
(username == "") &&
(extra == "||")
)
return;
}
else if (htype == HTYPE_HARMONY_HUB) {
if (
(address.empty())
)
return;
}
else if (htype == HTYPE_Philips_Hue) {
if (
(username.empty()) ||
(address.empty())
)
return;
if (port == 0)
port = 80;
}
else if (htype == HTYPE_RaspberryGPIO) {
//all fine here!
}
else if (htype == HTYPE_SysfsGpio) {
//all fine here!
}
else if (htype == HTYPE_Rtl433) {
//all fine here!
}
else if (htype == HTYPE_Daikin) {
//all fine here!
}
else if (htype == HTYPE_SBFSpot) {
if (username.empty())
return;
}
else if (htype == HTYPE_WINDDELEN) {
std::string mill_id = request::findValue(&req, "Mode1");
if (
(mill_id.empty()) ||
(sport.empty())
)
return;
}
else if (htype == HTYPE_Honeywell) {
//All fine here
}
else if (htype == HTYPE_OpenWebNetTCP) {
//All fine here
}
else if (htype == HTYPE_PythonPlugin) {
//All fine here
}
else if (htype == HTYPE_GoodweAPI) {
if (username.empty()) {
return;
}
}
else if (htype == HTYPE_RaspberryPCF8574) {
//All fine here
}
else if (htype == HTYPE_OpenWebNetUSB) {
//All fine here
}
else if (htype == HTYPE_IntergasInComfortLAN2RF) {
//All fine here
}
else if (htype == HTYPE_EnphaseAPI) {
//all fine here!
}
else
return;
std::string mode1Str;
std::string mode2Str;
std::string mode3Str;
std::string mode4Str;
std::string mode5Str;
std::string mode6Str;
root["status"] = "OK";
root["title"] = "UpdateHardware";
if (htype == HTYPE_Domoticz)
{
if (password.size() != 32)
{
password = GenerateMD5Hash(password);
}
}
if ((bIsSerial) && (!bEnabled) && (sport.empty()))
{
//just disable the device
m_sql.safe_query(
"UPDATE Hardware SET Enabled=%d WHERE (ID == '%q')",
(bEnabled == true) ? 1 : 0,
idx.c_str()
);
}
else
{
if (htype == HTYPE_HTTPPOLLER) {
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Extra='%q', DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
iDataTimeout,
idx.c_str()
);
}
else if (htype == HTYPE_PythonPlugin) {
mode1Str = request::findValue(&req, "Mode1");
mode2Str = request::findValue(&req, "Mode2");
mode3Str = request::findValue(&req, "Mode3");
mode4Str = request::findValue(&req, "Mode4");
mode5Str = request::findValue(&req, "Mode5");
mode6Str = request::findValue(&req, "Mode6");
sport = request::findValue(&req, "serialport");
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Extra='%q', Mode1='%q', Mode2='%q', Mode3='%q', Mode4='%q', Mode5='%q', Mode6='%q', DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(senabled == "true") ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1Str.c_str(), mode2Str.c_str(), mode3Str.c_str(), mode4Str.c_str(), mode5Str.c_str(), mode6Str.c_str(),
iDataTimeout,
idx.c_str()
);
}
else if (
(htype == HTYPE_RFXtrx433) ||
(htype == HTYPE_RFXtrx868)
)
{
//No Extra field here, handled in CWebServer::SetRFXCOMMode
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Mode1=%d, Mode2=%d, Mode3=%d, Mode4=%d, Mode5=%d, Mode6=%d, DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(bEnabled == true) ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout,
idx.c_str()
);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Extra FROM Hardware WHERE ID=%q", idx.c_str());
if (!result.empty())
extra = result[0][0];
}
else {
m_sql.safe_query(
"UPDATE Hardware SET Name='%q', Enabled=%d, Type=%d, Address='%q', Port=%d, SerialPort='%q', Username='%q', Password='%q', Extra='%q', Mode1=%d, Mode2=%d, Mode3=%d, Mode4=%d, Mode5=%d, Mode6=%d, DataTimeout=%d WHERE (ID == '%q')",
name.c_str(),
(bEnabled == true) ? 1 : 0,
htype,
address.c_str(),
port,
sport.c_str(),
username.c_str(),
password.c_str(),
extra.c_str(),
mode1, mode2, mode3, mode4, mode5, mode6,
iDataTimeout,
idx.c_str()
);
}
}
//re-add the device in our system
int ID = atoi(idx.c_str());
m_mainworker.AddHardwareFromParams(ID, name, bEnabled, htype, address, port, sport, username, password, extra, mode1, mode2, mode3, mode4, mode5, mode6, iDataTimeout, true);
}
void CWebServer::Cmd_GetDeviceValueOptions(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::vector<std::string> result;
result = CBasePush::DropdownOptions(atoi(idx.c_str()));
if ((result.size() == 1) && result[0] == "Status") {
root["result"][0]["Value"] = 0;
root["result"][0]["Wording"] = result[0];
}
else {
int ii = 0;
for (const auto & itt : result)
{
std::string ddOption = itt;
root["result"][ii]["Value"] = ii + 1;
root["result"][ii]["Wording"] = ddOption.c_str();
ii++;
}
}
root["status"] = "OK";
root["title"] = "GetDeviceValueOptions";
}
void CWebServer::Cmd_GetDeviceValueOptionWording(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string pos = request::findValue(&req, "pos");
if ((idx.empty()) || (pos.empty()))
return;
std::string wording;
wording = CBasePush::DropdownOptionsValue(atoi(idx.c_str()), atoi(pos.c_str()));
root["wording"] = wording;
root["status"] = "OK";
root["title"] = "GetDeviceValueOptions";
}
void CWebServer::Cmd_AddUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string variablename = request::findValue(&req, "vname");
std::string variablevalue = request::findValue(&req, "vvalue");
std::string variabletype = request::findValue(&req, "vtype");
if (
(variablename.empty()) ||
(variabletype.empty()) ||
((variablevalue.empty()) && (variabletype != "2"))
)
return;
root["title"] = "AddUserVariable";
std::string errorMessage;
if (!m_sql.AddUserVariable(variablename, (const _eUsrVariableType)atoi(variabletype.c_str()), variablevalue, errorMessage))
{
root["status"] = "ERR";
root["message"] = errorMessage;
}
else {
root["status"] = "OK";
}
}
void CWebServer::Cmd_DeleteUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
m_sql.DeleteUserVariable(idx);
root["status"] = "OK";
root["title"] = "DeleteUserVariable";
}
void CWebServer::Cmd_UpdateUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string variablename = request::findValue(&req, "vname");
std::string variablevalue = request::findValue(&req, "vvalue");
std::string variabletype = request::findValue(&req, "vtype");
if (
(variablename.empty()) ||
(variabletype.empty()) ||
((variablevalue.empty()) && (variabletype != "2"))
)
return;
std::vector<std::vector<std::string> > result;
if (idx.empty())
{
result = m_sql.safe_query("SELECT ID FROM UserVariables WHERE Name='%q'", variablename.c_str());
if (result.empty())
return;
idx = result[0][0];
}
result = m_sql.safe_query("SELECT Name, ValueType FROM UserVariables WHERE ID='%q'", idx.c_str());
if (result.empty())
return;
bool bTypeNameChanged = false;
if (variablename != result[0][0])
bTypeNameChanged = true; //new name
else if (variabletype != result[0][1])
bTypeNameChanged = true; //new type
root["title"] = "UpdateUserVariable";
std::string errorMessage;
if (!m_sql.UpdateUserVariable(idx, variablename, (const _eUsrVariableType)atoi(variabletype.c_str()), variablevalue, !bTypeNameChanged, errorMessage))
{
root["status"] = "ERR";
root["message"] = errorMessage;
}
else {
root["status"] = "OK";
if (bTypeNameChanged)
{
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentUserVariables();
}
}
}
void CWebServer::Cmd_GetUserVariables(WebEmSession & session, const request& req, Json::Value &root)
{
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, ValueType, Value, LastUpdate FROM UserVariables");
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Type"] = sd[2];
root["result"][ii]["Value"] = sd[3];
root["result"][ii]["LastUpdate"] = sd[4];
ii++;
}
root["status"] = "OK";
root["title"] = "GetUserVariables";
}
void CWebServer::Cmd_GetUserVariable(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
int iVarID = atoi(idx.c_str());
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, ValueType, Value, LastUpdate FROM UserVariables WHERE (ID==%d)", iVarID);
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Type"] = sd[2];
root["result"][ii]["Value"] = sd[3];
root["result"][ii]["LastUpdate"] = sd[4];
ii++;
}
root["status"] = "OK";
root["title"] = "GetUserVariable";
}
void CWebServer::Cmd_AllowNewHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sTimeout = request::findValue(&req, "timeout");
if (sTimeout.empty())
return;
root["status"] = "OK";
root["title"] = "AllowNewHardware";
m_sql.AllowNewHardwareTimer(atoi(sTimeout.c_str()));
}
void CWebServer::Cmd_DeleteHardware(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
int hwID = atoi(idx.c_str());
CDomoticzHardwareBase *pBaseHardware = m_mainworker.GetHardware(hwID);
if ((pBaseHardware != NULL) && (pBaseHardware->HwdType == HTYPE_DomoticzInternal)) {
// DomoticzInternal cannot be removed
return;
}
root["status"] = "OK";
root["title"] = "DeleteHardware";
m_mainworker.RemoveDomoticzHardware(hwID);
m_sql.DeleteHardware(idx);
}
void CWebServer::Cmd_GetLog(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetLog";
time_t lastlogtime = 0;
std::string slastlogtime = request::findValue(&req, "lastlogtime");
if (slastlogtime != "")
{
std::stringstream s_str(slastlogtime);
s_str >> lastlogtime;
}
_eLogLevel lLevel = LOG_NORM;
std::string sloglevel = request::findValue(&req, "loglevel");
if (!sloglevel.empty())
{
lLevel = (_eLogLevel)atoi(sloglevel.c_str());
}
std::list<CLogger::_tLogLineStruct> logmessages = _log.GetLog(lLevel);
int ii = 0;
for (const auto & itt : logmessages)
{
if (itt.logtime > lastlogtime)
{
std::stringstream szLogTime;
szLogTime << itt.logtime;
root["LastLogTime"] = szLogTime.str();
root["result"][ii]["level"] = static_cast<int>(itt.level);
root["result"][ii]["message"] = itt.logmessage;
ii++;
}
}
}
void CWebServer::Cmd_ClearLog(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "ClearLog";
_log.ClearLog();
}
//Plan Functions
void CWebServer::Cmd_AddPlan(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string name = request::findValue(&req, "name");
root["status"] = "OK";
root["title"] = "AddPlan";
m_sql.safe_query(
"INSERT INTO Plans (Name) VALUES ('%q')",
name.c_str()
);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT MAX(ID) FROM Plans");
if (!result.empty())
{
std::vector<std::string> sd = result[0];
int ID = atoi(sd[0].c_str());
root["idx"] = sd[0].c_str(); // OTO output the created ID for easier management on the caller side (if automated)
}
}
void CWebServer::Cmd_UpdatePlan(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string name = request::findValue(&req, "name");
if (
(name.empty())
)
return;
root["status"] = "OK";
root["title"] = "UpdatePlan";
m_sql.safe_query(
"UPDATE Plans SET Name='%q' WHERE (ID == '%q')",
name.c_str(),
idx.c_str()
);
}
void CWebServer::Cmd_DeletePlan(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeletePlan";
m_sql.safe_query(
"DELETE FROM DeviceToPlansMap WHERE (PlanID == '%q')",
idx.c_str()
);
m_sql.safe_query(
"DELETE FROM Plans WHERE (ID == '%q')",
idx.c_str()
);
}
void CWebServer::Cmd_GetUnusedPlanDevices(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetUnusedPlanDevices";
std::string sunique = request::findValue(&req, "unique");
if (sunique.empty())
return;
int iUnique = (sunique == "true") ? 1 : 0;
int ii = 0;
std::vector<std::vector<std::string> > result;
std::vector<std::vector<std::string> > result2;
result = m_sql.safe_query("SELECT T1.[ID], T1.[Name], T1.[Type], T1.[SubType], T2.[Name] AS HardwareName FROM DeviceStatus as T1, Hardware as T2 WHERE (T1.[Used]==1) AND (T2.[ID]==T1.[HardwareID]) ORDER BY T2.[Name], T1.[Name]");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
bool bDoAdd = true;
if (iUnique)
{
result2 = m_sql.safe_query("SELECT ID FROM DeviceToPlansMap WHERE (DeviceRowID=='%q') AND (DevSceneType==0)",
sd[0].c_str());
bDoAdd = (result2.size() == 0);
}
if (bDoAdd)
{
int _dtype = atoi(sd[2].c_str());
std::string Name = "[" + sd[4] + "] " + sd[1] + " (" + RFX_Type_Desc(_dtype, 1) + "/" + RFX_Type_SubType_Desc(_dtype, atoi(sd[3].c_str())) + ")";
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
//Add Scenes
result = m_sql.safe_query("SELECT ID, Name FROM Scenes ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
bool bDoAdd = true;
if (iUnique)
{
result2 = m_sql.safe_query("SELECT ID FROM DeviceToPlansMap WHERE (DeviceRowID=='%q') AND (DevSceneType==1)",
sd[0].c_str());
bDoAdd = (result2.size() == 0);
}
if (bDoAdd)
{
root["result"][ii]["type"] = 1;
root["result"][ii]["idx"] = sd[0];
std::string sname = "[Scene] " + sd[1];
root["result"][ii]["Name"] = sname;
ii++;
}
}
}
}
void CWebServer::Cmd_AddPlanActiveDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string sactivetype = request::findValue(&req, "activetype");
std::string activeidx = request::findValue(&req, "activeidx");
if (
(idx.empty()) ||
(sactivetype.empty()) ||
(activeidx.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddPlanActiveDevice";
int activetype = atoi(sactivetype.c_str());
//check if it is not already there
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM DeviceToPlansMap WHERE (DeviceRowID=='%q') AND (DevSceneType==%d) AND (PlanID=='%q')",
activeidx.c_str(), activetype, idx.c_str());
if (result.empty())
{
m_sql.safe_query(
"INSERT INTO DeviceToPlansMap (DevSceneType,DeviceRowID, PlanID) VALUES (%d,'%q','%q')",
activetype,
activeidx.c_str(),
idx.c_str()
);
}
}
void CWebServer::Cmd_GetPlanDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetPlanDevices";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, DevSceneType, DeviceRowID, [Order] FROM DeviceToPlansMap WHERE (PlanID=='%q') ORDER BY [Order]",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
int DevSceneType = atoi(sd[1].c_str());
std::string DevSceneRowID = sd[2];
std::string Name = "";
if (DevSceneType == 0)
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM DeviceStatus WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = result2[0][0];
}
}
else
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM Scenes WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = "[Scene] " + result2[0][0];
}
}
if (Name != "")
{
root["result"][ii]["idx"] = ID;
root["result"][ii]["devidx"] = DevSceneRowID;
root["result"][ii]["type"] = DevSceneType;
root["result"][ii]["DevSceneRowID"] = DevSceneRowID;
root["result"][ii]["order"] = sd[3];
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
}
void CWebServer::Cmd_DeletePlanDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeletePlanDevice";
m_sql.safe_query("DELETE FROM DeviceToPlansMap WHERE (ID == '%q')", idx.c_str());
}
void CWebServer::Cmd_SetPlanDeviceCoords(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
std::string planidx = request::findValue(&req, "planidx");
std::string xoffset = request::findValue(&req, "xoffset");
std::string yoffset = request::findValue(&req, "yoffset");
std::string type = request::findValue(&req, "DevSceneType");
if ((idx.empty()) || (planidx.empty()) || (xoffset.empty()) || (yoffset.empty()))
return;
if (type != "1") type = "0"; // 0 = Device, 1 = Scene/Group
root["status"] = "OK";
root["title"] = "SetPlanDeviceCoords";
m_sql.safe_query("UPDATE DeviceToPlansMap SET [XOffset] = '%q', [YOffset] = '%q' WHERE (DeviceRowID='%q') and (PlanID='%q') and (DevSceneType='%q')",
xoffset.c_str(), yoffset.c_str(), idx.c_str(), planidx.c_str(), type.c_str());
_log.Log(LOG_STATUS, "(Floorplan) Device '%s' coordinates set to '%s,%s' in plan '%s'.", idx.c_str(), xoffset.c_str(), yoffset.c_str(), planidx.c_str());
}
void CWebServer::Cmd_DeleteAllPlanDevices(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllPlanDevices";
m_sql.safe_query("DELETE FROM DeviceToPlansMap WHERE (PlanID == '%q')", idx.c_str());
}
void CWebServer::Cmd_ChangePlanOrder(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string sway = request::findValue(&req, "way");
if (sway.empty())
return;
bool bGoUp = (sway == "0");
std::string aOrder, oID, oOrder;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT [Order] FROM Plans WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
aOrder = result[0][0];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Plans WHERE ([Order]>'%q') ORDER BY [Order] ASC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Plans WHERE ([Order]<'%q') ORDER BY [Order] DESC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangePlanOrder";
m_sql.safe_query("UPDATE Plans SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
m_sql.safe_query("UPDATE Plans SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
void CWebServer::Cmd_ChangePlanDeviceOrder(WebEmSession & session, const request& req, Json::Value &root)
{
std::string planid = request::findValue(&req, "planid");
std::string idx = request::findValue(&req, "idx");
std::string sway = request::findValue(&req, "way");
if (
(planid.empty()) ||
(idx.empty()) ||
(sway.empty())
)
return;
bool bGoUp = (sway == "0");
std::string aOrder, oID, oOrder;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT [Order] FROM DeviceToPlansMap WHERE ((ID=='%q') AND (PlanID=='%q'))",
idx.c_str(), planid.c_str());
if (result.empty())
return;
aOrder = result[0][0];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM DeviceToPlansMap WHERE (([Order]>'%q') AND (PlanID=='%q')) ORDER BY [Order] ASC",
aOrder.c_str(), planid.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM DeviceToPlansMap WHERE (([Order]<'%q') AND (PlanID=='%q')) ORDER BY [Order] DESC",
aOrder.c_str(), planid.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangePlanOrder";
m_sql.safe_query("UPDATE DeviceToPlansMap SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
m_sql.safe_query("UPDATE DeviceToPlansMap SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
void CWebServer::Cmd_GetVersion(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetVersion";
root["version"] = szAppVersion;
root["hash"] = szAppHash;
root["build_time"] = szAppDate;
CdzVents* dzvents = CdzVents::GetInstance();
root["dzvents_version"] = dzvents->GetVersion();
root["python_version"] = szPyVersion;
if (session.rights != 2)
{
//only admin users will receive the update notification
root["UseUpdate"] = false;
root["HaveUpdate"] = false;
}
else
{
root["UseUpdate"] = g_bUseUpdater;
root["HaveUpdate"] = m_mainworker.IsUpdateAvailable(false);
root["DomoticzUpdateURL"] = m_mainworker.m_szDomoticzUpdateURL;
root["SystemName"] = m_mainworker.m_szSystemName;
root["Revision"] = m_mainworker.m_iRevision;
}
}
void CWebServer::Cmd_GetAuth(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetAuth";
if (session.rights != -1)
{
root["version"] = szAppVersion;
}
root["user"] = session.username;
root["rights"] = session.rights;
}
void CWebServer::Cmd_GetUptime(WebEmSession & session, const request& req, Json::Value &root)
{
//this is used in the about page, we are going to round the seconds a bit to display nicer
time_t atime = mytime(NULL);
time_t tuptime = atime - m_StartTime;
//round to 5 seconds (nicer in about page)
tuptime = ((tuptime / 5) * 5) + 5;
int days, hours, minutes, seconds;
days = (int)(tuptime / 86400);
tuptime -= (days * 86400);
hours = (int)(tuptime / 3600);
tuptime -= (hours * 3600);
minutes = (int)(tuptime / 60);
tuptime -= (minutes * 60);
seconds = (int)tuptime;
root["status"] = "OK";
root["title"] = "GetUptime";
root["days"] = days;
root["hours"] = hours;
root["minutes"] = minutes;
root["seconds"] = seconds;
}
void CWebServer::Cmd_GetActualHistory(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetActualHistory";
std::string historyfile = szUserDataFolder + "History.txt";
std::ifstream infile;
int ii = 0;
infile.open(historyfile.c_str());
std::string sLine;
if (infile.is_open())
{
while (!infile.eof())
{
getline(infile, sLine);
root["LastLogTime"] = "";
if (sLine.find("Version ") == 0)
root["result"][ii]["level"] = 1;
else
root["result"][ii]["level"] = 0;
root["result"][ii]["message"] = sLine;
ii++;
}
}
}
void CWebServer::Cmd_GetNewHistory(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetNewHistory";
std::string historyfile;
int nValue;
m_sql.GetPreferencesVar("ReleaseChannel", nValue);
bool bIsBetaChannel = (nValue != 0);
std::string szHistoryURL = "https://www.domoticz.com/download.php?channel=stable&type=history";
if (bIsBetaChannel)
{
utsname my_uname;
if (uname(&my_uname) < 0)
return;
std::string systemname = my_uname.sysname;
std::string machine = my_uname.machine;
std::transform(systemname.begin(), systemname.end(), systemname.begin(), ::tolower);
if (machine == "armv6l")
{
//Seems like old arm systems can also use the new arm build
machine = "armv7l";
}
if (((machine != "armv6l") && (machine != "armv7l") && (systemname != "windows") && (machine != "x86_64") && (machine != "aarch64")) || (strstr(my_uname.release, "ARCH+") != NULL))
szHistoryURL = "https://www.domoticz.com/download.php?channel=beta&type=history";
else
szHistoryURL = "https://www.domoticz.com/download.php?channel=beta&type=history&system=" + systemname + "&machine=" + machine;
}
if (!HTTPClient::GET(szHistoryURL, historyfile))
{
historyfile = "Unable to get Online History document !!";
}
std::istringstream stream(historyfile);
std::string sLine;
int ii = 0;
while (std::getline(stream, sLine))
{
root["LastLogTime"] = "";
if (sLine.find("Version ") == 0)
root["result"][ii]["level"] = 1;
else
root["result"][ii]["level"] = 0;
root["result"][ii]["message"] = sLine;
ii++;
}
}
void CWebServer::Cmd_GetConfig(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights == -1)
{
session.reply_status = reply::forbidden;
return;//Only auth user allowed
}
root["status"] = "OK";
root["title"] = "GetConfig";
bool bHaveUser = (session.username != "");
int urights = 3;
unsigned long UserID = 0;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
UserID = m_users[iUser].ID;
}
}
int nValue;
std::string sValue;
if (m_sql.GetPreferencesVar("Language", sValue))
{
root["language"] = sValue;
}
if (m_sql.GetPreferencesVar("DegreeDaysBaseTemperature", sValue))
{
root["DegreeDaysBaseTemperature"] = atof(sValue.c_str());
}
nValue = 0;
int iDashboardType = 0;
m_sql.GetPreferencesVar("DashboardType", iDashboardType);
root["DashboardType"] = iDashboardType;
m_sql.GetPreferencesVar("MobileType", nValue);
root["MobileType"] = nValue;
nValue = 1;
m_sql.GetPreferencesVar("5MinuteHistoryDays", nValue);
root["FiveMinuteHistoryDays"] = nValue;
nValue = 1;
m_sql.GetPreferencesVar("ShowUpdateEffect", nValue);
root["result"]["ShowUpdatedEffect"] = (nValue == 1);
root["AllowWidgetOrdering"] = m_sql.m_bAllowWidgetOrdering;
root["WindScale"] = m_sql.m_windscale*10.0f;
root["WindSign"] = m_sql.m_windsign;
root["TempScale"] = m_sql.m_tempscale;
root["TempSign"] = m_sql.m_tempsign;
std::string Latitude = "1";
std::string Longitude = "1";
if (m_sql.GetPreferencesVar("Location", nValue, sValue))
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
Latitude = strarray[0];
Longitude = strarray[1];
}
}
root["Latitude"] = Latitude;
root["Longitude"] = Longitude;
#ifndef NOCLOUD
bool bEnableTabProxy = request::get_req_header(&req, "X-From-MyDomoticz") != NULL;
#else
bool bEnableTabProxy = false;
#endif
int bEnableTabDashboard = 1;
int bEnableTabFloorplans = 1;
int bEnableTabLight = 1;
int bEnableTabScenes = 1;
int bEnableTabTemp = 1;
int bEnableTabWeather = 1;
int bEnableTabUtility = 1;
int bEnableTabCustom = 1;
std::vector<std::vector<std::string> > result;
if ((UserID != 0) && (UserID != 10000))
{
result = m_sql.safe_query("SELECT TabsEnabled FROM Users WHERE (ID==%lu)",
UserID);
if (!result.empty())
{
int TabsEnabled = atoi(result[0][0].c_str());
bEnableTabLight = (TabsEnabled&(1 << 0));
bEnableTabScenes = (TabsEnabled&(1 << 1));
bEnableTabTemp = (TabsEnabled&(1 << 2));
bEnableTabWeather = (TabsEnabled&(1 << 3));
bEnableTabUtility = (TabsEnabled&(1 << 4));
bEnableTabCustom = (TabsEnabled&(1 << 5));
bEnableTabFloorplans = (TabsEnabled&(1 << 6));
}
}
else
{
m_sql.GetPreferencesVar("EnableTabFloorplans", bEnableTabFloorplans);
m_sql.GetPreferencesVar("EnableTabLights", bEnableTabLight);
m_sql.GetPreferencesVar("EnableTabScenes", bEnableTabScenes);
m_sql.GetPreferencesVar("EnableTabTemp", bEnableTabTemp);
m_sql.GetPreferencesVar("EnableTabWeather", bEnableTabWeather);
m_sql.GetPreferencesVar("EnableTabUtility", bEnableTabUtility);
m_sql.GetPreferencesVar("EnableTabCustom", bEnableTabCustom);
}
if (iDashboardType == 3)
{
//Floorplan , no need to show a tab floorplan
bEnableTabFloorplans = 0;
}
root["result"]["EnableTabProxy"] = bEnableTabProxy;
root["result"]["EnableTabDashboard"] = bEnableTabDashboard != 0;
root["result"]["EnableTabFloorplans"] = bEnableTabFloorplans != 0;
root["result"]["EnableTabLights"] = bEnableTabLight != 0;
root["result"]["EnableTabScenes"] = bEnableTabScenes != 0;
root["result"]["EnableTabTemp"] = bEnableTabTemp != 0;
root["result"]["EnableTabWeather"] = bEnableTabWeather != 0;
root["result"]["EnableTabUtility"] = bEnableTabUtility != 0;
root["result"]["EnableTabCustom"] = bEnableTabCustom != 0;
if (bEnableTabCustom)
{
//Add custom templates
DIR *lDir;
struct dirent *ent;
std::string templatesFolder = szWWWFolder + "/templates";
int iFile = 0;
if ((lDir = opendir(templatesFolder.c_str())) != NULL)
{
while ((ent = readdir(lDir)) != NULL)
{
std::string filename = ent->d_name;
size_t pos = filename.find(".htm");
if (pos != std::string::npos)
{
std::string shortfile = filename.substr(0, pos);
root["result"]["templates"][iFile++] = shortfile;
}
}
closedir(lDir);
}
}
}
void CWebServer::Cmd_SendNotification(WebEmSession & session, const request& req, Json::Value &root)
{
std::string subject = request::findValue(&req, "subject");
std::string body = request::findValue(&req, "body");
std::string subsystem = request::findValue(&req, "subsystem");
if (
(subject.empty()) ||
(body.empty())
)
return;
if (subsystem.empty()) subsystem = NOTIFYALL;
//Add to queue
if (m_notifications.SendMessage(0, std::string(""), subsystem, subject, body, std::string(""), 1, std::string(""), false)) {
root["status"] = "OK";
}
root["title"] = "SendNotification";
}
void CWebServer::Cmd_EmailCameraSnapshot(WebEmSession & session, const request& req, Json::Value &root)
{
std::string camidx = request::findValue(&req, "camidx");
std::string subject = request::findValue(&req, "subject");
if (
(camidx.empty()) ||
(subject.empty())
)
return;
//Add to queue
m_sql.AddTaskItem(_tTaskItem::EmailCameraSnapshot(1, camidx, subject));
root["status"] = "OK";
root["title"] = "Email Camera Snapshot";
}
void CWebServer::Cmd_UpdateDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights < 1)
{
session.reply_status = reply::forbidden;
return; //only user or higher allowed
}
std::string idx = request::findValue(&req, "idx");
if (!IsIdxForUser(&session, atoi(idx.c_str())))
{
_log.Log(LOG_ERROR, "User: %s tried to update an Unauthorized device!", session.username.c_str());
session.reply_status = reply::forbidden;
return;
}
std::string hid = request::findValue(&req, "hid");
std::string did = request::findValue(&req, "did");
std::string dunit = request::findValue(&req, "dunit");
std::string dtype = request::findValue(&req, "dtype");
std::string dsubtype = request::findValue(&req, "dsubtype");
std::string nvalue = request::findValue(&req, "nvalue");
std::string svalue = request::findValue(&req, "svalue");
if ((nvalue.empty() && svalue.empty()))
{
return;
}
int signallevel = 12;
int batterylevel = 255;
if (idx.empty())
{
//No index supplied, check if raw parameters where supplied
if (
(hid.empty()) ||
(did.empty()) ||
(dunit.empty()) ||
(dtype.empty()) ||
(dsubtype.empty())
)
return;
}
else
{
//Get the raw device parameters
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType FROM DeviceStatus WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
hid = result[0][0];
did = result[0][1];
dunit = result[0][2];
dtype = result[0][3];
dsubtype = result[0][4];
}
int HardwareID = atoi(hid.c_str());
std::string DeviceID = did;
int unit = atoi(dunit.c_str());
int devType = atoi(dtype.c_str());
int subType = atoi(dsubtype.c_str());
uint64_t ulIdx = std::strtoull(idx.c_str(), nullptr, 10);
int invalue = atoi(nvalue.c_str());
std::string sSignalLevel = request::findValue(&req, "rssi");
if (sSignalLevel != "")
{
signallevel = atoi(sSignalLevel.c_str());
}
std::string sBatteryLevel = request::findValue(&req, "battery");
if (sBatteryLevel != "")
{
batterylevel = atoi(sBatteryLevel.c_str());
}
if (m_mainworker.UpdateDevice(HardwareID, DeviceID, unit, devType, subType, invalue, svalue, signallevel, batterylevel))
{
root["status"] = "OK";
root["title"] = "Update Device";
}
}
void CWebServer::Cmd_UpdateDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string script = request::findValue(&req, "script");
if (script.empty())
{
return;
}
std::string content = req.content;
std::vector<std::string> allParameters;
// Keep the url content on the right of the '?'
std::vector<std::string> allParts;
StringSplit(req.uri, "?", allParts);
if (!allParts.empty())
{
// Split all url parts separated by a '&'
StringSplit(allParts[1], "&", allParameters);
}
CLuaHandler luaScript;
bool ret = luaScript.executeLuaScript(script, content, allParameters);
if (ret)
{
root["status"] = "OK";
root["title"] = "Update Device";
}
}
void CWebServer::Cmd_SetThermostatState(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sstate = request::findValue(&req, "state");
std::string idx = request::findValue(&req, "idx");
std::string name = request::findValue(&req, "name");
if (
(idx.empty()) ||
(sstate.empty())
)
return;
int iState = atoi(sstate.c_str());
int urights = 3;
bool bHaveUser = (session.username != "");
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a Thermostat State change command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
root["status"] = "OK";
root["title"] = "Set Thermostat State";
_log.Log(LOG_NORM, "Setting Thermostat State....");
m_mainworker.SetThermostatState(idx, iState);
}
void CWebServer::Cmd_SystemShutdown(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
#ifdef WIN32
int ret = system("shutdown -s -f -t 1 -d up:125:1");
#else
int ret = system("sudo shutdown -h now");
#endif
if (ret != 0)
{
_log.Log(LOG_ERROR, "Error executing shutdown command. returned: %d", ret);
return;
}
root["title"] = "SystemShutdown";
root["status"] = "OK";
}
void CWebServer::Cmd_SystemReboot(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
#ifdef WIN32
int ret = system("shutdown -r -f -t 1 -d up:125:1");
#else
int ret = system("sudo shutdown -r now");
#endif
if (ret != 0)
{
_log.Log(LOG_ERROR, "Error executing reboot command. returned: %d", ret);
return;
}
root["title"] = "SystemReboot";
root["status"] = "OK";
}
void CWebServer::Cmd_ExcecuteScript(WebEmSession & session, const request& req, Json::Value &root)
{
std::string scriptname = request::findValue(&req, "scriptname");
if (scriptname.empty())
return;
if (scriptname.find("..") != std::string::npos)
return;
#ifdef WIN32
scriptname = szUserDataFolder + "scripts\\" + scriptname;
#else
scriptname = szUserDataFolder + "scripts/" + scriptname;
#endif
if (!file_exist(scriptname.c_str()))
return;
std::string script_params = request::findValue(&req, "scriptparams");
std::string strparm = szUserDataFolder;
if (!script_params.empty())
{
if (strparm.size() > 0)
strparm += " " + script_params;
else
strparm = script_params;
}
std::string sdirect = request::findValue(&req, "direct");
if (sdirect == "true")
{
_log.Log(LOG_STATUS, "Executing script: %s", scriptname.c_str());
#ifdef WIN32
ShellExecute(NULL, "open", scriptname.c_str(), strparm.c_str(), NULL, SW_SHOWNORMAL);
#else
std::string lscript = scriptname + " " + strparm;
int ret = system(lscript.c_str());
if (ret != 0)
{
_log.Log(LOG_ERROR, "Error executing script command (%s). returned: %d", lscript.c_str(), ret);
return;
}
#endif
}
else
{
//add script to background worker
m_sql.AddTaskItem(_tTaskItem::ExecuteScript(0.2f, scriptname, strparm));
}
root["title"] = "ExecuteScript";
root["status"] = "OK";
}
void CWebServer::Cmd_GetCosts(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
char szTmp[100];
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type, SubType, nValue, sValue FROM DeviceStatus WHERE (ID=='%q')",
idx.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
int nValue = 0;
root["status"] = "OK";
root["title"] = "GetElectraCosts";
m_sql.GetPreferencesVar("CostEnergy", nValue);
root["CostEnergy"] = nValue;
m_sql.GetPreferencesVar("CostEnergyT2", nValue);
root["CostEnergyT2"] = nValue;
m_sql.GetPreferencesVar("CostEnergyR1", nValue);
root["CostEnergyR1"] = nValue;
m_sql.GetPreferencesVar("CostEnergyR2", nValue);
root["CostEnergyR2"] = nValue;
m_sql.GetPreferencesVar("CostGas", nValue);
root["CostGas"] = nValue;
m_sql.GetPreferencesVar("CostWater", nValue);
root["CostWater"] = nValue;
int tValue = 1000;
if (m_sql.GetPreferencesVar("MeterDividerWater", tValue))
{
root["DividerWater"] = float(tValue);
}
unsigned char dType = atoi(sd[0].c_str());
//unsigned char subType = atoi(sd[1].c_str());
//nValue = (unsigned char)atoi(sd[2].c_str());
std::string sValue = sd[3];
if (dType == pTypeP1Power)
{
//also provide the counter values
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() != 6)
return;
float EnergyDivider = 1000.0f;
if (m_sql.GetPreferencesVar("MeterDividerEnergy", tValue))
{
EnergyDivider = float(tValue);
}
unsigned long long powerusage1 = std::strtoull(splitresults[0].c_str(), nullptr, 10);
unsigned long long powerusage2 = std::strtoull(splitresults[1].c_str(), nullptr, 10);
unsigned long long powerdeliv1 = std::strtoull(splitresults[2].c_str(), nullptr, 10);
unsigned long long powerdeliv2 = std::strtoull(splitresults[3].c_str(), nullptr, 10);
unsigned long long usagecurrent = std::strtoull(splitresults[4].c_str(), nullptr, 10);
unsigned long long delivcurrent = std::strtoull(splitresults[5].c_str(), nullptr, 10);
powerdeliv1 = (powerdeliv1 < 10) ? 0 : powerdeliv1;
powerdeliv2 = (powerdeliv2 < 10) ? 0 : powerdeliv2;
sprintf(szTmp, "%.03f", float(powerusage1) / EnergyDivider);
root["CounterT1"] = szTmp;
sprintf(szTmp, "%.03f", float(powerusage2) / EnergyDivider);
root["CounterT2"] = szTmp;
sprintf(szTmp, "%.03f", float(powerdeliv1) / EnergyDivider);
root["CounterR1"] = szTmp;
sprintf(szTmp, "%.03f", float(powerdeliv2) / EnergyDivider);
root["CounterR2"] = szTmp;
}
}
}
void CWebServer::Cmd_CheckForUpdate(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
urights = static_cast<int>(m_users[iUser].userrights);
}
root["statuscode"] = urights;
root["status"] = "OK";
root["title"] = "CheckForUpdate";
root["HaveUpdate"] = false;
root["Revision"] = m_mainworker.m_iRevision;
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin users may update
}
bool bIsForced = (request::findValue(&req, "forced") == "true");
if (!bIsForced)
{
int nValue = 0;
m_sql.GetPreferencesVar("UseAutoUpdate", nValue);
if (nValue != 1)
{
return;
}
}
root["HaveUpdate"] = m_mainworker.IsUpdateAvailable(bIsForced);
root["DomoticzUpdateURL"] = m_mainworker.m_szDomoticzUpdateURL;
root["SystemName"] = m_mainworker.m_szSystemName;
root["Revision"] = m_mainworker.m_iRevision;
}
void CWebServer::Cmd_DownloadUpdate(WebEmSession & session, const request& req, Json::Value &root)
{
if (!m_mainworker.StartDownloadUpdate())
return;
root["status"] = "OK";
root["title"] = "DownloadUpdate";
}
void CWebServer::Cmd_DownloadReady(WebEmSession & session, const request& req, Json::Value &root)
{
if (!m_mainworker.m_bHaveDownloadedDomoticzUpdate)
return;
root["status"] = "OK";
root["title"] = "DownloadReady";
root["downloadok"] = (m_mainworker.m_bHaveDownloadedDomoticzUpdateSuccessFull) ? true : false;
}
void CWebServer::Cmd_DeleteDatePoint(WebEmSession & session, const request& req, Json::Value &root)
{
const std::string idx = request::findValue(&req, "idx");
const std::string Date = request::findValue(&req, "date");
if (
(idx.empty()) ||
(Date.empty())
)
return;
root["status"] = "OK";
root["title"] = "deletedatapoint";
m_sql.DeleteDataPoint(idx.c_str(), Date);
}
bool CWebServer::IsIdxForUser(const WebEmSession *pSession, const int Idx)
{
if (pSession->rights == 2)
return true;
if (pSession->rights == 0)
return false; //viewer
//User
int iUser = FindUser(pSession->username.c_str());
if ((iUser < 0) || (iUser >= (int)m_users.size()))
return false;
if (m_users[iUser].TotSensors == 0)
return true; // all sensors
std::vector<std::vector<std::string> > result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == '%d') AND (DeviceRowID == '%d')", m_users[iUser].ID, Idx);
return (!result.empty());
}
void CWebServer::HandleCommand(const std::string &cparam, WebEmSession & session, const request& req, Json::Value &root)
{
std::map < std::string, webserver_response_function >::iterator pf = m_webcommands.find(cparam);
if (pf != m_webcommands.end())
{
pf->second(session, req, root);
return;
}
std::vector<std::vector<std::string> > result;
char szTmp[300];
bool bHaveUser = (session.username != "");
int iUser = -1;
if (bHaveUser)
{
iUser = FindUser(session.username.c_str());
}
if (cparam == "deleteallsubdevices")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllSubDevices";
result = m_sql.safe_query("DELETE FROM LightSubDevices WHERE (ParentID == '%q')", idx.c_str());
}
else if (cparam == "deletesubdevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteSubDevice";
result = m_sql.safe_query("DELETE FROM LightSubDevices WHERE (ID == '%q')", idx.c_str());
}
else if (cparam == "addsubdevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string subidx = request::findValue(&req, "subidx");
if ((idx.empty()) || (subidx.empty()))
return;
if (idx == subidx)
return;
//first check if it is not already a sub device
result = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q') AND (ParentID =='%q')",
subidx.c_str(), idx.c_str());
if (result.empty())
{
root["status"] = "OK";
root["title"] = "AddSubDevice";
//no it is not, add it
result = m_sql.safe_query(
"INSERT INTO LightSubDevices (DeviceRowID, ParentID) VALUES ('%q','%q')",
subidx.c_str(),
idx.c_str()
);
}
}
else if (cparam == "addscenedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string devidx = request::findValue(&req, "devidx");
std::string isscene = request::findValue(&req, "isscene");
std::string scommand = request::findValue(&req, "command");
int ondelay = atoi(request::findValue(&req, "ondelay").c_str());
int offdelay = atoi(request::findValue(&req, "offdelay").c_str());
if (
(idx.empty()) ||
(devidx.empty()) ||
(isscene.empty())
)
return;
int level = -1;
if (request::hasValue(&req, "level"))
level = atoi(request::findValue(&req, "level").c_str());
std::string color = _tColor(request::findValue(&req, "color")).toJSONString(); //Parse the color to detect incorrectly formatted color data
unsigned char command = 0;
result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType, SwitchType, Options FROM DeviceStatus WHERE (ID=='%q')",
devidx.c_str());
if (!result.empty())
{
int dType = atoi(result[0][3].c_str());
int sType = atoi(result[0][4].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(result[0][5].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(result[0][6].c_str());
GetLightCommand(dType, sType, switchtype, scommand, command, options);
}
//first check if this device is not the scene code!
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID=='%q')", idx.c_str());
if (!result.empty())
{
int SceneType = atoi(result[0][1].c_str());
std::vector<std::string> arrayActivators;
StringSplit(result[0][0], ";", arrayActivators);
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
std::string sCode = "";
if (arrayCode.size() == 2)
{
sCode = arrayCode[1];
}
if (sID == devidx)
{
return; //Group does not work with separate codes, so already there
}
}
}
//first check if it is not already a part of this scene/group (with the same OnDelay)
if (isscene == "true") {
result = m_sql.safe_query("SELECT ID FROM SceneDevices WHERE (DeviceRowID=='%q') AND (SceneRowID =='%q') AND (OnDelay == %d) AND (OffDelay == %d) AND (Cmd == %d)",
devidx.c_str(), idx.c_str(), ondelay, offdelay, command);
}
else {
result = m_sql.safe_query("SELECT ID FROM SceneDevices WHERE (DeviceRowID=='%q') AND (SceneRowID =='%q') AND (OnDelay == %d)",
devidx.c_str(), idx.c_str(), ondelay);
}
if (result.empty())
{
root["status"] = "OK";
root["title"] = "AddSceneDevice";
//no it is not, add it
if (isscene == "true")
{
m_sql.safe_query(
"INSERT INTO SceneDevices (DeviceRowID, SceneRowID, Cmd, Level, Color, OnDelay, OffDelay) VALUES ('%q','%q',%d,%d,'%q',%d,%d)",
devidx.c_str(),
idx.c_str(),
command,
level,
color.c_str(),
ondelay,
offdelay
);
}
else
{
m_sql.safe_query(
"INSERT INTO SceneDevices (DeviceRowID, SceneRowID, Level, Color, OnDelay, OffDelay) VALUES ('%q','%q',%d,'%q',%d,%d)",
devidx.c_str(),
idx.c_str(),
level,
color.c_str(),
ondelay,
offdelay
);
}
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentScenesGroups();
}
}
else if (cparam == "updatescenedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string devidx = request::findValue(&req, "devidx");
std::string scommand = request::findValue(&req, "command");
int ondelay = atoi(request::findValue(&req, "ondelay").c_str());
int offdelay = atoi(request::findValue(&req, "offdelay").c_str());
if (
(idx.empty()) ||
(devidx.empty())
)
return;
unsigned char command = 0;
result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType, SwitchType, Options FROM DeviceStatus WHERE (ID=='%q')",
devidx.c_str());
if (!result.empty())
{
int dType = atoi(result[0][3].c_str());
int sType = atoi(result[0][4].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(result[0][5].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(result[0][6].c_str());
GetLightCommand(dType, sType, switchtype, scommand, command, options);
}
int level = -1;
if (request::hasValue(&req, "level"))
level = atoi(request::findValue(&req, "level").c_str());
std::string color = _tColor(request::findValue(&req, "color")).toJSONString(); //Parse the color to detect incorrectly formatted color data
root["status"] = "OK";
root["title"] = "UpdateSceneDevice";
result = m_sql.safe_query(
"UPDATE SceneDevices SET Cmd=%d, Level=%d, Color='%q', OnDelay=%d, OffDelay=%d WHERE (ID == '%q')",
command, level, color.c_str(), ondelay, offdelay, idx.c_str());
}
else if (cparam == "deletescenedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteSceneDevice";
m_sql.safe_query("DELETE FROM SceneDevices WHERE (ID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM CamerasActiveDevices WHERE (DevSceneType==1) AND (DevSceneRowID == '%q')", idx.c_str());
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentScenesGroups();
}
else if (cparam == "getsubdevices")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetSubDevices";
result = m_sql.safe_query("SELECT a.ID, b.Name FROM LightSubDevices a, DeviceStatus b WHERE (a.ParentID=='%q') AND (b.ID == a.DeviceRowID)",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["ID"] = sd[0];
root["result"][ii]["Name"] = sd[1];
ii++;
}
}
}
else if (cparam == "getscenedevices")
{
std::string idx = request::findValue(&req, "idx");
std::string isscene = request::findValue(&req, "isscene");
if (
(idx.empty()) ||
(isscene.empty())
)
return;
root["status"] = "OK";
root["title"] = "GetSceneDevices";
result = m_sql.safe_query("SELECT a.ID, b.Name, a.DeviceRowID, b.Type, b.SubType, b.nValue, b.sValue, a.Cmd, a.Level, b.ID, a.[Order], a.Color, a.OnDelay, a.OffDelay, b.SwitchType FROM SceneDevices a, DeviceStatus b WHERE (a.SceneRowID=='%q') AND (b.ID == a.DeviceRowID) ORDER BY a.[Order]",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["ID"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["DevID"] = sd[2];
root["result"][ii]["DevRealIdx"] = sd[9];
root["result"][ii]["Order"] = atoi(sd[10].c_str());
root["result"][ii]["OnDelay"] = atoi(sd[12].c_str());
root["result"][ii]["OffDelay"] = atoi(sd[13].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(sd[14].c_str());
unsigned char devType = atoi(sd[3].c_str());
//switchtype seemed not to be used down with the GetLightStatus command,
//causing RFY to go wrong, fixing here
if (devType != pTypeRFY)
switchtype = STYPE_OnOff;
unsigned char subType = atoi(sd[4].c_str());
unsigned char nValue = (unsigned char)atoi(sd[5].c_str());
std::string sValue = sd[6];
int command = atoi(sd[7].c_str());
int level = atoi(sd[8].c_str());
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(devType, subType, switchtype, command, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Command"] = lstatus;
root["result"][ii]["Level"] = level;
root["result"][ii]["Color"] = _tColor(sd[11]).toJSONString();
root["result"][ii]["Type"] = RFX_Type_Desc(devType, 1);
root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(devType, subType);
ii++;
}
}
}
else if (cparam == "changescenedeviceorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string sway = request::findValue(&req, "way");
if (sway.empty())
return;
bool bGoUp = (sway == "0");
std::string aScene, aOrder, oID, oOrder;
//Get actual device order
result = m_sql.safe_query("SELECT SceneRowID, [Order] FROM SceneDevices WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
aScene = result[0][0];
aOrder = result[0][1];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM SceneDevices WHERE (SceneRowID=='%q' AND [Order]>'%q') ORDER BY [Order] ASC",
aScene.c_str(), aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM SceneDevices WHERE (SceneRowID=='%q' AND [Order]<'%q') ORDER BY [Order] DESC",
aScene.c_str(), aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangeSceneDeviceOrder";
result = m_sql.safe_query("UPDATE SceneDevices SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
result = m_sql.safe_query("UPDATE SceneDevices SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
else if (cparam == "deleteallscenedevices")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllSceneDevices";
result = m_sql.safe_query("DELETE FROM SceneDevices WHERE (SceneRowID == %q)", idx.c_str());
}
else if (cparam == "getmanualhardware")
{
//used by Add Manual Light/Switch dialog
root["status"] = "OK";
root["title"] = "GetHardware";
result = m_sql.safe_query("SELECT ID, Name, Type FROM Hardware ORDER BY ID ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int ID = atoi(sd[0].c_str());
std::string Name = sd[1];
_eHardwareTypes Type = (_eHardwareTypes)atoi(sd[2].c_str());
if (
(Type == HTYPE_RFXLAN) ||
(Type == HTYPE_RFXtrx315) ||
(Type == HTYPE_RFXtrx433) ||
(Type == HTYPE_RFXtrx868) ||
(Type == HTYPE_EnOceanESP2) ||
(Type == HTYPE_EnOceanESP3) ||
(Type == HTYPE_Dummy) ||
(Type == HTYPE_Tellstick) ||
(Type == HTYPE_EVOHOME_SCRIPT) ||
(Type == HTYPE_EVOHOME_SERIAL) ||
(Type == HTYPE_EVOHOME_WEB) ||
(Type == HTYPE_EVOHOME_TCP) ||
(Type == HTYPE_RaspberryGPIO) ||
(Type == HTYPE_RFLINKUSB) ||
(Type == HTYPE_RFLINKTCP) ||
(Type == HTYPE_ZIBLUEUSB) ||
(Type == HTYPE_ZIBLUETCP) ||
(Type == HTYPE_OpenWebNetTCP) ||
(Type == HTYPE_OpenWebNetUSB) ||
(Type == HTYPE_SysfsGpio) ||
(Type == HTYPE_USBtinGateway)
)
{
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
}
else if (cparam == "getgpio")
{
//used by Add Manual Light/Switch dialog
root["title"] = "GetGpio";
#ifdef WITH_GPIO
std::vector<CGpioPin> pins = CGpio::GetPinList();
if (pins.size() == 0) {
root["status"] = "ERROR";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "GPIO INIT ERROR";
}
else {
int ii = 0;
for (const auto & it : pins)
{
CGpioPin pin = it;
root["status"] = "OK";
root["result"][ii]["idx"] = pin.GetPin();
root["result"][ii]["Name"] = pin.ToString();
ii++;
}
}
#else
root["status"] = "OK";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "N/A";
#endif
}
else if (cparam == "getsysfsgpio")
{
//used by Add Manual Light/Switch dialog
root["title"] = "GetSysfsGpio";
#ifdef WITH_GPIO
std::vector<int> gpio_ids = CSysfsGpio::GetGpioIds();
std::vector<std::string> gpio_names = CSysfsGpio::GetGpioNames();
if (gpio_ids.size() == 0) {
root["status"] = "ERROR";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "No sysfs-gpio exports";
}
else {
for (int ii = 0; ii < gpio_ids.size(); ii++)
{
root["status"] = "OK";
root["result"][ii]["idx"] = gpio_ids[ii];
root["result"][ii]["Name"] = gpio_names[ii];
}
}
#else
root["status"] = "OK";
root["result"][0]["idx"] = 0;
root["result"][0]["Name"] = "N/A";
#endif
}
else if (cparam == "getlightswitches")
{
root["status"] = "OK";
root["title"] = "GetLightSwitches";
result = m_sql.safe_query("SELECT ID, Name, Type, SubType, Used, SwitchType, Options FROM DeviceStatus ORDER BY Name");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
std::string Name = sd[1];
int Type = atoi(sd[2].c_str());
int SubType = atoi(sd[3].c_str());
int used = atoi(sd[4].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(sd[5].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sd[6]);
bool bdoAdd = false;
switch (Type)
{
case pTypeLighting1:
case pTypeLighting2:
case pTypeLighting3:
case pTypeLighting4:
case pTypeLighting5:
case pTypeLighting6:
case pTypeFan:
case pTypeColorSwitch:
case pTypeSecurity1:
case pTypeSecurity2:
case pTypeEvohome:
case pTypeEvohomeRelay:
case pTypeCurtain:
case pTypeBlinds:
case pTypeRFY:
case pTypeChime:
case pTypeThermostat2:
case pTypeThermostat3:
case pTypeThermostat4:
case pTypeRemote:
case pTypeRadiator1:
case pTypeGeneralSwitch:
case pTypeHomeConfort:
case pTypeFS20:
bdoAdd = true;
if (!used)
{
bdoAdd = false;
bool bIsSubDevice = false;
std::vector<std::vector<std::string> > resultSD;
resultSD = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q')",
sd[0].c_str());
if (resultSD.size() > 0)
bdoAdd = true;
}
if ((Type == pTypeRadiator1) && (SubType != sTypeSmartwaresSwitchRadiator))
bdoAdd = false;
if (bdoAdd)
{
int idx = atoi(ID.c_str());
if (!IsIdxForUser(&session, idx))
continue;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = Name;
root["result"][ii]["Type"] = RFX_Type_Desc(Type, 1);
root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(Type, SubType);
bool bIsDimmer = (
(switchtype == STYPE_Dimmer) ||
(switchtype == STYPE_BlindsPercentage) ||
(switchtype == STYPE_BlindsPercentageInverted) ||
(switchtype == STYPE_Selector)
);
root["result"][ii]["IsDimmer"] = bIsDimmer;
std::string dimmerLevels = "none";
if (bIsDimmer)
{
std::stringstream ss;
if (switchtype == STYPE_Selector) {
std::map<std::string, std::string> selectorStatuses;
GetSelectorSwitchStatuses(options, selectorStatuses);
bool levelOffHidden = (options["LevelOffHidden"] == "true");
for (int i = 0; i < (int)selectorStatuses.size(); i++) {
if (levelOffHidden && (i == 0)) {
continue;
}
if ((levelOffHidden && (i > 1)) || (i > 0)) {
ss << ",";
}
ss << i * 10;
}
}
else
{
int nValue = 0;
std::string sValue = "";
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
int maxDimLevel = 0;
bool bHaveGroupCmd = false;
GetLightStatus(Type, SubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
for (int i = 0; i <= maxDimLevel; i++)
{
if (i != 0)
{
ss << ",";
}
ss << (int)float((100.0f / float(maxDimLevel))*i);
}
}
dimmerLevels = ss.str();
}
root["result"][ii]["DimmerLevels"] = dimmerLevels;
ii++;
}
break;
}
}
}
}
else if (cparam == "getlightswitchesscenes")
{
root["status"] = "OK";
root["title"] = "GetLightSwitchesScenes";
int ii = 0;
//First List/Switch Devices
result = m_sql.safe_query("SELECT ID, Name, Type, SubType, Used FROM DeviceStatus ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
std::string Name = sd[1];
int Type = atoi(sd[2].c_str());
int SubType = atoi(sd[3].c_str());
int used = atoi(sd[4].c_str());
if (used)
{
switch (Type)
{
case pTypeLighting1:
case pTypeLighting2:
case pTypeLighting3:
case pTypeLighting4:
case pTypeLighting5:
case pTypeLighting6:
case pTypeFan:
case pTypeColorSwitch:
case pTypeSecurity1:
case pTypeSecurity2:
case pTypeEvohome:
case pTypeEvohomeRelay:
case pTypeCurtain:
case pTypeBlinds:
case pTypeRFY:
case pTypeChime:
case pTypeThermostat2:
case pTypeThermostat3:
case pTypeThermostat4:
case pTypeRemote:
case pTypeGeneralSwitch:
case pTypeHomeConfort:
case pTypeFS20:
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = "[Light/Switch] " + Name;
ii++;
break;
case pTypeRadiator1:
if (SubType == sTypeSmartwaresSwitchRadiator)
{
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = "[Light/Switch] " + Name;
ii++;
}
break;
}
}
}
}//end light/switches
//Add Scenes
result = m_sql.safe_query("SELECT ID, Name FROM Scenes ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
std::string Name = sd[1];
root["result"][ii]["type"] = 1;
root["result"][ii]["idx"] = ID;
root["result"][ii]["Name"] = "[Scene] " + Name;
ii++;
}
}//end light/switches
}
else if (cparam == "getcamactivedevices")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetCameraActiveDevices";
//First List/Switch Devices
result = m_sql.safe_query("SELECT ID, DevSceneType, DevSceneRowID, DevSceneWhen, DevSceneDelay FROM CamerasActiveDevices WHERE (CameraRowID=='%q') ORDER BY ID",
idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string ID = sd[0];
int DevSceneType = atoi(sd[1].c_str());
std::string DevSceneRowID = sd[2];
int DevSceneWhen = atoi(sd[3].c_str());
int DevSceneDelay = atoi(sd[4].c_str());
std::string Name = "";
if (DevSceneType == 0)
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM DeviceStatus WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = "[Light/Switches] " + result2[0][0];
}
}
else
{
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query("SELECT Name FROM Scenes WHERE (ID=='%q')",
DevSceneRowID.c_str());
if (!result2.empty())
{
Name = "[Scene] " + result2[0][0];
}
}
if (Name != "")
{
root["result"][ii]["idx"] = ID;
root["result"][ii]["type"] = DevSceneType;
root["result"][ii]["DevSceneRowID"] = DevSceneRowID;
root["result"][ii]["when"] = DevSceneWhen;
root["result"][ii]["delay"] = DevSceneDelay;
root["result"][ii]["Name"] = Name;
ii++;
}
}
}
}
else if (cparam == "addcamactivedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string activeidx = request::findValue(&req, "activeidx");
std::string sactivetype = request::findValue(&req, "activetype");
std::string sactivewhen = request::findValue(&req, "activewhen");
std::string sactivedelay = request::findValue(&req, "activedelay");
if (
(idx.empty()) ||
(activeidx.empty()) ||
(sactivetype.empty()) ||
(sactivewhen.empty()) ||
(sactivedelay.empty())
)
{
return;
}
int activetype = atoi(sactivetype.c_str());
int activewhen = atoi(sactivewhen.c_str());
int activedelay = atoi(sactivedelay.c_str());
//first check if it is not already a Active Device
result = m_sql.safe_query(
"SELECT ID FROM CamerasActiveDevices WHERE (CameraRowID=='%q')"
" AND (DevSceneType==%d) AND (DevSceneRowID=='%q')"
" AND (DevSceneWhen==%d)",
idx.c_str(), activetype, activeidx.c_str(), activewhen);
if (result.empty())
{
root["status"] = "OK";
root["title"] = "AddCameraActiveDevice";
//no it is not, add it
result = m_sql.safe_query(
"INSERT INTO CamerasActiveDevices (CameraRowID, DevSceneType, DevSceneRowID, DevSceneWhen, DevSceneDelay) VALUES ('%q',%d,'%q',%d,%d)",
idx.c_str(),
activetype,
activeidx.c_str(),
activewhen,
activedelay
);
m_mainworker.m_cameras.ReloadCameras();
}
}
else if (cparam == "deleteamactivedevice")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteCameraActiveDevice";
result = m_sql.safe_query("DELETE FROM CamerasActiveDevices WHERE (ID == '%q')", idx.c_str());
m_mainworker.m_cameras.ReloadCameras();
}
else if (cparam == "deleteallactivecamdevices")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteAllCameraActiveDevices";
result = m_sql.safe_query("DELETE FROM CamerasActiveDevices WHERE (CameraRowID == '%q')", idx.c_str());
m_mainworker.m_cameras.ReloadCameras();
}
else if (cparam == "testnotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string notification_Title = "Domoticz test";
std::string notification_Message = "Domoticz test message!";
std::string subsystem = request::findValue(&req, "subsystem");
std::string extraData = request::findValue(&req, "extradata");
m_notifications.ConfigFromGetvars(req, false);
if (m_notifications.SendMessage(0, std::string(""), subsystem, notification_Title, notification_Message, extraData, 1, std::string(""), false)) {
root["status"] = "OK";
}
/* we need to reload the config, because the values that were set were only for testing */
m_notifications.LoadConfig();
}
else if (cparam == "testswitch")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string hwdid = request::findValue(&req, "hwdid");
std::string sswitchtype = request::findValue(&req, "switchtype");
std::string slighttype = request::findValue(&req, "lighttype");
if (
(hwdid.empty()) ||
(sswitchtype.empty()) ||
(slighttype.empty())
)
return;
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
int lighttype = atoi(slighttype.c_str());
int dtype;
int subtype = 0;
std::string sunitcode;
std::string devid;
if (lighttype == 70)
{
//EnOcean (Lighting2 with Base_ID offset)
dtype = pTypeLighting2;
subtype = sTypeAC;
std::string sgroupcode = request::findValue(&req, "groupcode");
sunitcode = request::findValue(&req, "unitcode");
int iUnitTest = atoi(sunitcode.c_str()); //only First Rocker_ID at the moment, gives us 128 devices we can control, should be enough!
if (
(sunitcode.empty()) ||
(sgroupcode.empty()) ||
((iUnitTest < 1) || (iUnitTest > 128))
)
return;
sunitcode = sgroupcode;//Button A or B
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pBaseHardware == NULL)
return;
if ((pBaseHardware->HwdType != HTYPE_EnOceanESP2) && (pBaseHardware->HwdType != HTYPE_EnOceanESP3)
&& (pBaseHardware->HwdType != HTYPE_USBtinGateway) )
return;
unsigned long rID = 0;
if (pBaseHardware->HwdType == HTYPE_EnOceanESP2)
{
CEnOceanESP2 *pEnoceanHardware = reinterpret_cast<CEnOceanESP2 *>(pBaseHardware);
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_EnOceanESP3)
{
CEnOceanESP3 *pEnoceanHardware = reinterpret_cast<CEnOceanESP3 *>(pBaseHardware);
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_USBtinGateway) //Like EnOcean (Lighting2 with Base_ID offset)
{
USBtin *pUSBtinHardware = reinterpret_cast<USBtin *>(pBaseHardware);
//base ID calculate in the USBtinharwade dependant of the CAN Layer !
//for exemple see MultiblocV8 layer...
rID = pUSBtinHardware->switch_id_base;
std::stringstream ssunitcode;
ssunitcode << iUnitTest;
sunitcode = ssunitcode.str();
}
//convert to hex, and we have our ID
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << rID;
devid = s_strid.str();
}
else if (lighttype == 68)
{
#ifdef WITH_GPIO
dtype = pTypeLighting1;
subtype = sTypeIMPULS;
devid = "0";
sunitcode = request::findValue(&req, "unitcode"); //Unit code = GPIO number
if (sunitcode.empty()) {
root["status"] = "ERROR";
root["message"] = "No GPIO number given";
return;
}
CGpio *pGpio = reinterpret_cast<CGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pGpio == NULL) {
root["status"] = "ERROR";
root["message"] = "Could not retrieve GPIO hardware pointer";
return;
}
if (pGpio->HwdType != HTYPE_RaspberryGPIO) {
root["status"] = "ERROR";
root["message"] = "Given hardware is not GPIO";
return;
}
CGpioPin *pPin = CGpio::GetPPinById(atoi(sunitcode.c_str()));
if (pPin == NULL) {
root["status"] = "ERROR";
root["message"] = "Given pin does not exist on this GPIO hardware";
return;
}
if (pPin->GetIsInput()) {
root["status"] = "ERROR";
root["message"] = "Given pin is not configured for output";
return;
}
#else
root["status"] = "ERROR";
root["message"] = "GPIO support is disabled";
return;
#endif
}
else if (lighttype == 69)
{
#ifdef WITH_GPIO
sunitcode = request::findValue(&req, "unitcode"); // sysfs-gpio number
int unitcode = atoi(sunitcode.c_str());
dtype = pTypeLighting2;
subtype = sTypeAC;
std::string sswitchtype = request::findValue(&req, "switchtype");
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
std::string id = request::findValue(&req, "id");
if ((id.empty()) || (sunitcode.empty()))
{
return;
}
devid = id;
if (sunitcode.empty())
{
root["status"] = "ERROR";
root["message"] = "No GPIO number given";
return;
}
CSysfsGpio *pSysfsGpio = reinterpret_cast<CSysfsGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pSysfsGpio == NULL) {
root["status"] = "ERROR";
root["message"] = "Could not retrieve SysfsGpio hardware pointer";
return;
}
if (pSysfsGpio->HwdType != HTYPE_SysfsGpio) {
root["status"] = "ERROR";
root["message"] = "Given hardware is not SysfsGpio";
return;
}
#else
root["status"] = "ERROR";
root["message"] = "GPIO support is disabled";
return;
#endif
}
else if (lighttype < 20)
{
dtype = pTypeLighting1;
subtype = lighttype;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype < 30)
{
dtype = pTypeLighting2;
subtype = lighttype - 20;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype < 70)
{
dtype = pTypeLighting5;
subtype = lighttype - 50;
if (lighttype == 59)
subtype = sTypeIT;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
if ((subtype != sTypeEMW100) && (subtype != sTypeLivolo) && (subtype != sTypeLivolo1to10) && (subtype != sTypeRGB432W) && (subtype != sTypeIT))
devid = "00" + id;
else
devid = id;
}
else
{
if (lighttype == 100)
{
//Chime/ByronSX
dtype = pTypeChime;
subtype = sTypeByronSX;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str()) - 1;
switch (iUnitCode)
{
case 0:
iUnitCode = chime_sound0;
break;
case 1:
iUnitCode = chime_sound1;
break;
case 2:
iUnitCode = chime_sound2;
break;
case 3:
iUnitCode = chime_sound3;
break;
case 4:
iUnitCode = chime_sound4;
break;
case 5:
iUnitCode = chime_sound5;
break;
case 6:
iUnitCode = chime_sound6;
break;
case 7:
iUnitCode = chime_sound7;
break;
}
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if (lighttype == 101)
{
//Curtain Harrison
dtype = pTypeCurtain;
subtype = sTypeHarrison;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype == 102)
{
//RFY
dtype = pTypeRFY;
subtype = sTypeRFY;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 103)
{
//Meiantech
dtype = pTypeSecurity1;
subtype = sTypeMeiantech;
std::string id = request::findValue(&req, "id");
if (
(id.empty())
)
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 104)
{
//HE105
dtype = pTypeThermostat2;
subtype = sTypeHE105;
sunitcode = request::findValue(&req, "unitcode");
if (sunitcode.empty())
return;
//convert to hex, and we have our Unit Code
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << sunitcode;
int iUnitCode;
s_strid >> iUnitCode;
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = "1";
}
else if (lighttype == 105)
{
//ASA
dtype = pTypeRFY;
subtype = sTypeASA;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 106)
{
//Blyss
dtype = pTypeLighting6;
subtype = sTypeBlyss;
std::string sgroupcode = request::findValue(&req, "groupcode");
sunitcode = request::findValue(&req, "unitcode");
std::string id = request::findValue(&req, "id");
if (
(sgroupcode.empty()) ||
(sunitcode.empty()) ||
(id.empty())
)
return;
devid = id + sgroupcode;
}
else if (lighttype == 107)
{
//RFY2
dtype = pTypeRFY;
subtype = sTypeRFY2;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if ((lighttype >= 200) && (lighttype < 300))
{
dtype = pTypeBlinds;
subtype = lighttype - 200;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if (lighttype == 301)
{
//Smartwares Radiator
dtype = pTypeRadiator1;
subtype = sTypeSmartwaresSwitchRadiator;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 302)
{
//Home Confort
dtype = pTypeHomeConfort;
subtype = sTypeHomeConfortTEL010;
std::string id = request::findValue(&req, "id");
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
sprintf(szTmp, "%02X", atoi(shousecode.c_str()));
shousecode = szTmp;
devid = id + shousecode;
}
else if (lighttype == 303)
{
//Selector Switch
dtype = pTypeGeneralSwitch;
subtype = sSwitchTypeSelector;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 304)
{
//Itho CVE RFT
dtype = pTypeFan;
subtype = sTypeItho;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 305)
{
//Lucci Air/DC
dtype = pTypeFan;
subtype = sTypeLucciAir;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 306)
{
//Lucci Air DC
dtype = pTypeFan;
subtype = sTypeLucciAirDC;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 307)
{
//Westinghouse
dtype = pTypeFan;
subtype = sTypeWestinghouse;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 400) {
//Openwebnet Bus Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 401) {
//Openwebnet Bus Lights
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 402)
{
//Openwebnet Bus Auxiliary
dtype = pTypeGeneralSwitch;
subtype = sSwitchAuxiliaryT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 403) {
//Openwebnet Zigbee Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 404) {
//Light Openwebnet Zigbee
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if ((lighttype == 405) || (lighttype == 406)) {
// Openwebnet Dry Contact / IR Detection
dtype = pTypeGeneralSwitch;
subtype = sSwitchContactT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
}
// ----------- If needed convert to GeneralSwitch type (for o.a. RFlink) -----------
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pBaseHardware != NULL)
{
if ((pBaseHardware->HwdType == HTYPE_RFLINKUSB) || (pBaseHardware->HwdType == HTYPE_RFLINKTCP)) {
ConvertToGeneralSwitchType(devid, dtype, subtype);
}
}
// -----------------------------------------------
root["status"] = "OK";
root["message"] = "OK";
root["title"] = "TestSwitch";
std::vector<std::string> sd;
sd.push_back(hwdid);
sd.push_back(devid);
sd.push_back(sunitcode);
sprintf(szTmp, "%d", dtype);
sd.push_back(szTmp);
sprintf(szTmp, "%d", subtype);
sd.push_back(szTmp);
sprintf(szTmp, "%d", switchtype);
sd.push_back(szTmp);
sd.push_back(""); //AddjValue2
sd.push_back(""); //nValue
sd.push_back(""); //sValue
sd.push_back(""); //Name
sd.push_back(""); //Options
std::string switchcmd = "On";
int level = 0;
if (lighttype == 70)
{
//Special EnOcean case, if it is a dimmer, set a dim value
if (switchtype == STYPE_Dimmer)
level = 5;
}
m_mainworker.SwitchLightInt(sd, switchcmd, level, NoColor, true);
}
else if (cparam == "addswitch")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string hwdid = request::findValue(&req, "hwdid");
std::string name = request::findValue(&req, "name");
std::string sswitchtype = request::findValue(&req, "switchtype");
std::string slighttype = request::findValue(&req, "lighttype");
std::string maindeviceidx = request::findValue(&req, "maindeviceidx");
std::string deviceoptions;
if (
(hwdid.empty()) ||
(sswitchtype.empty()) ||
(slighttype.empty()) ||
(name.empty())
)
return;
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
int lighttype = atoi(slighttype.c_str());
int dtype = 0;
int subtype = 0;
std::string sunitcode;
std::string devid;
#ifdef ENABLE_PYTHON
//check if HW is plugin
{
result = m_sql.safe_query("SELECT Type FROM Hardware WHERE (ID == '%q')", hwdid.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
_eHardwareTypes Type = (_eHardwareTypes)atoi(sd[0].c_str());
if (Type == HTYPE_PythonPlugin)
{
// Not allowed to add device to plugin HW (plugin framework does not use key column "ID" but instead uses column "unit" as key)
_log.Log(LOG_ERROR, "CWebServer::HandleCommand addswitch: Not allowed to add device owned by plugin %u!", atoi(hwdid.c_str()));
root["message"] = "Not allowed to add switch to plugin HW!";
return;
}
}
}
#endif
if (lighttype == 70)
{
//EnOcean (Lighting2 with Base_ID offset)
dtype = pTypeLighting2;
subtype = sTypeAC;
sunitcode = request::findValue(&req, "unitcode");
std::string sgroupcode = request::findValue(&req, "groupcode");
int iUnitTest = atoi(sunitcode.c_str()); //gives us 128 devices we can control, should be enough!
if (
(sunitcode.empty()) ||
(sgroupcode.empty()) ||
((iUnitTest < 1) || (iUnitTest > 128))
)
return;
sunitcode = sgroupcode;//Button A/B
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pBaseHardware == NULL)
return;
if ((pBaseHardware->HwdType != HTYPE_EnOceanESP2) && (pBaseHardware->HwdType != HTYPE_EnOceanESP3)
&& (pBaseHardware->HwdType != HTYPE_USBtinGateway) )
return;
unsigned long rID = 0;
if (pBaseHardware->HwdType == HTYPE_EnOceanESP2)
{
CEnOceanESP2 *pEnoceanHardware = reinterpret_cast<CEnOceanESP2*>(pBaseHardware);
if (pEnoceanHardware->m_id_base == 0)
{
root["message"] = "BaseID not found, is the hardware running?";
return;
}
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_EnOceanESP3)
{
CEnOceanESP3 *pEnoceanHardware = reinterpret_cast<CEnOceanESP3*>(pBaseHardware);
if (pEnoceanHardware->m_id_base == 0)
{
root["message"] = "BaseID not found, is the hardware running?";
return;
}
rID = pEnoceanHardware->m_id_base + iUnitTest;
}
else if (pBaseHardware->HwdType == HTYPE_USBtinGateway)
{
USBtin *pUSBtinHardware = reinterpret_cast<USBtin *>(pBaseHardware);
rID = pUSBtinHardware->switch_id_base;
std::stringstream ssunitcode;
ssunitcode << iUnitTest;
sunitcode = ssunitcode.str();
}
//convert to hex, and we have our ID
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << rID;
devid = s_strid.str();
}
else if (lighttype == 68)
{
#ifdef WITH_GPIO
dtype = pTypeLighting1;
subtype = sTypeIMPULS;
devid = "0";
sunitcode = request::findValue(&req, "unitcode"); //Unit code = GPIO number
if (sunitcode.empty()) {
return;
}
CGpio *pGpio = reinterpret_cast<CGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if (pGpio == NULL) {
return;
}
if (pGpio->HwdType != HTYPE_RaspberryGPIO) {
return;
}
CGpioPin *pPin = CGpio::GetPPinById(atoi(sunitcode.c_str()));
if (pPin == NULL) {
return;
}
#else
return;
#endif
}
else if (lighttype == 69)
{
#ifdef WITH_GPIO
dtype = pTypeLighting2;
subtype = sTypeAC;
devid = "0";
sunitcode = request::findValue(&req, "unitcode"); // sysfs-gpio number
int unitcode = atoi(sunitcode.c_str());
std::string sswitchtype = request::findValue(&req, "switchtype");
_eSwitchType switchtype = (_eSwitchType)atoi(sswitchtype.c_str());
std::string id = request::findValue(&req, "id");
CSysfsGpio::RequestDbUpdate(unitcode);
if ((id.empty()) || (sunitcode.empty()))
{
return;
}
devid = id;
CSysfsGpio *pSysfsGpio = reinterpret_cast<CSysfsGpio *>(m_mainworker.GetHardware(atoi(hwdid.c_str())));
if ((pSysfsGpio == NULL) || (pSysfsGpio->HwdType != HTYPE_SysfsGpio))
{
return;
}
#else
return;
#endif
}
else if (lighttype < 20)
{
dtype = pTypeLighting1;
subtype = lighttype;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype < 30)
{
dtype = pTypeLighting2;
subtype = lighttype - 20;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype < 70)
{
dtype = pTypeLighting5;
subtype = lighttype - 50;
if (lighttype == 59)
subtype = sTypeIT;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
if ((subtype != sTypeEMW100) && (subtype != sTypeLivolo) && (subtype != sTypeLivolo1to10) && (subtype != sTypeRGB432W) && (subtype != sTypeLightwaveRF) && (subtype != sTypeIT))
devid = "00" + id;
else
devid = id;
}
else if (lighttype == 101)
{
//Curtain Harrison
dtype = pTypeCurtain;
subtype = sTypeHarrison;
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
devid = shousecode;
}
else if (lighttype == 102)
{
//RFY
dtype = pTypeRFY;
subtype = sTypeRFY;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 103)
{
//Meiantech
dtype = pTypeSecurity1;
subtype = sTypeMeiantech;
std::string id = request::findValue(&req, "id");
if (
(id.empty())
)
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 104)
{
//HE105
dtype = pTypeThermostat2;
subtype = sTypeHE105;
sunitcode = request::findValue(&req, "unitcode");
if (sunitcode.empty())
return;
//convert to hex, and we have our Unit Code
std::stringstream s_strid;
s_strid << std::hex << std::uppercase << sunitcode;
int iUnitCode;
s_strid >> iUnitCode;
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = "1";
}
else if (lighttype == 105)
{
//ASA
dtype = pTypeRFY;
subtype = sTypeASA;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else if (lighttype == 106)
{
//Blyss
dtype = pTypeLighting6;
subtype = sTypeBlyss;
std::string sgroupcode = request::findValue(&req, "groupcode");
sunitcode = request::findValue(&req, "unitcode");
std::string id = request::findValue(&req, "id");
if (
(sgroupcode.empty()) ||
(sunitcode.empty()) ||
(id.empty())
)
return;
devid = id + sgroupcode;
}
else if (lighttype == 107)
{
//RFY2
dtype = pTypeRFY;
subtype = sTypeRFY2;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
}
else
{
if (lighttype == 100)
{
//Chime/ByronSX
dtype = pTypeChime;
subtype = sTypeByronSX;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str()) - 1;
switch (iUnitCode)
{
case 0:
iUnitCode = chime_sound0;
break;
case 1:
iUnitCode = chime_sound1;
break;
case 2:
iUnitCode = chime_sound2;
break;
case 3:
iUnitCode = chime_sound3;
break;
case 4:
iUnitCode = chime_sound4;
break;
case 5:
iUnitCode = chime_sound5;
break;
case 6:
iUnitCode = chime_sound6;
break;
case 7:
iUnitCode = chime_sound7;
break;
}
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if ((lighttype >= 200) && (lighttype < 300))
{
dtype = pTypeBlinds;
subtype = lighttype - 200;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
devid = id;
}
else if (lighttype == 301)
{
//Smartwares Radiator
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = id;
//For this device, we will also need to add a Radiator type, do that first
dtype = pTypeRadiator1;
subtype = sTypeSmartwares;
//check if switch is unique
result = m_sql.safe_query(
"SELECT Name FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (!result.empty())
{
root["message"] = "Switch already exists!";
return;
}
bool bActEnabledState = m_sql.m_bAcceptNewHardware;
m_sql.m_bAcceptNewHardware = true;
std::string devname;
m_sql.UpdateValue(atoi(hwdid.c_str()), devid.c_str(), atoi(sunitcode.c_str()), dtype, subtype, 0, -1, 0, "20.5", devname);
m_sql.m_bAcceptNewHardware = bActEnabledState;
//set name and switchtype
result = m_sql.safe_query(
"SELECT ID FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (result.empty())
{
root["message"] = "Error finding switch in Database!?!?";
return;
}
std::string ID = result[0][0];
m_sql.safe_query(
"UPDATE DeviceStatus SET Used=1, Name='%q', SwitchType=%d WHERE (ID == '%q')",
name.c_str(), switchtype, ID.c_str());
//Now continue to insert the switch
dtype = pTypeRadiator1;
subtype = sTypeSmartwaresSwitchRadiator;
}
else if (lighttype == 302)
{
//Home Confort
dtype = pTypeHomeConfort;
subtype = sTypeHomeConfortTEL010;
std::string id = request::findValue(&req, "id");
std::string shousecode = request::findValue(&req, "housecode");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(shousecode.empty()) ||
(sunitcode.empty())
)
return;
int iUnitCode = atoi(sunitcode.c_str());
sprintf(szTmp, "%d", iUnitCode);
sunitcode = szTmp;
sprintf(szTmp, "%02X", atoi(shousecode.c_str()));
shousecode = szTmp;
devid = id + shousecode;
}
else if (lighttype == 303)
{
//Selector Switch
dtype = pTypeGeneralSwitch;
subtype = sSwitchTypeSelector;
std::string id = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(id.empty()) ||
(sunitcode.empty())
)
return;
devid = "0" + id;
switchtype = STYPE_Selector;
if (!deviceoptions.empty()) {
deviceoptions.append(";");
}
deviceoptions.append("SelectorStyle:0;LevelNames:Off|Level1|Level2|Level3");
}
else if (lighttype == 304)
{
//Itho CVE RFT
dtype = pTypeFan;
subtype = sTypeItho;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 305)
{
//Lucci Air
dtype = pTypeFan;
subtype = sTypeLucciAir;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 306)
{
//Lucci Air DC
dtype = pTypeFan;
subtype = sTypeLucciAirDC;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 307)
{
//Westinghouse
dtype = pTypeFan;
subtype = sTypeWestinghouse;
std::string id = request::findValue(&req, "id");
if (id.empty())
return;
devid = id;
sunitcode = "0";
}
else if (lighttype == 400)
{
//Openwebnet Bus Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 401)
{
//Openwebnet Bus Lights
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 402)
{
//Openwebnet Bus Auxiliary
dtype = pTypeGeneralSwitch;
subtype = sSwitchAuxiliaryT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 403)
{
//Openwebnet Zigbee Blinds
dtype = pTypeGeneralSwitch;
subtype = sSwitchBlindsT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if (lighttype == 404)
{
//Openwebnet Zigbee Lights
dtype = pTypeGeneralSwitch;
subtype = sSwitchLightT2;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
else if ((lighttype == 405) || (lighttype == 406))
{
//Openwebnet Dry Contact / IR Detection
dtype = pTypeGeneralSwitch;
subtype = sSwitchContactT1;
devid = request::findValue(&req, "id");
sunitcode = request::findValue(&req, "unitcode");
if (
(devid.empty()) ||
(sunitcode.empty())
)
return;
}
}
//check if switch is unique
result = m_sql.safe_query(
"SELECT Name FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (!result.empty())
{
root["message"] = "Switch already exists!";
return;
}
// ----------- If needed convert to GeneralSwitch type (for o.a. RFlink) -----------
CDomoticzHardwareBase *pBaseHardware = m_mainworker.GetHardware(atoi(hwdid.c_str()));
if (pBaseHardware != NULL)
{
if ((pBaseHardware->HwdType == HTYPE_RFLINKUSB) || (pBaseHardware->HwdType == HTYPE_RFLINKTCP)) {
ConvertToGeneralSwitchType(devid, dtype, subtype);
}
}
// -----------------------------------------------
bool bActEnabledState = m_sql.m_bAcceptNewHardware;
m_sql.m_bAcceptNewHardware = true;
std::string devname;
m_sql.UpdateValue(atoi(hwdid.c_str()), devid.c_str(), atoi(sunitcode.c_str()), dtype, subtype, 0, -1, 0, devname);
m_sql.m_bAcceptNewHardware = bActEnabledState;
//set name and switchtype
result = m_sql.safe_query(
"SELECT ID FROM DeviceStatus WHERE (HardwareID=='%q' AND DeviceID=='%q' AND Unit=='%q' AND Type==%d AND SubType==%d)",
hwdid.c_str(), devid.c_str(), sunitcode.c_str(), dtype, subtype);
if (result.empty())
{
root["message"] = "Error finding switch in Database!?!?";
return;
}
std::string ID = result[0][0];
m_sql.safe_query(
"UPDATE DeviceStatus SET Used=1, Name='%q', SwitchType=%d WHERE (ID == '%q')",
name.c_str(), switchtype, ID.c_str());
m_mainworker.m_eventsystem.GetCurrentStates();
//Set device options
m_sql.SetDeviceOptions(atoi(ID.c_str()), m_sql.BuildDeviceOptions(deviceoptions, false));
if (maindeviceidx != "")
{
if (maindeviceidx != ID)
{
//this is a sub device for another light/switch
//first check if it is not already a sub device
result = m_sql.safe_query(
"SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q') AND (ParentID =='%q')",
ID.c_str(), maindeviceidx.c_str());
if (result.empty())
{
//no it is not, add it
result = m_sql.safe_query(
"INSERT INTO LightSubDevices (DeviceRowID, ParentID) VALUES ('%q','%q')",
ID.c_str(),
maindeviceidx.c_str()
);
}
}
}
root["status"] = "OK";
root["title"] = "AddSwitch";
}
else if (cparam == "getnotificationtypes")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
//First get Device Type/SubType
result = m_sql.safe_query("SELECT Type, SubType, SwitchType FROM DeviceStatus WHERE (ID == '%q')",
idx.c_str());
if (result.empty())
return;
root["status"] = "OK";
root["title"] = "GetNotificationTypes";
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
unsigned char switchtype = atoi(result[0][2].c_str());
int ii = 0;
if (
(dType == pTypeLighting1) ||
(dType == pTypeLighting2) ||
(dType == pTypeLighting3) ||
(dType == pTypeLighting4) ||
(dType == pTypeLighting5) ||
(dType == pTypeLighting6) ||
(dType == pTypeColorSwitch) ||
(dType == pTypeSecurity1) ||
(dType == pTypeSecurity2) ||
(dType == pTypeEvohome) ||
(dType == pTypeEvohomeRelay) ||
(dType == pTypeCurtain) ||
(dType == pTypeBlinds) ||
(dType == pTypeRFY) ||
(dType == pTypeChime) ||
(dType == pTypeThermostat2) ||
(dType == pTypeThermostat3) ||
(dType == pTypeThermostat4) ||
(dType == pTypeRemote) ||
(dType == pTypeGeneralSwitch) ||
(dType == pTypeHomeConfort) ||
(dType == pTypeFS20) ||
((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator))
)
{
if (switchtype != STYPE_PushOff)
{
root["result"][ii]["val"] = NTYPE_SWITCH_ON;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 1);
ii++;
}
if (switchtype != STYPE_PushOn)
{
root["result"][ii]["val"] = NTYPE_SWITCH_OFF;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 1);
ii++;
}
if (switchtype == STYPE_Media)
{
std::string idx = request::findValue(&req, "idx");
result = m_sql.safe_query("SELECT HardwareID FROM DeviceStatus WHERE (ID=='%q')", idx.c_str());
if (!result.empty())
{
std::string hdwid = result[0][0];
CDomoticzHardwareBase *pBaseHardware = reinterpret_cast<CDomoticzHardwareBase*>(m_mainworker.GetHardware(atoi(hdwid.c_str())));
if (pBaseHardware != NULL) {
_eHardwareTypes type = pBaseHardware->HwdType;
root["result"][ii]["val"] = NTYPE_PAUSED;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PAUSED, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PAUSED, 1);
ii++;
if (type == HTYPE_Kodi) {
root["result"][ii]["val"] = NTYPE_AUDIO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AUDIO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AUDIO, 1);
ii++;
root["result"][ii]["val"] = NTYPE_VIDEO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_VIDEO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_VIDEO, 1);
ii++;
root["result"][ii]["val"] = NTYPE_PHOTO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PHOTO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PHOTO, 1);
ii++;
}
if (type == HTYPE_LogitechMediaServer) {
root["result"][ii]["val"] = NTYPE_PLAYING;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PLAYING, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PLAYING, 1);
ii++;
root["result"][ii]["val"] = NTYPE_STOPPED;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_STOPPED, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_STOPPED, 1);
ii++;
}
if (type == HTYPE_HEOS) {
root["result"][ii]["val"] = NTYPE_PLAYING;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PLAYING, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PLAYING, 1);
ii++;
root["result"][ii]["val"] = NTYPE_STOPPED;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_STOPPED, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_STOPPED, 1);
ii++;
}
}
}
}
}
if (
(
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
(dType == pTypeEvohomeZone) ||
(dType == pTypeEvohomeWater) ||
(dType == pTypeThermostat1) ||
(dType == pTypeRego6XXTemp) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))
) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp))
)
{
root["result"][ii]["val"] = NTYPE_TEMPERATURE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 1);
ii++;
}
if (
(dType == pTypeHUM) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO)
)
{
root["result"][ii]["val"] = NTYPE_HUMIDITY;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_HUMIDITY, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_HUMIDITY, 1);
ii++;
}
if (
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO)
)
{
root["result"][ii]["val"] = NTYPE_DEWPOINT;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_DEWPOINT, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_DEWPOINT, 1);
ii++;
}
if (dType == pTypeRAIN)
{
root["result"][ii]["val"] = NTYPE_RAIN;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_RAIN, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_RAIN, 1);
ii++;
}
if (dType == pTypeWIND)
{
root["result"][ii]["val"] = NTYPE_WIND;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_WIND, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_WIND, 1);
ii++;
}
if (dType == pTypeUV)
{
root["result"][ii]["val"] = NTYPE_UV;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_UV, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_UV, 1);
ii++;
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeBARO) ||
(dType == pTypeTEMP_BARO)
)
{
root["result"][ii]["val"] = NTYPE_BARO;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_BARO, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_BARO, 1);
ii++;
}
if (
((dType == pTypeRFXMeter) && (dSubType == sTypeRFXMeterCount)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental)) ||
(dType == pTypeYouLess) ||
((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))
)
{
if ((switchtype == MTYPE_ENERGY) || (switchtype == MTYPE_ENERGY_GENERATED))
{
root["result"][ii]["val"] = NTYPE_TODAYENERGY;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 1);
}
else if (switchtype == MTYPE_GAS)
{
root["result"][ii]["val"] = NTYPE_TODAYGAS;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYGAS, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYGAS, 1);
}
else if (switchtype == MTYPE_COUNTER)
{
root["result"][ii]["val"] = NTYPE_TODAYCOUNTER;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYCOUNTER, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYCOUNTER, 1);
}
else
{
//water (same as gas)
root["result"][ii]["val"] = NTYPE_TODAYGAS;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYGAS, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYGAS, 1);
}
ii++;
}
if (dType == pTypeYouLess)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeAirQuality)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
else if ((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness)))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeVisibility))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeDistance))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypePressure))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeLux)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeWEIGHT)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypeUsage)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (
(dType == pTypeENERGY) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if (dType == pTypePOWER)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeCURRENT) && (dSubType == sTypeELEC1))
{
root["result"][ii]["val"] = NTYPE_AMPERE1;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE1, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE1, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE2;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE2, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE2, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE3;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE3, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE3, 1);
ii++;
}
if ((dType == pTypeCURRENTENERGY) && (dSubType == sTypeELEC4))
{
root["result"][ii]["val"] = NTYPE_AMPERE1;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE1, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE1, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE2;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE2, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE2, 1);
ii++;
root["result"][ii]["val"] = NTYPE_AMPERE3;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_AMPERE3, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_AMPERE3, 1);
ii++;
}
if (dType == pTypeP1Power)
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
root["result"][ii]["val"] = NTYPE_TODAYENERGY;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYENERGY, 1);
ii++;
}
if (dType == pTypeP1Gas)
{
root["result"][ii]["val"] = NTYPE_TODAYGAS;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TODAYGAS, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TODAYGAS, 1);
ii++;
}
if ((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint))
{
root["result"][ii]["val"] = NTYPE_TEMPERATURE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_TEMPERATURE, 1);
ii++;
}
if (dType == pTypeEvohomeZone)
{
root["result"][ii]["val"] = NTYPE_TEMPERATURE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SETPOINT, 0); //FIXME NTYPE_SETPOINT implementation?
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SETPOINT, 1);
ii++;
}
if ((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypePercentage))
{
root["result"][ii]["val"] = NTYPE_PERCENTAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_PERCENTAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_PERCENTAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeWaterflow))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeCustom))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeFan))
{
root["result"][ii]["val"] = NTYPE_RPM;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_RPM, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_RPM, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeAlert))
{
root["result"][ii]["val"] = NTYPE_USAGE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_USAGE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_USAGE, 1);
ii++;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeZWaveAlarm))
{
root["result"][ii]["val"] = NTYPE_VALUE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_VALUE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_VALUE, 1);
ii++;
}
if ((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))
{
root["result"][ii]["val"] = NTYPE_SWITCH_ON;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_ON, 1);
ii++;
root["result"][ii]["val"] = NTYPE_SWITCH_OFF;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_SWITCH_OFF, 1);
ii++;
}
if (!IsLightOrSwitch(dType, dSubType))
{
root["result"][ii]["val"] = NTYPE_LASTUPDATE;
root["result"][ii]["text"] = Notification_Type_Desc(NTYPE_LASTUPDATE, 0);
root["result"][ii]["ptag"] = Notification_Type_Desc(NTYPE_LASTUPDATE, 1);
ii++;
}
}
else if (cparam == "addnotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string stype = request::findValue(&req, "ttype");
std::string swhen = request::findValue(&req, "twhen");
std::string svalue = request::findValue(&req, "tvalue");
std::string scustommessage = request::findValue(&req, "tmsg");
std::string sactivesystems = request::findValue(&req, "tsystems");
std::string spriority = request::findValue(&req, "tpriority");
std::string ssendalways = request::findValue(&req, "tsendalways");
std::string srecovery = (request::findValue(&req, "trecovery") == "true") ? "1" : "0";
if ((stype.empty()) || (swhen.empty()) || (svalue.empty()) || (spriority.empty()) || (ssendalways.empty()) || (srecovery.empty()))
return;
_eNotificationTypes ntype = (_eNotificationTypes)atoi(stype.c_str());
std::string ttype = Notification_Type_Desc(ntype, 1);
if (
(ntype == NTYPE_SWITCH_ON) ||
(ntype == NTYPE_SWITCH_OFF) ||
(ntype == NTYPE_DEWPOINT)
)
{
if ((ntype == NTYPE_SWITCH_ON) && (swhen == "2")) { // '='
unsigned char twhen = '=';
sprintf(szTmp, "%s;%c;%s", ttype.c_str(), twhen, svalue.c_str());
}
else
strcpy(szTmp, ttype.c_str());
}
else
{
std::string twhen;
if (swhen == "0")
twhen = ">";
else if (swhen == "1")
twhen = ">=";
else if (swhen == "2")
twhen = "=";
else if (swhen == "3")
twhen = "!=";
else if (swhen == "4")
twhen = "<=";
else
twhen = "<";
sprintf(szTmp, "%s;%s;%s;%s", ttype.c_str(), twhen.c_str(), svalue.c_str(), srecovery.c_str());
}
int priority = atoi(spriority.c_str());
bool bOK = m_notifications.AddNotification(idx, szTmp, scustommessage, sactivesystems, priority, (ssendalways == "true") ? true : false);
if (bOK) {
root["status"] = "OK";
root["title"] = "AddNotification";
}
}
else if (cparam == "updatenotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string devidx = request::findValue(&req, "devidx");
if ((idx.empty()) || (devidx.empty()))
return;
std::string stype = request::findValue(&req, "ttype");
std::string swhen = request::findValue(&req, "twhen");
std::string svalue = request::findValue(&req, "tvalue");
std::string scustommessage = request::findValue(&req, "tmsg");
std::string sactivesystems = request::findValue(&req, "tsystems");
std::string spriority = request::findValue(&req, "tpriority");
std::string ssendalways = request::findValue(&req, "tsendalways");
std::string srecovery = (request::findValue(&req, "trecovery") == "true") ? "1" : "0";
if ((stype.empty()) || (swhen.empty()) || (svalue.empty()) || (spriority.empty()) || (ssendalways.empty()) || srecovery.empty())
return;
root["status"] = "OK";
root["title"] = "UpdateNotification";
std::string recoverymsg;
if ((srecovery == "1") && (m_notifications.CustomRecoveryMessage(strtoull(idx.c_str(), NULL, 0), recoverymsg, true)))
{
scustommessage.append(";;");
scustommessage.append(recoverymsg);
}
//delete old record
m_notifications.RemoveNotification(idx);
_eNotificationTypes ntype = (_eNotificationTypes)atoi(stype.c_str());
std::string ttype = Notification_Type_Desc(ntype, 1);
if (
(ntype == NTYPE_SWITCH_ON) ||
(ntype == NTYPE_SWITCH_OFF) ||
(ntype == NTYPE_DEWPOINT)
)
{
if ((ntype == NTYPE_SWITCH_ON) && (swhen == "2")) { // '='
unsigned char twhen = '=';
sprintf(szTmp, "%s;%c;%s", ttype.c_str(), twhen, svalue.c_str());
}
else
strcpy(szTmp, ttype.c_str());
}
else
{
std::string twhen;
if (swhen == "0")
twhen = ">";
else if (swhen == "1")
twhen = ">=";
else if (swhen == "2")
twhen = "=";
else if (swhen == "3")
twhen = "!=";
else if (swhen == "4")
twhen = "<=";
else
twhen = "<";
sprintf(szTmp, "%s;%s;%s;%s", ttype.c_str(), twhen.c_str(), svalue.c_str(), srecovery.c_str());
}
int priority = atoi(spriority.c_str());
m_notifications.AddNotification(devidx, szTmp, scustommessage, sactivesystems, priority, (ssendalways == "true") ? true : false);
}
else if (cparam == "deletenotification")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteNotification";
m_notifications.RemoveNotification(idx);
}
else if (cparam == "switchdeviceorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx1 = request::findValue(&req, "idx1");
std::string idx2 = request::findValue(&req, "idx2");
if ((idx1.empty()) || (idx2.empty()))
return;
std::string sroomid = request::findValue(&req, "roomid");
int roomid = atoi(sroomid.c_str());
std::string Order1, Order2;
if (roomid == 0)
{
//get device order 1
result = m_sql.safe_query("SELECT [Order] FROM DeviceStatus WHERE (ID == '%q')",
idx1.c_str());
if (result.empty())
return;
Order1 = result[0][0];
//get device order 2
result = m_sql.safe_query("SELECT [Order] FROM DeviceStatus WHERE (ID == '%q')",
idx2.c_str());
if (result.empty())
return;
Order2 = result[0][0];
root["status"] = "OK";
root["title"] = "SwitchDeviceOrder";
if (atoi(Order1.c_str()) < atoi(Order2.c_str()))
{
m_sql.safe_query(
"UPDATE DeviceStatus SET [Order] = [Order]+1 WHERE ([Order] >= '%q' AND [Order] < '%q')",
Order1.c_str(), Order2.c_str());
}
else
{
m_sql.safe_query(
"UPDATE DeviceStatus SET [Order] = [Order]-1 WHERE ([Order] > '%q' AND [Order] <= '%q')",
Order2.c_str(), Order1.c_str());
}
m_sql.safe_query("UPDATE DeviceStatus SET [Order] = '%q' WHERE (ID == '%q')",
Order1.c_str(), idx2.c_str());
}
else
{
//change order in a room
//get device order 1
result = m_sql.safe_query("SELECT [Order] FROM DeviceToPlansMap WHERE (DeviceRowID == '%q') AND (PlanID==%d)",
idx1.c_str(), roomid);
if (result.empty())
return;
Order1 = result[0][0];
//get device order 2
result = m_sql.safe_query("SELECT [Order] FROM DeviceToPlansMap WHERE (DeviceRowID == '%q') AND (PlanID==%d)",
idx2.c_str(), roomid);
if (result.empty())
return;
Order2 = result[0][0];
root["status"] = "OK";
root["title"] = "SwitchDeviceOrder";
if (atoi(Order1.c_str()) < atoi(Order2.c_str()))
{
m_sql.safe_query(
"UPDATE DeviceToPlansMap SET [Order] = [Order]+1 WHERE ([Order] >= '%q' AND [Order] < '%q') AND (PlanID==%d)",
Order1.c_str(), Order2.c_str(), roomid);
}
else
{
m_sql.safe_query(
"UPDATE DeviceToPlansMap SET [Order] = [Order]-1 WHERE ([Order] > '%q' AND [Order] <= '%q') AND (PlanID==%d)",
Order2.c_str(), Order1.c_str(), roomid);
}
m_sql.safe_query("UPDATE DeviceToPlansMap SET [Order] = '%q' WHERE (DeviceRowID == '%q') AND (PlanID==%d)",
Order1.c_str(), idx2.c_str(), roomid);
}
}
else if (cparam == "switchsceneorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx1 = request::findValue(&req, "idx1");
std::string idx2 = request::findValue(&req, "idx2");
if ((idx1.empty()) || (idx2.empty()))
return;
std::string Order1, Order2;
//get device order 1
result = m_sql.safe_query("SELECT [Order] FROM Scenes WHERE (ID == '%q')",
idx1.c_str());
if (result.empty())
return;
Order1 = result[0][0];
//get device order 2
result = m_sql.safe_query("SELECT [Order] FROM Scenes WHERE (ID == '%q')",
idx2.c_str());
if (result.empty())
return;
Order2 = result[0][0];
root["status"] = "OK";
root["title"] = "SwitchSceneOrder";
if (atoi(Order1.c_str()) < atoi(Order2.c_str()))
{
m_sql.safe_query(
"UPDATE Scenes SET [Order] = [Order]+1 WHERE ([Order] >= '%q' AND [Order] < '%q')",
Order1.c_str(), Order2.c_str());
}
else
{
m_sql.safe_query(
"UPDATE Scenes SET [Order] = [Order]-1 WHERE ([Order] > '%q' AND [Order] <= '%q')",
Order2.c_str(), Order1.c_str());
}
m_sql.safe_query("UPDATE Scenes SET [Order] = '%q' WHERE (ID == '%q')",
Order1.c_str(), idx2.c_str());
}
else if (cparam == "clearnotifications")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "ClearNotification";
m_notifications.RemoveDeviceNotifications(idx);
}
else if (cparam == "adduser")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string senabled = request::findValue(&req, "enabled");
std::string username = request::findValue(&req, "username");
std::string password = request::findValue(&req, "password");
std::string srights = request::findValue(&req, "rights");
std::string sRemoteSharing = request::findValue(&req, "RemoteSharing");
std::string sTabsEnabled = request::findValue(&req, "TabsEnabled");
if (
(senabled.empty()) ||
(username.empty()) ||
(password.empty()) ||
(srights.empty()) ||
(sRemoteSharing.empty()) ||
(sTabsEnabled.empty())
)
return;
int rights = atoi(srights.c_str());
if (rights != 2)
{
if (!FindAdminUser())
{
root["message"] = "Add a Admin user first! (Or enable Settings/Website Protection)";
return;
}
}
root["status"] = "OK";
root["title"] = "AddUser";
m_sql.safe_query(
"INSERT INTO Users (Active, Username, Password, Rights, RemoteSharing, TabsEnabled) VALUES (%d,'%q','%q','%d','%d','%d')",
(senabled == "true") ? 1 : 0,
base64_encode(username).c_str(),
password.c_str(),
rights,
(sRemoteSharing == "true") ? 1 : 0,
atoi(sTabsEnabled.c_str())
);
LoadUsers();
}
else if (cparam == "updateuser")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string senabled = request::findValue(&req, "enabled");
std::string username = request::findValue(&req, "username");
std::string password = request::findValue(&req, "password");
std::string srights = request::findValue(&req, "rights");
std::string sRemoteSharing = request::findValue(&req, "RemoteSharing");
std::string sTabsEnabled = request::findValue(&req, "TabsEnabled");
if (
(senabled.empty()) ||
(username.empty()) ||
(password.empty()) ||
(srights.empty()) ||
(sRemoteSharing.empty()) ||
(sTabsEnabled.empty())
)
return;
int rights = atoi(srights.c_str());
if (rights != 2)
{
if (!FindAdminUser())
{
root["message"] = "Add a Admin user first! (Or enable Settings/Website Protection)";
return;
}
}
std::string sHashedUsername = base64_encode(username);
// Invalid user's sessions if username or password has changed
std::string sOldUsername;
std::string sOldPassword;
result = m_sql.safe_query("SELECT Username, Password FROM Users WHERE (ID == '%q')", idx.c_str());
if (result.size() == 1)
{
sOldUsername = result[0][0];
sOldPassword = result[0][1];
}
if ((sHashedUsername != sOldUsername) || (password != sOldPassword))
RemoveUsersSessions(sOldUsername, session);
root["status"] = "OK";
root["title"] = "UpdateUser";
m_sql.safe_query(
"UPDATE Users SET Active=%d, Username='%q', Password='%q', Rights=%d, RemoteSharing=%d, TabsEnabled=%d WHERE (ID == '%q')",
(senabled == "true") ? 1 : 0,
sHashedUsername.c_str(),
password.c_str(),
rights,
(sRemoteSharing == "true") ? 1 : 0,
atoi(sTabsEnabled.c_str()),
idx.c_str()
);
LoadUsers();
}
else if (cparam == "deleteuser")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteUser";
// Remove user's sessions
result = m_sql.safe_query("SELECT Username FROM Users WHERE (ID == '%q')", idx.c_str());
if (result.size() == 1)
{
RemoveUsersSessions(result[0][0], session);
}
m_sql.safe_query("DELETE FROM Users WHERE (ID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SharedDevices WHERE (SharedUserID == '%q')", idx.c_str());
LoadUsers();
}
else if (cparam == "clearlightlog")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
//First get Device Type/SubType
result = m_sql.safe_query("SELECT Type, SubType FROM DeviceStatus WHERE (ID == '%q')",
idx.c_str());
if (result.empty())
return;
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
if (
(dType != pTypeLighting1) &&
(dType != pTypeLighting2) &&
(dType != pTypeLighting3) &&
(dType != pTypeLighting4) &&
(dType != pTypeLighting5) &&
(dType != pTypeLighting6) &&
(dType != pTypeFan) &&
(dType != pTypeColorSwitch) &&
(dType != pTypeSecurity1) &&
(dType != pTypeSecurity2) &&
(dType != pTypeEvohome) &&
(dType != pTypeEvohomeRelay) &&
(dType != pTypeCurtain) &&
(dType != pTypeBlinds) &&
(dType != pTypeRFY) &&
(dType != pTypeChime) &&
(dType != pTypeThermostat2) &&
(dType != pTypeThermostat3) &&
(dType != pTypeThermostat4) &&
(dType != pTypeRemote) &&
(dType != pTypeGeneralSwitch) &&
(dType != pTypeHomeConfort) &&
(dType != pTypeFS20) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeTextStatus))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeAlert)))
)
return; //no light device! we should not be here!
root["status"] = "OK";
root["title"] = "ClearLightLog";
result = m_sql.safe_query("DELETE FROM LightingLog WHERE (DeviceRowID=='%q')", idx.c_str());
}
else if (cparam == "clearscenelog")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "ClearSceneLog";
result = m_sql.safe_query("DELETE FROM SceneLog WHERE (SceneRowID=='%q')", idx.c_str());
}
else if (cparam == "learnsw")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
m_sql.AllowNewHardwareTimer(5);
m_sql.m_LastSwitchID = "";
bool bReceivedSwitch = false;
unsigned char cntr = 0;
while ((!bReceivedSwitch) && (cntr < 50)) //wait for max. 5 seconds
{
if (m_sql.m_LastSwitchID != "")
{
bReceivedSwitch = true;
break;
}
else
{
//sleep 100ms
sleep_milliseconds(100);
cntr++;
}
}
if (bReceivedSwitch)
{
//check if used
result = m_sql.safe_query("SELECT Name, Used, nValue FROM DeviceStatus WHERE (ID==%" PRIu64 ")",
m_sql.m_LastSwitchRowID);
if (!result.empty())
{
root["status"] = "OK";
root["title"] = "LearnSW";
root["ID"] = m_sql.m_LastSwitchID;
root["idx"] = m_sql.m_LastSwitchRowID;
root["Name"] = result[0][0];
root["Used"] = atoi(result[0][1].c_str());
root["Cmd"] = atoi(result[0][2].c_str());
}
}
} //learnsw
else if (cparam == "makefavorite")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string sisfavorite = request::findValue(&req, "isfavorite");
if ((idx.empty()) || (sisfavorite.empty()))
return;
int isfavorite = atoi(sisfavorite.c_str());
m_sql.safe_query("UPDATE DeviceStatus SET Favorite=%d WHERE (ID == '%q')",
isfavorite, idx.c_str());
root["status"] = "OK";
root["title"] = "MakeFavorite";
} //makefavorite
else if (cparam == "makescenefavorite")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string sisfavorite = request::findValue(&req, "isfavorite");
if ((idx.empty()) || (sisfavorite.empty()))
return;
int isfavorite = atoi(sisfavorite.c_str());
m_sql.safe_query("UPDATE Scenes SET Favorite=%d WHERE (ID == '%q')",
isfavorite, idx.c_str());
root["status"] = "OK";
root["title"] = "MakeSceneFavorite";
} //makescenefavorite
else if (cparam == "resetsecuritystatus")
{
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "switchcmd");
if ((idx.empty()) || (switchcmd.empty()))
return;
root["status"] = "OK";
root["title"] = "ResetSecurityStatus";
int nValue = -1;
// Change to generic *Security_Status_Desc lookup...
if (switchcmd == "Panic End") {
nValue = 7;
}
else if (switchcmd == "Normal") {
nValue = 0;
}
if (nValue >= 0)
{
m_sql.safe_query("UPDATE DeviceStatus SET nValue=%d WHERE (ID == '%q')",
nValue, idx.c_str());
root["status"] = "OK";
root["title"] = "SwitchLight";
}
}
else if (cparam == "verifypasscode")
{
std::string passcode = request::findValue(&req, "passcode");
if (passcode.empty())
return;
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode == rpassword)
{
root["title"] = "VerifyPasscode";
root["status"] = "OK";
return;
}
}
else if (cparam == "switchmodal")
{
int urights = 3;
if (bHaveUser)
{
int iUser = -1;
iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = (int)m_users[iUser].userrights;
_log.Log(LOG_STATUS, "User: %s initiated a modal command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "status");
std::string until = request::findValue(&req, "until");//optional until date / time as applicable
std::string action = request::findValue(&req, "action");//Run action or not (update status only)
std::string onlyonchange = request::findValue(&req, "ooc");//No update unless the value changed (check if updated)
//The on action is used to call a script to update the real device so we only want to use it when altering the status in the Domoticz Web Client
//If we're posting the status from the real device to domoticz we don't want to run the on action script ("action"!=1) to avoid loops and contention
//""... we only want to log a change (and trigger an event) when the status has actually changed ("ooc"==1) i.e. suppress non transient updates
if ((idx.empty()) || (switchcmd.empty()))
return;
std::string passcode = request::findValue(&req, "passcode");
if (passcode.size() > 0)
{
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode != rpassword)
{
root["title"] = "Modal";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
}
if (m_mainworker.SwitchModal(idx, switchcmd, action, onlyonchange, until) == true)//FIXME we need to return a status of already set / no update if ooc=="1" and no status update was performed
{
root["status"] = "OK";
root["title"] = "Modal";
}
}
else if (cparam == "switchlight")
{
if (session.rights < 1)
{
session.reply_status = reply::forbidden;
return; //Only user/admin allowed
}
std::string Username = "Admin";
if (!session.username.empty())
Username = session.username;
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "switchcmd");
std::string level = "-1";
if (switchcmd == "Set Level")
level = request::findValue(&req, "level");
std::string onlyonchange = request::findValue(&req, "ooc");//No update unless the value changed (check if updated)
_log.Debug(DEBUG_WEBSERVER, "WEBS switchlight idx:%s switchcmd:%s level:%s", idx.c_str(), switchcmd.c_str(), level.c_str());
std::string passcode = request::findValue(&req, "passcode");
if ((idx.empty()) || (switchcmd.empty()) || ((switchcmd == "Set Level") && (level.empty())) )
return;
result = m_sql.safe_query(
"SELECT [Protected],[Name] FROM DeviceStatus WHERE (ID = '%q')", idx.c_str());
if (result.empty())
{
//Switch not found!
return;
}
bool bIsProtected = atoi(result[0][0].c_str()) != 0;
std::string sSwitchName = result[0][1];
if (session.rights == 1)
{
if (!IsIdxForUser(&session, atoi(idx.c_str())))
{
_log.Log(LOG_ERROR, "User: %s initiated a Unauthorized switch command!", Username.c_str());
session.reply_status = reply::forbidden;
return;
}
}
if (bIsProtected)
{
if (passcode.empty())
{
//Switch is protected, but no passcode has been
root["title"] = "SwitchLight";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode != rpassword)
{
_log.Log(LOG_ERROR, "User: %s initiated a switch command (Wrong code!)", Username.c_str());
root["title"] = "SwitchLight";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
}
_log.Log(LOG_STATUS, "User: %s initiated a switch command (%s/%s/%s)", Username.c_str(), idx.c_str(), sSwitchName.c_str(), switchcmd.c_str());
root["title"] = "SwitchLight";
if (m_mainworker.SwitchLight(idx, switchcmd, level, "-1", onlyonchange, 0) == true)
{
root["status"] = "OK";
}
else
{
root["status"] = "ERROR";
root["message"] = "Error sending switch command, check device/hardware !";
}
} //(rtype=="switchlight")
else if (cparam == "switchscene")
{
if (session.rights < 1)
{
session.reply_status = reply::forbidden;
return; //Only user/admin allowed
}
std::string Username = "Admin";
if (!session.username.empty())
Username = session.username;
std::string idx = request::findValue(&req, "idx");
std::string switchcmd = request::findValue(&req, "switchcmd");
std::string passcode = request::findValue(&req, "passcode");
if ((idx.empty()) || (switchcmd.empty()))
return;
result = m_sql.safe_query(
"SELECT [Protected] FROM Scenes WHERE (ID = '%q')", idx.c_str());
if (result.empty())
{
//Scene/Group not found!
return;
}
bool bIsProtected = atoi(result[0][0].c_str()) != 0;
if (bIsProtected)
{
if (passcode.empty())
{
root["title"] = "SwitchScene";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
//Check if passcode is correct
passcode = GenerateMD5Hash(passcode);
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("ProtectionPassword", nValue, rpassword);
if (passcode != rpassword)
{
root["title"] = "SwitchScene";
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
_log.Log(LOG_ERROR, "User: %s initiated a scene/group command (Wrong code!)", Username.c_str());
return;
}
}
_log.Log(LOG_STATUS, "User: %s initiated a scene/group command", Username.c_str());
if (m_mainworker.SwitchScene(idx, switchcmd) == true)
{
root["status"] = "OK";
root["title"] = "SwitchScene";
}
} //(rtype=="switchscene")
else if (cparam == "getSunRiseSet") {
if (!m_mainworker.m_LastSunriseSet.empty())
{
std::vector<std::string> strarray;
StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray);
if (strarray.size() == 10)
{
struct tm loctime;
time_t now = mytime(NULL);
localtime_r(&now, &loctime);
//strftime(szTmp, 80, "%b %d %Y %X", &loctime);
strftime(szTmp, 80, "%Y-%m-%d %X", &loctime);
root["status"] = "OK";
root["title"] = "getSunRiseSet";
root["ServerTime"] = szTmp;
root["Sunrise"] = strarray[0];
root["Sunset"] = strarray[1];
root["SunAtSouth"] = strarray[2];
root["CivTwilightStart"] = strarray[3];
root["CivTwilightEnd"] = strarray[4];
root["NautTwilightStart"] = strarray[5];
root["NautTwilightEnd"] = strarray[6];
root["AstrTwilightStart"] = strarray[7];
root["AstrTwilightEnd"] = strarray[8];
root["DayLength"] = strarray[9];
}
}
}
else if (cparam == "getServerTime") {
struct tm loctime;
time_t now = mytime(NULL);
localtime_r(&now, &loctime);
//strftime(szTmp, 80, "%b %d %Y %X", &loctime);
strftime(szTmp, 80, "%Y-%m-%d %X", &loctime);
root["status"] = "OK";
root["title"] = "getServerTime";
root["ServerTime"] = szTmp;
}
else if (cparam == "getsecstatus")
{
root["status"] = "OK";
root["title"] = "GetSecStatus";
int secstatus = 0;
m_sql.GetPreferencesVar("SecStatus", secstatus);
root["secstatus"] = secstatus;
int secondelay = 30;
m_sql.GetPreferencesVar("SecOnDelay", secondelay);
root["secondelay"] = secondelay;
}
else if (cparam == "setsecstatus")
{
std::string ssecstatus = request::findValue(&req, "secstatus");
std::string seccode = request::findValue(&req, "seccode");
if ((ssecstatus.empty()) || (seccode.empty()))
{
root["message"] = "WRONG CODE";
return;
}
root["title"] = "SetSecStatus";
std::string rpassword;
int nValue = 1;
m_sql.GetPreferencesVar("SecPassword", nValue, rpassword);
if (seccode != rpassword)
{
root["status"] = "ERROR";
root["message"] = "WRONG CODE";
return;
}
root["status"] = "OK";
int iSecStatus = atoi(ssecstatus.c_str());
m_mainworker.UpdateDomoticzSecurityStatus(iSecStatus);
}
else if (cparam == "setcolbrightnessvalue")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
_tColor color;
std::string json = request::findValue(&req, "color");
std::string hex = request::findValue(&req, "hex");
std::string hue = request::findValue(&req, "hue");
std::string sat = request::findValue(&req, "sat");
std::string brightness = request::findValue(&req, "brightness");
std::string iswhite = request::findValue(&req, "iswhite");
int ival = 100;
float brightnessAdj = 1.0f;
if (!json.empty())
{
color = _tColor(json);
if (color.mode == ColorModeRGB)
{
// Normalize RGB to full brightness
float hsb[3];
int r, g, b;
rgb2hsb(color.r, color.g, color.b, hsb);
hsb2rgb(hsb[0]*360.0f, hsb[1], 1.0f, r, g, b, 255);
color.r = r;
color.g = g;
color.b = b;
brightnessAdj = hsb[2];
}
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue: json: %s, color: '%s', bri: '%s'", json.c_str(), color.toString().c_str(), brightness.c_str());
}
else if (!hex.empty())
{
uint64_t ihex = hexstrtoui64(hex);
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue: hex: '%s', ihex: %" PRIx64 ", bri: '%s', iswhite: '%s'", hex.c_str(), ihex, brightness.c_str(), iswhite.c_str());
uint8_t r = 0;
uint8_t g = 0;
uint8_t b = 0;
uint8_t cw = 0;
uint8_t ww = 0;
switch (hex.length())
{
case 6: //RGB
r = (uint8_t)((ihex & 0x0000FF0000) >> 16);
g = (uint8_t)((ihex & 0x000000FF00) >> 8);
b = (uint8_t)ihex & 0xFF;
float hsb[3];
int tr, tg, tb; // tmp of 'int' type so can be passed as references to hsb2rgb
rgb2hsb(r, g, b, hsb);
// Normalize RGB to full brightness
hsb2rgb(hsb[0]*360.0f, hsb[1], 1.0f, tr, tg, tb, 255);
r = tr;
g = tg;
b = tb;
brightnessAdj = hsb[2];
// Backwards compatibility: set iswhite for unsaturated colors
iswhite = (hsb[1] < (20.0 / 255.0)) ? "true" : "false";
color = _tColor(r, g, b, cw, ww, ColorModeRGB);
break;
case 8: //RGB_WW
r = (uint8_t)((ihex & 0x00FF000000) >> 24);
g = (uint8_t)((ihex & 0x0000FF0000) >> 16);
b = (uint8_t)((ihex & 0x000000FF00) >> 8);
ww = (uint8_t)ihex & 0xFF;
color = _tColor(r, g, b, cw, ww, ColorModeCustom);
break;
case 10: //RGB_CW_WW
r = (uint8_t)((ihex & 0xFF00000000) >> 32);
g = (uint8_t)((ihex & 0x00FF000000) >> 24);
b = (uint8_t)((ihex & 0x0000FF0000) >> 16);
cw = (uint8_t)((ihex & 0x000000FF00) >> 8);
ww = (uint8_t)ihex & 0xFF;
color = _tColor(r, g, b, cw, ww, ColorModeCustom);
break;
}
if (iswhite == "true") color.mode = ColorModeWhite;
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue: rgbww: %02x%02x%02x%02x%02x, color: '%s'", r, g, b, cw, ww, color.toString().c_str());
}
else if (!hue.empty())
{
int r, g, b;
//convert hue to RGB
float iHue = float(atof(hue.c_str()));
float iSat = 100.0f;
if (!sat.empty()) iSat = float(atof(sat.c_str()));
hsb2rgb(iHue, iSat/100.0f, 1.0f, r, g, b, 255);
color = _tColor(r, g, b, 0, 0, ColorModeRGB);
if (iswhite == "true") color.mode = ColorModeWhite;
//_log.Debug(DEBUG_WEBSERVER, "setcolbrightnessvalue2: hue: %f, rgb: %02x%02x%02x, color: '%s'", iHue, r, g, b, color.toString().c_str());
}
if (color.mode == ColorModeNone)
{
return;
}
if (!brightness.empty())
ival = atoi(brightness.c_str());
ival = int(ival * brightnessAdj);
ival = std::max(ival, 0);
ival = std::min(ival, 100);
_log.Log(LOG_STATUS, "setcolbrightnessvalue: ID: %" PRIx64 ", bri: %d, color: '%s'", ID, ival, color.toString().c_str());
m_mainworker.SwitchLight(ID, "Set Color", (unsigned char)ival, color, false, 0);
root["status"] = "OK";
root["title"] = "SetColBrightnessValue";
}
else if (cparam.find("setkelvinlevel") == 0)
{
root["status"] = "OK";
root["title"] = "Set Kelvin Level";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
std::string kelvin = request::findValue(&req, "kelvin");
double ival = atof(kelvin.c_str());
ival = std::max(ival, 0.0);
ival = std::min(ival, 100.0);
_tColor color = _tColor(round(ival*255.0f/100.0f), ColorModeTemp);
_log.Log(LOG_STATUS, "setkelvinlevel: t: %f, color: '%s'", ival, color.toString().c_str());
m_mainworker.SwitchLight(ID, "Set Color", -1, color, false, 0);
}
else if (cparam == "brightnessup")
{
root["status"] = "OK";
root["title"] = "Set brightness up!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Bright Up", 0, NoColor, false, 0);
}
else if (cparam == "brightnessdown")
{
root["status"] = "OK";
root["title"] = "Set brightness down!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Bright Down", 0, NoColor, false, 0);
}
else if (cparam == "discomode")
{
root["status"] = "OK";
root["title"] = "Set to last known disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Disco Mode", 0, NoColor, false, 0);
}
else if (cparam.find("discomodenum") == 0 && cparam != "discomode" && cparam.size() == 13)
{
root["status"] = "OK";
root["title"] = "Set to disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
char szTmp[40];
sprintf(szTmp, "Disco Mode %s", cparam.substr(12).c_str());
m_mainworker.SwitchLight(ID, szTmp, 0, NoColor, false, 0);
}
else if (cparam == "discoup")
{
root["status"] = "OK";
root["title"] = "Set to next disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Disco Up", 0, NoColor, false, 0);
}
else if (cparam == "discodown")
{
root["status"] = "OK";
root["title"] = "Set to previous disco mode!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Disco Down", 0, NoColor, false, 0);
}
else if (cparam == "speedup")
{
root["status"] = "OK";
root["title"] = "Set disco speed up!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Up", 0, NoColor, false, 0);
}
else if (cparam == "speeduplong")
{
root["status"] = "OK";
root["title"] = "Set speed long!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Up Long", 0, NoColor, false, 0);
}
else if (cparam == "speeddown")
{
root["status"] = "OK";
root["title"] = "Set disco speed down!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Down", 0, NoColor, false, 0);
}
else if (cparam == "speedmin")
{
root["status"] = "OK";
root["title"] = "Set disco speed minimal!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Minimal", 0, NoColor, false, 0);
}
else if (cparam == "speedmax")
{
root["status"] = "OK";
root["title"] = "Set disco speed maximal!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Speed Maximal", 0, NoColor, false, 0);
}
else if (cparam == "warmer")
{
root["status"] = "OK";
root["title"] = "Set Kelvin up!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Warmer", 0, NoColor, false, 0);
}
else if (cparam == "cooler")
{
root["status"] = "OK";
root["title"] = "Set Kelvin down!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Cooler", 0, NoColor, false, 0);
}
else if (cparam == "fulllight")
{
root["status"] = "OK";
root["title"] = "Set Full!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Set Full", 0, NoColor, false, 0);
}
else if (cparam == "nightlight")
{
root["status"] = "OK";
root["title"] = "Set to nightlight!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.SwitchLight(ID, "Set Night", 0, NoColor, false, 0);
}
else if (cparam == "whitelight")
{
root["status"] = "OK";
root["title"] = "Set to clear white!";
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
{
return;
}
uint64_t ID = std::strtoull(idx.c_str(), nullptr, 10);
//TODO: Change to color with mode=ColorModeWhite and level=100?
m_mainworker.SwitchLight(ID, "Set White", 0, NoColor, false, 0);
}
else if (cparam == "getfloorplanimages")
{
root["status"] = "OK";
root["title"] = "GetFloorplanImages";
bool bReturnUnused = atoi(request::findValue(&req, "unused").c_str()) != 0;
if (!bReturnUnused)
result = m_sql.safe_query("SELECT ID, Name, ScaleFactor FROM Floorplans ORDER BY [Name]");
else
result = m_sql.safe_query("SELECT ID, Name, ScaleFactor FROM Floorplans WHERE ID NOT IN(SELECT FloorplanID FROM Plans)");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["name"] = sd[1];
root["result"][ii]["scalefactor"] = sd[2];
ii++;
}
}
}
else if (cparam == "updatefloorplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string name = request::findValue(&req, "name");
std::string scalefactor = request::findValue(&req, "scalefactor");
if (
(name.empty())
||(scalefactor.empty())
)
return;
root["status"] = "OK";
root["title"] = "UpdateFloorplan";
m_sql.safe_query(
"UPDATE Floorplans SET Name='%q',ScaleFactor='%q' WHERE (ID == '%q')",
name.c_str(),
scalefactor.c_str(),
idx.c_str()
);
}
else if (cparam == "deletefloorplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteFloorplan";
m_sql.safe_query("UPDATE DeviceToPlansMap SET XOffset=0,YOffset=0 WHERE (PlanID IN (SELECT ID from Plans WHERE (FloorplanID == '%q')))", idx.c_str());
m_sql.safe_query("UPDATE Plans SET FloorplanID=0,Area='' WHERE (FloorplanID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM Floorplans WHERE (ID == '%q')", idx.c_str());
}
else if (cparam == "changefloorplanorder")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
std::string sway = request::findValue(&req, "way");
if (sway.empty())
return;
bool bGoUp = (sway == "0");
std::string aOrder, oID, oOrder;
result = m_sql.safe_query("SELECT [Order] FROM Floorplans WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
aOrder = result[0][0];
if (!bGoUp)
{
//Get next device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Floorplans WHERE ([Order]>'%q') ORDER BY [Order] ASC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
else
{
//Get previous device order
result = m_sql.safe_query("SELECT ID, [Order] FROM Floorplans WHERE ([Order]<'%q') ORDER BY [Order] DESC",
aOrder.c_str());
if (result.empty())
return;
oID = result[0][0];
oOrder = result[0][1];
}
//Swap them
root["status"] = "OK";
root["title"] = "ChangeFloorPlanOrder";
m_sql.safe_query("UPDATE Floorplans SET [Order] = '%q' WHERE (ID='%q')",
oOrder.c_str(), idx.c_str());
m_sql.safe_query("UPDATE Floorplans SET [Order] = '%q' WHERE (ID='%q')",
aOrder.c_str(), oID.c_str());
}
else if (cparam == "getunusedfloorplanplans")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "GetUnusedFloorplanPlans";
int ii = 0;
result = m_sql.safe_query("SELECT ID, Name FROM Plans WHERE (FloorplanID==0) ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["type"] = 0;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
ii++;
}
}
}
else if (cparam == "getfloorplanplans")
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetFloorplanPlans";
int ii = 0;
result = m_sql.safe_query("SELECT ID, Name, Area FROM Plans WHERE (FloorplanID=='%q') ORDER BY Name",
idx.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Area"] = sd[2];
ii++;
}
}
}
else if (cparam == "addfloorplanplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string planidx = request::findValue(&req, "planidx");
if (
(idx.empty()) ||
(planidx.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddFloorplanPlan";
m_sql.safe_query(
"UPDATE Plans SET FloorplanID='%q' WHERE (ID == '%q')",
idx.c_str(),
planidx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Plan '%s' added to floorplan '%s'.", planidx.c_str(), idx.c_str());
}
else if (cparam == "updatefloorplanplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string planidx = request::findValue(&req, "planidx");
std::string planarea = request::findValue(&req, "area");
if (planidx.empty())
return;
root["status"] = "OK";
root["title"] = "UpdateFloorplanPlan";
m_sql.safe_query(
"UPDATE Plans SET Area='%q' WHERE (ID == '%q')",
planarea.c_str(),
planidx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Plan '%s' floor area updated to '%s'.", planidx.c_str(), planarea.c_str());
}
else if (cparam == "deletefloorplanplan")
{
if (session.rights < 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteFloorplanPlan";
m_sql.safe_query(
"UPDATE DeviceToPlansMap SET XOffset=0,YOffset=0 WHERE (PlanID == '%q')",
idx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Device coordinates reset for plan '%s'.", idx.c_str());
m_sql.safe_query(
"UPDATE Plans SET FloorplanID=0,Area='' WHERE (ID == '%q')",
idx.c_str()
);
_log.Log(LOG_STATUS, "(Floorplan) Plan '%s' floorplan data reset.", idx.c_str());
}
}
void CWebServer::DisplaySwitchTypesCombo(std::string & content_part)
{
char szTmp[200];
std::map<std::string, int> _switchtypes;
for (int ii = 0; ii < STYPE_END; ii++)
{
_switchtypes[Switch_Type_Desc((_eSwitchType)ii)] = ii;
}
//return a sorted list
for (const auto & itt : _switchtypes)
{
sprintf(szTmp, "<option value=\"%d\">%s</option>\n", itt.second, itt.first.c_str());
content_part += szTmp;
}
}
void CWebServer::DisplayMeterTypesCombo(std::string & content_part)
{
char szTmp[200];
for (int ii = 0; ii < MTYPE_END; ii++)
{
sprintf(szTmp, "<option value=\"%d\">%s</option>\n", ii, Meter_Type_Desc((_eMeterType)ii));
content_part += szTmp;
}
}
void CWebServer::DisplayLanguageCombo(std::string & content_part)
{
//return a sorted list
std::map<std::string, std::string> _ltypes;
char szTmp[200];
int ii = 0;
while (guiLanguage[ii].szShort != NULL)
{
_ltypes[guiLanguage[ii].szLong] = guiLanguage[ii].szShort;
ii++;
}
for (const auto & itt : _ltypes)
{
sprintf(szTmp, "<option value=\"%s\">%s</option>\n", itt.second.c_str(), itt.first.c_str());
content_part += szTmp;
}
}
void CWebServer::DisplayTimerTypesCombo(std::string & content_part)
{
char szTmp[200];
for (int ii = 0; ii < TTYPE_END; ii++)
{
sprintf(szTmp, "<option data-i18n=\"%s\" value=\"%d\">%s</option>\n", Timer_Type_Desc(ii), ii, Timer_Type_Desc(ii));
content_part += szTmp;
}
}
void CWebServer::LoadUsers()
{
ClearUserPasswords();
std::string WebUserName, WebPassword;
int nValue = 0;
if (m_sql.GetPreferencesVar("WebUserName", nValue, WebUserName))
{
if (m_sql.GetPreferencesVar("WebPassword", nValue, WebPassword))
{
if ((WebUserName != "") && (WebPassword != ""))
{
WebUserName = base64_decode(WebUserName);
//WebPassword = WebPassword;
AddUser(10000, WebUserName, WebPassword, URIGHTS_ADMIN, 0xFFFF);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Active, Username, Password, Rights, TabsEnabled FROM Users");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int bIsActive = static_cast<int>(atoi(sd[1].c_str()));
if (bIsActive)
{
unsigned long ID = (unsigned long)atol(sd[0].c_str());
std::string username = base64_decode(sd[2]);
std::string password = sd[3];
_eUserRights rights = (_eUserRights)atoi(sd[4].c_str());
int activetabs = atoi(sd[5].c_str());
AddUser(ID, username, password, rights, activetabs);
}
}
}
}
}
}
m_mainworker.LoadSharedUsers();
}
void CWebServer::AddUser(const unsigned long ID, const std::string &username, const std::string &password, const int userrights, const int activetabs)
{
std::vector<std::vector<std::string> > result = m_sql.safe_query("SELECT COUNT(*) FROM SharedDevices WHERE (SharedUserID == '%d')", ID);
if (result.empty())
return;
_tWebUserPassword wtmp;
wtmp.ID = ID;
wtmp.Username = username;
wtmp.Password = password;
wtmp.userrights = (_eUserRights)userrights;
wtmp.ActiveTabs = activetabs;
wtmp.TotSensors = atoi(result[0][0].c_str());
m_users.push_back(wtmp);
m_pWebEm->AddUserPassword(ID, username, password, (_eUserRights)userrights, activetabs);
}
void CWebServer::ClearUserPasswords()
{
m_users.clear();
m_pWebEm->ClearUserPasswords();
}
int CWebServer::FindUser(const char* szUserName)
{
int iUser = 0;
for (const auto & itt : m_users)
{
if (itt.Username == szUserName)
return iUser;
iUser++;
}
return -1;
}
bool CWebServer::FindAdminUser()
{
for (const auto & itt : m_users)
{
if (itt.userrights == URIGHTS_ADMIN)
return true;
}
return false;
}
void CWebServer::PostSettings(WebEmSession & session, const request& req, std::string & redirect_uri)
{
redirect_uri = "/index.html";
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string Latitude = request::findValue(&req, "Latitude");
std::string Longitude = request::findValue(&req, "Longitude");
if ((Latitude != "") && (Longitude != ""))
{
std::string LatLong = Latitude + ";" + Longitude;
m_sql.UpdatePreferencesVar("Location", LatLong.c_str());
m_mainworker.GetSunSettings();
}
m_notifications.ConfigFromGetvars(req, true);
std::string DashboardType = request::findValue(&req, "DashboardType");
m_sql.UpdatePreferencesVar("DashboardType", atoi(DashboardType.c_str()));
std::string MobileType = request::findValue(&req, "MobileType");
m_sql.UpdatePreferencesVar("MobileType", atoi(MobileType.c_str()));
int nUnit = atoi(request::findValue(&req, "WindUnit").c_str());
m_sql.UpdatePreferencesVar("WindUnit", nUnit);
m_sql.m_windunit = (_eWindUnit)nUnit;
nUnit = atoi(request::findValue(&req, "TempUnit").c_str());
m_sql.UpdatePreferencesVar("TempUnit", nUnit);
m_sql.m_tempunit = (_eTempUnit)nUnit;
nUnit = atoi(request::findValue(&req, "WeightUnit").c_str());
m_sql.UpdatePreferencesVar("WeightUnit", nUnit);
m_sql.m_weightunit = (_eWeightUnit)nUnit;
m_sql.SetUnitsAndScale();
std::string AuthenticationMethod = request::findValue(&req, "AuthenticationMethod");
_eAuthenticationMethod amethod = (_eAuthenticationMethod)atoi(AuthenticationMethod.c_str());
m_sql.UpdatePreferencesVar("AuthenticationMethod", static_cast<int>(amethod));
m_pWebEm->SetAuthenticationMethod(amethod);
std::string ReleaseChannel = request::findValue(&req, "ReleaseChannel");
m_sql.UpdatePreferencesVar("ReleaseChannel", atoi(ReleaseChannel.c_str()));
std::string LightHistoryDays = request::findValue(&req, "LightHistoryDays");
m_sql.UpdatePreferencesVar("LightHistoryDays", atoi(LightHistoryDays.c_str()));
std::string s5MinuteHistoryDays = request::findValue(&req, "ShortLogDays");
m_sql.UpdatePreferencesVar("5MinuteHistoryDays", atoi(s5MinuteHistoryDays.c_str()));
int iShortLogInterval = atoi(request::findValue(&req, "ShortLogInterval").c_str());
if (iShortLogInterval < 1)
iShortLogInterval = 5;
m_sql.UpdatePreferencesVar("ShortLogInterval", iShortLogInterval);
m_sql.m_ShortLogInterval = iShortLogInterval;
std::string sElectricVoltage = request::findValue(&req, "ElectricVoltage");
m_sql.UpdatePreferencesVar("ElectricVoltage", atoi(sElectricVoltage.c_str()));
std::string sCM113DisplayType = request::findValue(&req, "CM113DisplayType");
m_sql.UpdatePreferencesVar("CM113DisplayType", atoi(sCM113DisplayType.c_str()));
std::string WebUserName = base64_encode(CURLEncode::URLDecode(request::findValue(&req, "WebUserName")));
std::string WebPassword = CURLEncode::URLDecode(request::findValue(&req, "WebPassword"));
//Get old username/password
std::string sOldWebLogin;
std::string sOldWebPassword;
m_sql.GetPreferencesVar("WebUserName", sOldWebLogin);
m_sql.GetPreferencesVar("WebPassword", sOldWebPassword);
bool bHaveAdminUserPasswordChange = false;
if ((WebUserName == sOldWebLogin) && (WebPassword.empty()))
{
//All is OK, no changes
}
else if (WebUserName.empty() || WebPassword.empty())
{
//If no Admin User/Password is specified, we clear them
if ((!sOldWebLogin.empty()) || (!sOldWebPassword.empty()))
bHaveAdminUserPasswordChange = true;
WebUserName = "";
WebPassword = "";
}
else {
if ((WebUserName != sOldWebLogin) || (WebPassword != sOldWebPassword))
{
bHaveAdminUserPasswordChange = true;
}
}
// Invalid sessions of WebUser when the username or password has been changed
if (bHaveAdminUserPasswordChange)
{
RemoveUsersSessions(sOldWebLogin, session);
m_sql.UpdatePreferencesVar("WebUserName", WebUserName.c_str());
m_sql.UpdatePreferencesVar("WebPassword", WebPassword.c_str());
}
std::string WebLocalNetworks = CURLEncode::URLDecode(request::findValue(&req, "WebLocalNetworks"));
std::string WebRemoteProxyIPs = CURLEncode::URLDecode(request::findValue(&req, "WebRemoteProxyIPs"));
m_sql.UpdatePreferencesVar("WebLocalNetworks", WebLocalNetworks.c_str());
m_sql.UpdatePreferencesVar("WebRemoteProxyIPs", WebRemoteProxyIPs.c_str());
LoadUsers();
m_pWebEm->ClearLocalNetworks();
std::vector<std::string> strarray;
StringSplit(WebLocalNetworks, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddLocalNetworks(itt);
//add local hostname
m_pWebEm->AddLocalNetworks("");
m_pWebEm->ClearRemoteProxyIPs();
strarray.clear();
StringSplit(WebRemoteProxyIPs, ";", strarray);
for (const auto & itt : strarray)
m_pWebEm->AddRemoteProxyIPs(itt);
if (session.username.empty())
{
//Local network could be changed so lets for a check here
session.rights = -1;
}
std::string SecPassword = request::findValue(&req, "SecPassword");
SecPassword = CURLEncode::URLDecode(SecPassword);
if (SecPassword.size() != 32)
{
SecPassword = GenerateMD5Hash(SecPassword);
}
m_sql.UpdatePreferencesVar("SecPassword", SecPassword.c_str());
std::string ProtectionPassword = request::findValue(&req, "ProtectionPassword");
ProtectionPassword = CURLEncode::URLDecode(ProtectionPassword);
if (ProtectionPassword.size() != 32)
{
ProtectionPassword = GenerateMD5Hash(ProtectionPassword);
}
m_sql.UpdatePreferencesVar("ProtectionPassword", ProtectionPassword.c_str());
int EnergyDivider = atoi(request::findValue(&req, "EnergyDivider").c_str());
int GasDivider = atoi(request::findValue(&req, "GasDivider").c_str());
int WaterDivider = atoi(request::findValue(&req, "WaterDivider").c_str());
if (EnergyDivider < 1)
EnergyDivider = 1000;
if (GasDivider < 1)
GasDivider = 100;
if (WaterDivider < 1)
WaterDivider = 100;
m_sql.UpdatePreferencesVar("MeterDividerEnergy", EnergyDivider);
m_sql.UpdatePreferencesVar("MeterDividerGas", GasDivider);
m_sql.UpdatePreferencesVar("MeterDividerWater", WaterDivider);
std::string scheckforupdates = request::findValue(&req, "checkforupdates");
m_sql.UpdatePreferencesVar("UseAutoUpdate", (scheckforupdates == "on" ? 1 : 0));
std::string senableautobackup = request::findValue(&req, "enableautobackup");
m_sql.UpdatePreferencesVar("UseAutoBackup", (senableautobackup == "on" ? 1 : 0));
float CostEnergy = static_cast<float>(atof(request::findValue(&req, "CostEnergy").c_str()));
float CostEnergyT2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyT2").c_str()));
float CostEnergyR1 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR1").c_str()));
float CostEnergyR2 = static_cast<float>(atof(request::findValue(&req, "CostEnergyR2").c_str()));
float CostGas = static_cast<float>(atof(request::findValue(&req, "CostGas").c_str()));
float CostWater = static_cast<float>(atof(request::findValue(&req, "CostWater").c_str()));
m_sql.UpdatePreferencesVar("CostEnergy", int(CostEnergy*10000.0f));
m_sql.UpdatePreferencesVar("CostEnergyT2", int(CostEnergyT2*10000.0f));
m_sql.UpdatePreferencesVar("CostEnergyR1", int(CostEnergyR1*10000.0f));
m_sql.UpdatePreferencesVar("CostEnergyR2", int(CostEnergyR2*10000.0f));
m_sql.UpdatePreferencesVar("CostGas", int(CostGas*10000.0f));
m_sql.UpdatePreferencesVar("CostWater", int(CostWater*10000.0f));
int rnOldvalue = 0;
int rnvalue = 0;
m_sql.GetPreferencesVar("ActiveTimerPlan", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "ActiveTimerPlan").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("ActiveTimerPlan", rnvalue);
m_sql.m_ActiveTimerPlan = rnvalue;
m_mainworker.m_scheduler.ReloadSchedules();
}
m_sql.UpdatePreferencesVar("DoorbellCommand", atoi(request::findValue(&req, "DoorbellCommand").c_str()));
m_sql.UpdatePreferencesVar("SmartMeterType", atoi(request::findValue(&req, "SmartMeterType").c_str()));
std::string EnableTabFloorplans = request::findValue(&req, "EnableTabFloorplans");
m_sql.UpdatePreferencesVar("EnableTabFloorplans", (EnableTabFloorplans == "on" ? 1 : 0));
std::string EnableTabLights = request::findValue(&req, "EnableTabLights");
m_sql.UpdatePreferencesVar("EnableTabLights", (EnableTabLights == "on" ? 1 : 0));
std::string EnableTabTemp = request::findValue(&req, "EnableTabTemp");
m_sql.UpdatePreferencesVar("EnableTabTemp", (EnableTabTemp == "on" ? 1 : 0));
std::string EnableTabWeather = request::findValue(&req, "EnableTabWeather");
m_sql.UpdatePreferencesVar("EnableTabWeather", (EnableTabWeather == "on" ? 1 : 0));
std::string EnableTabUtility = request::findValue(&req, "EnableTabUtility");
m_sql.UpdatePreferencesVar("EnableTabUtility", (EnableTabUtility == "on" ? 1 : 0));
std::string EnableTabScenes = request::findValue(&req, "EnableTabScenes");
m_sql.UpdatePreferencesVar("EnableTabScenes", (EnableTabScenes == "on" ? 1 : 0));
std::string EnableTabCustom = request::findValue(&req, "EnableTabCustom");
m_sql.UpdatePreferencesVar("EnableTabCustom", (EnableTabCustom == "on" ? 1 : 0));
m_sql.GetPreferencesVar("NotificationSensorInterval", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "NotificationSensorInterval").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("NotificationSensorInterval", rnvalue);
m_notifications.ReloadNotifications();
}
m_sql.GetPreferencesVar("NotificationSwitchInterval", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "NotificationSwitchInterval").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("NotificationSwitchInterval", rnvalue);
m_notifications.ReloadNotifications();
}
std::string RaspCamParams = request::findValue(&req, "RaspCamParams");
if (RaspCamParams != "")
{
if (IsArgumentSecure(RaspCamParams))
m_sql.UpdatePreferencesVar("RaspCamParams", RaspCamParams.c_str());
}
std::string UVCParams = request::findValue(&req, "UVCParams");
if (UVCParams != "")
{
if (IsArgumentSecure(UVCParams))
m_sql.UpdatePreferencesVar("UVCParams", UVCParams.c_str());
}
std::string EnableNewHardware = request::findValue(&req, "AcceptNewHardware");
int iEnableNewHardware = (EnableNewHardware == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("AcceptNewHardware", iEnableNewHardware);
m_sql.m_bAcceptNewHardware = (iEnableNewHardware == 1);
std::string HideDisabledHardwareSensors = request::findValue(&req, "HideDisabledHardwareSensors");
int iHideDisabledHardwareSensors = (HideDisabledHardwareSensors == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("HideDisabledHardwareSensors", iHideDisabledHardwareSensors);
std::string ShowUpdateEffect = request::findValue(&req, "ShowUpdateEffect");
int iShowUpdateEffect = (ShowUpdateEffect == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("ShowUpdateEffect", iShowUpdateEffect);
std::string SendErrorsAsNotification = request::findValue(&req, "SendErrorsAsNotification");
int iSendErrorsAsNotification = (SendErrorsAsNotification == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("SendErrorsAsNotification", iSendErrorsAsNotification);
_log.ForwardErrorsToNotificationSystem(iSendErrorsAsNotification != 0);
std::string DegreeDaysBaseTemperature = request::findValue(&req, "DegreeDaysBaseTemperature");
m_sql.UpdatePreferencesVar("DegreeDaysBaseTemperature", DegreeDaysBaseTemperature);
rnOldvalue = 0;
m_sql.GetPreferencesVar("EnableEventScriptSystem", rnOldvalue);
std::string EnableEventScriptSystem = request::findValue(&req, "EnableEventScriptSystem");
int iEnableEventScriptSystem = (EnableEventScriptSystem == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("EnableEventScriptSystem", iEnableEventScriptSystem);
m_sql.m_bEnableEventSystem = (iEnableEventScriptSystem == 1);
if (iEnableEventScriptSystem != rnOldvalue)
{
m_mainworker.m_eventsystem.SetEnabled(m_sql.m_bEnableEventSystem);
m_mainworker.m_eventsystem.StartEventSystem();
}
rnOldvalue = 0;
m_sql.GetPreferencesVar("DisableDzVentsSystem", rnOldvalue);
std::string DisableDzVentsSystem = request::findValue(&req, "DisableDzVentsSystem");
int iDisableDzVentsSystem = (DisableDzVentsSystem == "on" ? 0 : 1);
m_sql.UpdatePreferencesVar("DisableDzVentsSystem", iDisableDzVentsSystem);
m_sql.m_bDisableDzVentsSystem = (iDisableDzVentsSystem == 1);
if (m_sql.m_bEnableEventSystem && !iDisableDzVentsSystem && iDisableDzVentsSystem != rnOldvalue)
{
m_mainworker.m_eventsystem.LoadEvents();
m_mainworker.m_eventsystem.GetCurrentStates();
}
m_sql.UpdatePreferencesVar("DzVentsLogLevel", atoi(request::findValue(&req, "DzVentsLogLevel").c_str()));
std::string LogEventScriptTrigger = request::findValue(&req, "LogEventScriptTrigger");
m_sql.m_bLogEventScriptTrigger = (LogEventScriptTrigger == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("LogEventScriptTrigger", m_sql.m_bLogEventScriptTrigger);
std::string EnableWidgetOrdering = request::findValue(&req, "AllowWidgetOrdering");
int iEnableAllowWidgetOrdering = (EnableWidgetOrdering == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("AllowWidgetOrdering", iEnableAllowWidgetOrdering);
m_sql.m_bAllowWidgetOrdering = (iEnableAllowWidgetOrdering == 1);
rnOldvalue = 0;
m_sql.GetPreferencesVar("RemoteSharedPort", rnOldvalue);
m_sql.UpdatePreferencesVar("RemoteSharedPort", atoi(request::findValue(&req, "RemoteSharedPort").c_str()));
rnvalue = 0;
m_sql.GetPreferencesVar("RemoteSharedPort", rnvalue);
if (rnvalue != rnOldvalue)
{
m_mainworker.m_sharedserver.StopServer();
if (rnvalue != 0)
{
char szPort[100];
sprintf(szPort, "%d", rnvalue);
m_mainworker.m_sharedserver.StartServer("::", szPort);
m_mainworker.LoadSharedUsers();
}
}
m_sql.UpdatePreferencesVar("Language", request::findValue(&req, "Language").c_str());
std::string SelectedTheme = request::findValue(&req, "Themes");
m_sql.UpdatePreferencesVar("WebTheme", SelectedTheme.c_str());
m_pWebEm->SetWebTheme(SelectedTheme);
std::string Title = request::findValue(&req, "Title").c_str();
m_sql.UpdatePreferencesVar("Title", (Title.empty()) ? "Domoticz" : Title);
m_sql.GetPreferencesVar("RandomTimerFrame", rnOldvalue);
rnvalue = atoi(request::findValue(&req, "RandomSpread").c_str());
if (rnOldvalue != rnvalue)
{
m_sql.UpdatePreferencesVar("RandomTimerFrame", rnvalue);
m_mainworker.m_scheduler.ReloadSchedules();
}
m_sql.UpdatePreferencesVar("SecOnDelay", atoi(request::findValue(&req, "SecOnDelay").c_str()));
int sensortimeout = atoi(request::findValue(&req, "SensorTimeout").c_str());
if (sensortimeout < 10)
sensortimeout = 10;
m_sql.UpdatePreferencesVar("SensorTimeout", sensortimeout);
int batterylowlevel = atoi(request::findValue(&req, "BatterLowLevel").c_str());
if (batterylowlevel > 100)
batterylowlevel = 100;
m_sql.GetPreferencesVar("BatteryLowNotification", rnOldvalue);
m_sql.UpdatePreferencesVar("BatteryLowNotification", batterylowlevel);
if ((rnOldvalue != batterylowlevel) && (batterylowlevel != 0))
m_sql.CheckBatteryLow();
int nValue = 0;
nValue = atoi(request::findValue(&req, "FloorplanPopupDelay").c_str());
m_sql.UpdatePreferencesVar("FloorplanPopupDelay", nValue);
std::string FloorplanFullscreenMode = request::findValue(&req, "FloorplanFullscreenMode");
m_sql.UpdatePreferencesVar("FloorplanFullscreenMode", (FloorplanFullscreenMode == "on" ? 1 : 0));
std::string FloorplanAnimateZoom = request::findValue(&req, "FloorplanAnimateZoom");
m_sql.UpdatePreferencesVar("FloorplanAnimateZoom", (FloorplanAnimateZoom == "on" ? 1 : 0));
std::string FloorplanShowSensorValues = request::findValue(&req, "FloorplanShowSensorValues");
m_sql.UpdatePreferencesVar("FloorplanShowSensorValues", (FloorplanShowSensorValues == "on" ? 1 : 0));
std::string FloorplanShowSwitchValues = request::findValue(&req, "FloorplanShowSwitchValues");
m_sql.UpdatePreferencesVar("FloorplanShowSwitchValues", (FloorplanShowSwitchValues == "on" ? 1 : 0));
std::string FloorplanShowSceneNames = request::findValue(&req, "FloorplanShowSceneNames");
m_sql.UpdatePreferencesVar("FloorplanShowSceneNames", (FloorplanShowSceneNames == "on" ? 1 : 0));
m_sql.UpdatePreferencesVar("FloorplanRoomColour", CURLEncode::URLDecode(request::findValue(&req, "FloorplanRoomColour").c_str()).c_str());
m_sql.UpdatePreferencesVar("FloorplanActiveOpacity", atoi(request::findValue(&req, "FloorplanActiveOpacity").c_str()));
m_sql.UpdatePreferencesVar("FloorplanInactiveOpacity", atoi(request::findValue(&req, "FloorplanInactiveOpacity").c_str()));
#ifndef NOCLOUD
std::string md_userid, md_password, pf_userid, pf_password;
int md_subsystems, pf_subsystems;
m_sql.GetPreferencesVar("MyDomoticzUserId", pf_userid);
m_sql.GetPreferencesVar("MyDomoticzPassword", pf_password);
m_sql.GetPreferencesVar("MyDomoticzSubsystems", pf_subsystems);
md_userid = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzUserId"));
md_password = CURLEncode::URLDecode(request::findValue(&req, "MyDomoticzPassword"));
md_subsystems = (request::findValue(&req, "SubsystemHttp").empty() ? 0 : 1) + (request::findValue(&req, "SubsystemShared").empty() ? 0 : 2) + (request::findValue(&req, "SubsystemApps").empty() ? 0 : 4);
if (md_userid != pf_userid || md_password != pf_password || md_subsystems != pf_subsystems) {
m_sql.UpdatePreferencesVar("MyDomoticzUserId", md_userid);
if (md_password != pf_password) {
md_password = base64_encode(md_password);
m_sql.UpdatePreferencesVar("MyDomoticzPassword", md_password);
}
m_sql.UpdatePreferencesVar("MyDomoticzSubsystems", md_subsystems);
m_webservers.RestartProxy();
}
#endif
m_sql.UpdatePreferencesVar("OneWireSensorPollPeriod", atoi(request::findValue(&req, "OneWireSensorPollPeriod").c_str()));
m_sql.UpdatePreferencesVar("OneWireSwitchPollPeriod", atoi(request::findValue(&req, "OneWireSwitchPollPeriod").c_str()));
std::string IFTTTEnabled = request::findValue(&req, "IFTTTEnabled");
int iIFTTTEnabled = (IFTTTEnabled == "on" ? 1 : 0);
m_sql.UpdatePreferencesVar("IFTTTEnabled", iIFTTTEnabled);
std::string szKey = request::findValue(&req, "IFTTTAPI");
m_sql.UpdatePreferencesVar("IFTTTAPI", base64_encode(szKey));
m_notifications.LoadConfig();
#ifdef ENABLE_PYTHON
//Signal plugins to update Settings dictionary
PluginLoadConfig();
#endif
}
void CWebServer::RestoreDatabase(WebEmSession & session, const request& req, std::string & redirect_uri)
{
redirect_uri = "/index.html";
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string dbasefile = request::findValue(&req, "dbasefile");
if (dbasefile.empty()) {
return;
}
m_mainworker.StopDomoticzHardware();
m_sql.RestoreDatabase(dbasefile);
m_mainworker.AddAllDomoticzHardware();
}
struct _tHardwareListInt {
std::string Name;
int HardwareTypeVal;
std::string HardwareType;
bool Enabled;
std::string Mode1; // Used to flag DimmerType as relative for some old LimitLessLight type bulbs
std::string Mode2; // Used to flag DimmerType as relative for some old LimitLessLight type bulbs
} tHardwareList;
void CWebServer::GetJSonDevices(
Json::Value &root,
const std::string &rused,
const std::string &rfilter,
const std::string &order,
const std::string &rowid,
const std::string &planID,
const std::string &floorID,
const bool bDisplayHidden,
const bool bDisplayDisabled,
const bool bFetchFavorites,
const time_t LastUpdate,
const std::string &username,
const std::string &hardwareid)
{
std::vector<std::vector<std::string> > result;
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
struct tm tLastUpdate;
localtime_r(&now, &tLastUpdate);
const time_t iLastUpdate = LastUpdate - 1;
int SensorTimeOut = 60;
m_sql.GetPreferencesVar("SensorTimeout", SensorTimeOut);
//Get All Hardware ID's/Names, need them later
std::map<int, _tHardwareListInt> _hardwareNames;
result = m_sql.safe_query("SELECT ID, Name, Enabled, Type, Mode1, Mode2 FROM Hardware");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
_tHardwareListInt tlist;
int ID = atoi(sd[0].c_str());
tlist.Name = sd[1];
tlist.Enabled = (atoi(sd[2].c_str()) != 0);
tlist.HardwareTypeVal = atoi(sd[3].c_str());
#ifndef ENABLE_PYTHON
tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal);
#else
if (tlist.HardwareTypeVal != HTYPE_PythonPlugin)
{
tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal);
}
else
{
tlist.HardwareType = PluginHardwareDesc(ID);
}
#endif
tlist.Mode1 = sd[4];
tlist.Mode2 = sd[5];
_hardwareNames[ID] = tlist;
}
}
root["ActTime"] = static_cast<int>(now);
char szTmp[300];
if (!m_mainworker.m_LastSunriseSet.empty())
{
std::vector<std::string> strarray;
StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray);
if (strarray.size() == 10)
{
//strftime(szTmp, 80, "%b %d %Y %X", &tm1);
strftime(szTmp, 80, "%Y-%m-%d %X", &tm1);
root["ServerTime"] = szTmp;
root["Sunrise"] = strarray[0];
root["Sunset"] = strarray[1];
root["SunAtSouth"] = strarray[2];
root["CivTwilightStart"] = strarray[3];
root["CivTwilightEnd"] = strarray[4];
root["NautTwilightStart"] = strarray[5];
root["NautTwilightEnd"] = strarray[6];
root["AstrTwilightStart"] = strarray[7];
root["AstrTwilightEnd"] = strarray[8];
root["DayLength"] = strarray[9];
}
}
char szOrderBy[50];
std::string szQuery;
bool isAlpha = true;
const std::string orderBy = order.c_str();
for (size_t i = 0; i < orderBy.size(); i++) {
if (!isalpha(orderBy[i])) {
isAlpha = false;
}
}
if (order.empty() || (!isAlpha)) {
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
} else {
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
unsigned char tempsign = m_sql.m_tempsign[0];
bool bHaveUser = false;
int iUser = -1;
unsigned int totUserDevices = 0;
bool bShowScenes = true;
bHaveUser = (username != "");
if (bHaveUser)
{
iUser = FindUser(username.c_str());
if (iUser != -1)
{
_eUserRights urights = m_users[iUser].userrights;
if (urights != URIGHTS_ADMIN)
{
result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == %lu)", m_users[iUser].ID);
totUserDevices = (unsigned int)result.size();
bShowScenes = (m_users[iUser].ActiveTabs&(1 << 1)) != 0;
}
}
}
std::set<std::string> _HiddenDevices;
bool bAllowDeviceToBeHidden = false;
int ii = 0;
if (rfilter == "all")
{
if (
(bShowScenes) &&
((rused == "all") || (rused == "true"))
)
{
//add scenes
if (rowid != "")
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A"
" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)"
" WHERE (A.ID=='%q')",
rowid.c_str());
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A, DeviceToPlansMap as B WHERE (B.PlanID=='%q')"
" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==1) ORDER BY B.[Order]",
planID.c_str());
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A, DeviceToPlansMap as B, Plans as C"
" WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID) AND (B.DeviceRowID==a.ID)"
" AND (B.DevSceneType==1) ORDER BY B.[Order]",
floorID.c_str());
else {
szQuery = (
"SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType,"
" A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description"
" FROM Scenes as A"
" LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)"
" ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), order.c_str());
}
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
unsigned char favorite = atoi(sd[4].c_str());
//Check if we only want favorite devices
if ((bFetchFavorites) && (!favorite))
continue;
std::string sLastUpdate = sd[3];
if (iLastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= iLastUpdate)
continue;
}
int nValue = atoi(sd[2].c_str());
unsigned char scenetype = atoi(sd[5].c_str());
int iProtected = atoi(sd[6].c_str());
std::string sSceneName = sd[1];
if (!bDisplayHidden && sSceneName[0] == '$')
{
continue;
}
if (scenetype == 0)
{
root["result"][ii]["Type"] = "Scene";
root["result"][ii]["TypeImg"] = "scene";
}
else
{
root["result"][ii]["Type"] = "Group";
root["result"][ii]["TypeImg"] = "group";
}
// has this scene/group already been seen, now with different plan?
// assume results are ordered such that same device is adjacent
// if the idx and the Type are equal (type to prevent matching against Scene with same idx)
std::string thisIdx = sd[0];
if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) {
std::string typeOfThisOne = root["result"][ii]["Type"].asString();
if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) {
root["result"][ii - 1]["PlanIDs"].append(atoi(sd[9].c_str()));
continue;
}
}
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sSceneName;
root["result"][ii]["Description"] = sd[10];
root["result"][ii]["Favorite"] = favorite;
root["result"][ii]["Protected"] = (iProtected != 0);
root["result"][ii]["LastUpdate"] = sLastUpdate;
root["result"][ii]["PlanID"] = sd[9].c_str();
Json::Value jsonArray;
jsonArray.append(atoi(sd[9].c_str()));
root["result"][ii]["PlanIDs"] = jsonArray;
if (nValue == 0)
root["result"][ii]["Status"] = "Off";
else if (nValue == 1)
root["result"][ii]["Status"] = "On";
else
root["result"][ii]["Status"] = "Mixed";
root["result"][ii]["Data"] = root["result"][ii]["Status"];
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(1, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
root["result"][ii]["XOffset"] = atoi(sd[7].c_str());
root["result"][ii]["YOffset"] = atoi(sd[8].c_str());
ii++;
}
}
}
}
char szData[250];
if (totUserDevices == 0)
{
//All
if (rowid != "")
{
//_log.Log(LOG_STATUS, "Getting device with id: %s", rowid.c_str());
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used, A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus A LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) "
"WHERE (A.ID=='%q')",
rowid.c_str());
}
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, B.XOffset, B.YOffset,"
" B.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, DeviceToPlansMap as B "
"WHERE (B.PlanID=='%q') AND (B.DeviceRowID==a.ID)"
" AND (B.DevSceneType==0) ORDER BY B.[Order]",
planID.c_str());
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, B.XOffset, B.YOffset,"
" B.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, DeviceToPlansMap as B,"
" Plans as C "
"WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID)"
" AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"ORDER BY B.[Order]",
floorID.c_str());
else {
if (!bDisplayHidden)
{
//Build a list of Hidden Devices
result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')");
if (!result.empty())
{
std::string pID = result[0][0];
result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)",
pID.c_str());
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator ittP;
for (ittP = result.begin(); ittP != result.end(); ++ittP)
{
_HiddenDevices.insert(ittP[0][0]);
}
}
}
bAllowDeviceToBeHidden = true;
}
if (order.empty() || (!isAlpha))
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
else
{
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
//_log.Log(LOG_STATUS, "Getting all devices: order by %s ", szOrderBy);
if (hardwareid != "") {
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B "
"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"WHERE (A.HardwareID == %q) "
"ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), hardwareid.c_str(), order.c_str());
}
else {
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType,"
" A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue,"
" A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID,"
" A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2,"
" A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B "
"ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) "
"ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), order.c_str());
}
}
}
else
{
if (iUser == -1) {
return;
}
//Specific devices
if (rowid != "")
{
//_log.Log(LOG_STATUS, "Getting device with id: %s for user %lu", rowid.c_str(), m_users[iUser].ID);
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, 0 as XOffset,"
" 0 as YOffset, 0 as PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B "
"WHERE (B.DeviceRowID==a.ID)"
" AND (B.SharedUserID==%lu) AND (A.ID=='%q')",
m_users[iUser].ID, rowid.c_str());
}
else if ((planID != "") && (planID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, C.XOffset,"
" C.YOffset, C.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B,"
" DeviceToPlansMap as C "
"WHERE (C.PlanID=='%q') AND (C.DeviceRowID==a.ID)"
" AND (B.DeviceRowID==a.ID) "
"AND (B.SharedUserID==%lu) ORDER BY C.[Order]",
planID.c_str(), m_users[iUser].ID);
else if ((floorID != "") && (floorID != "0"))
result = m_sql.safe_query(
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, C.XOffset, C.YOffset,"
" C.PlanID, A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B,"
" DeviceToPlansMap as C, Plans as D "
"WHERE (D.FloorplanID=='%q') AND (D.ID==C.PlanID)"
" AND (C.DeviceRowID==a.ID) AND (B.DeviceRowID==a.ID)"
" AND (B.SharedUserID==%lu) ORDER BY C.[Order]",
floorID.c_str(), m_users[iUser].ID);
else {
if (!bDisplayHidden)
{
//Build a list of Hidden Devices
result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')");
if (!result.empty())
{
std::string pID = result[0][0];
result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)",
pID.c_str());
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator ittP;
for (ittP = result.begin(); ittP != result.end(); ++ittP)
{
_HiddenDevices.insert(ittP[0][0]);
}
}
}
bAllowDeviceToBeHidden = true;
}
if (order.empty() || (!isAlpha))
{
strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC");
}
else
{
sprintf(szOrderBy, "A.[Order],A.%%s ASC");
}
// _log.Log(LOG_STATUS, "Getting all devices for user %lu", m_users[iUser].ID);
szQuery = (
"SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,"
" A.Type, A.SubType, A.SignalLevel, A.BatteryLevel,"
" A.nValue, A.sValue, A.LastUpdate, A.Favorite,"
" A.SwitchType, A.HardwareID, A.AddjValue,"
" A.AddjMulti, A.AddjValue2, A.AddjMulti2,"
" A.LastLevel, A.CustomImage, A.StrParam1,"
" A.StrParam2, A.Protected, IFNULL(C.XOffset,0),"
" IFNULL(C.YOffset,0), IFNULL(C.PlanID,0), A.Description,"
" A.Options, A.Color "
"FROM DeviceStatus as A, SharedDevices as B "
"LEFT OUTER JOIN DeviceToPlansMap as C ON (C.DeviceRowID==A.ID)"
"WHERE (B.DeviceRowID==A.ID)"
" AND (B.SharedUserID==%lu) ORDER BY ");
szQuery += szOrderBy;
result = m_sql.safe_query(szQuery.c_str(), m_users[iUser].ID, order.c_str());
}
}
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
unsigned char favorite = atoi(sd[12].c_str());
if ((planID != "") && (planID != "0"))
favorite = 1;
//Check if we only want favorite devices
if ((bFetchFavorites) && (!favorite))
continue;
std::string sDeviceName = sd[3];
if (!bDisplayHidden)
{
if (_HiddenDevices.find(sd[0]) != _HiddenDevices.end())
continue;
if (sDeviceName[0] == '$')
{
if (bAllowDeviceToBeHidden)
continue;
if (planID.size() > 0)
sDeviceName = sDeviceName.substr(1);
}
}
int hardwareID = atoi(sd[14].c_str());
std::map<int, _tHardwareListInt>::iterator hItt = _hardwareNames.find(hardwareID);
if (hItt != _hardwareNames.end())
{
//ignore sensors where the hardware is disabled
if ((!bDisplayDisabled) && (!(*hItt).second.Enabled))
continue;
}
unsigned int dType = atoi(sd[5].c_str());
unsigned int dSubType = atoi(sd[6].c_str());
unsigned int used = atoi(sd[4].c_str());
int nValue = atoi(sd[9].c_str());
std::string sValue = sd[10];
std::string sLastUpdate = sd[11];
if (sLastUpdate.size() > 19)
sLastUpdate = sLastUpdate.substr(0, 19);
if (iLastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= iLastUpdate)
continue;
}
_eSwitchType switchtype = (_eSwitchType)atoi(sd[13].c_str());
_eMeterType metertype = (_eMeterType)switchtype;
double AddjValue = atof(sd[15].c_str());
double AddjMulti = atof(sd[16].c_str());
double AddjValue2 = atof(sd[17].c_str());
double AddjMulti2 = atof(sd[18].c_str());
int LastLevel = atoi(sd[19].c_str());
int CustomImage = atoi(sd[20].c_str());
std::string strParam1 = base64_encode(sd[21]);
std::string strParam2 = base64_encode(sd[22]);
int iProtected = atoi(sd[23].c_str());
std::string Description = sd[27];
std::string sOptions = sd[28];
std::string sColor = sd[29];
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sOptions);
struct tm ntime;
time_t checktime;
ParseSQLdatetime(checktime, ntime, sLastUpdate, tm1.tm_isdst);
bool bHaveTimeout = (now - checktime >= SensorTimeOut * 60);
if (dType == pTypeTEMP_RAIN)
continue; //dont want you for now
if ((rused == "true") && (!used))
continue;
if (
(rused == "false") &&
(used)
)
continue;
if (rfilter != "")
{
if (rfilter == "light")
{
if (
(dType != pTypeLighting1) &&
(dType != pTypeLighting2) &&
(dType != pTypeLighting3) &&
(dType != pTypeLighting4) &&
(dType != pTypeLighting5) &&
(dType != pTypeLighting6) &&
(dType != pTypeFan) &&
(dType != pTypeColorSwitch) &&
(dType != pTypeSecurity1) &&
(dType != pTypeSecurity2) &&
(dType != pTypeEvohome) &&
(dType != pTypeEvohomeRelay) &&
(dType != pTypeCurtain) &&
(dType != pTypeBlinds) &&
(dType != pTypeRFY) &&
(dType != pTypeChime) &&
(dType != pTypeThermostat2) &&
(dType != pTypeThermostat3) &&
(dType != pTypeThermostat4) &&
(dType != pTypeRemote) &&
(dType != pTypeGeneralSwitch) &&
(dType != pTypeHomeConfort) &&
(dType != pTypeChime) &&
(dType != pTypeFS20) &&
(!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)))
)
continue;
}
else if (rfilter == "temp")
{
if (
(dType != pTypeTEMP) &&
(dType != pTypeHUM) &&
(dType != pTypeTEMP_HUM) &&
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO) &&
(dType != pTypeEvohomeZone) &&
(dType != pTypeEvohomeWater) &&
(!((dType == pTypeWIND) && (dSubType == sTypeWIND4))) &&
(!((dType == pTypeUV) && (dSubType == sTypeUV3))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp))) &&
(dType != pTypeThermostat1) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))) &&
(dType != pTypeRego6XXTemp)
)
continue;
}
else if (rfilter == "weather")
{
if (
(dType != pTypeWIND) &&
(dType != pTypeRAIN) &&
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO) &&
(dType != pTypeUV) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeVisibility))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeBaro))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)))
)
continue;
}
else if (rfilter == "utility")
{
if (
(dType != pTypeRFXMeter) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD))) &&
(!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeVoltage))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCurrent))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeTextStatus))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeAlert))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypePressure))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypePercentage))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeWaterflow))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCustom))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeFan))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveClock))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatMode))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatFanMode))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeDistance))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))) &&
(!((dType == pTypeGeneral) && (dSubType == sTypeKwh))) &&
(dType != pTypeCURRENT) &&
(dType != pTypeCURRENTENERGY) &&
(dType != pTypeENERGY) &&
(dType != pTypePOWER) &&
(dType != pTypeP1Power) &&
(dType != pTypeP1Gas) &&
(dType != pTypeYouLess) &&
(dType != pTypeAirQuality) &&
(dType != pTypeLux) &&
(dType != pTypeUsage) &&
(!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))) &&
(!((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint))) &&
(dType != pTypeWEIGHT) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwares)))
)
continue;
}
else if (rfilter == "wind")
{
if (
(dType != pTypeWIND)
)
continue;
}
else if (rfilter == "rain")
{
if (
(dType != pTypeRAIN)
)
continue;
}
else if (rfilter == "uv")
{
if (
(dType != pTypeUV)
)
continue;
}
else if (rfilter == "baro")
{
if (
(dType != pTypeTEMP_HUM_BARO) &&
(dType != pTypeTEMP_BARO)
)
continue;
}
else if (rfilter == "zwavealarms")
{
if (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveAlarm)))
continue;
}
}
// has this device already been seen, now with different plan?
// assume results are ordered such that same device is adjacent
// if the idx and the Type are equal (type to prevent matching against Scene with same idx)
std::string thisIdx = sd[0];
int devIdx = atoi(thisIdx.c_str());
if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) {
std::string typeOfThisOne = RFX_Type_Desc(dType, 1);
if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) {
root["result"][ii - 1]["PlanIDs"].append(atoi(sd[26].c_str()));
continue;
}
}
root["result"][ii]["HardwareID"] = hardwareID;
if (_hardwareNames.find(hardwareID) == _hardwareNames.end())
{
root["result"][ii]["HardwareName"] = "Unknown?";
root["result"][ii]["HardwareTypeVal"] = 0;
root["result"][ii]["HardwareType"] = "Unknown?";
}
else
{
root["result"][ii]["HardwareName"] = _hardwareNames[hardwareID].Name;
root["result"][ii]["HardwareTypeVal"] = _hardwareNames[hardwareID].HardwareTypeVal;
root["result"][ii]["HardwareType"] = _hardwareNames[hardwareID].HardwareType;
}
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Protected"] = (iProtected != 0);
CDomoticzHardwareBase *pHardware = m_mainworker.GetHardware(hardwareID);
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_SolarEdgeAPI)
{
int seSensorTimeOut = 60 * 24 * 60;
bHaveTimeout = (now - checktime >= seSensorTimeOut * 60);
}
else if (pHardware->HwdType == HTYPE_Wunderground)
{
CWunderground *pWHardware = reinterpret_cast<CWunderground *>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_DarkSky)
{
CDarkSky *pWHardware = reinterpret_cast<CDarkSky*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_AccuWeather)
{
CAccuWeather *pWHardware = reinterpret_cast<CAccuWeather*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
else if (pHardware->HwdType == HTYPE_OpenWeatherMap)
{
COpenWeatherMap *pWHardware = reinterpret_cast<COpenWeatherMap*>(pHardware);
std::string forecast_url = pWHardware->GetForecastURL();
if (forecast_url != "")
{
root["result"][ii]["forecast_url"] = base64_encode(forecast_url);
}
}
}
if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_PythonPlugin))
{
// Device ID special formatting should not be applied to Python plugins
root["result"][ii]["ID"] = sd[1];
}
else
{
sprintf(szData, "%04X", (unsigned int)atoi(sd[1].c_str()));
if (
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_BARO) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeBARO) ||
(dType == pTypeHUM) ||
(dType == pTypeWIND) ||
(dType == pTypeRAIN) ||
(dType == pTypeUV) ||
(dType == pTypeCURRENT) ||
(dType == pTypeCURRENTENERGY) ||
(dType == pTypeENERGY) ||
(dType == pTypeRFXMeter) ||
(dType == pTypeAirQuality) ||
(dType == pTypeRFXSensor) ||
(dType == pTypeP1Power) ||
(dType == pTypeP1Gas)
)
{
root["result"][ii]["ID"] = szData;
}
else
{
root["result"][ii]["ID"] = sd[1];
}
}
root["result"][ii]["Unit"] = atoi(sd[2].c_str());
root["result"][ii]["Type"] = RFX_Type_Desc(dType, 1);
root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(dType, dSubType);
root["result"][ii]["TypeImg"] = RFX_Type_Desc(dType, 2);
root["result"][ii]["Name"] = sDeviceName;
root["result"][ii]["Description"] = Description;
root["result"][ii]["Used"] = used;
root["result"][ii]["Favorite"] = favorite;
int iSignalLevel = atoi(sd[7].c_str());
if (iSignalLevel < 12)
root["result"][ii]["SignalLevel"] = iSignalLevel;
else
root["result"][ii]["SignalLevel"] = "-";
root["result"][ii]["BatteryLevel"] = atoi(sd[8].c_str());
root["result"][ii]["LastUpdate"] = sLastUpdate;
root["result"][ii]["CustomImage"] = CustomImage;
root["result"][ii]["XOffset"] = sd[24].c_str();
root["result"][ii]["YOffset"] = sd[25].c_str();
root["result"][ii]["PlanID"] = sd[26].c_str();
Json::Value jsonArray;
jsonArray.append(atoi(sd[26].c_str()));
root["result"][ii]["PlanIDs"] = jsonArray;
root["result"][ii]["AddjValue"] = AddjValue;
root["result"][ii]["AddjMulti"] = AddjMulti;
root["result"][ii]["AddjValue2"] = AddjValue2;
root["result"][ii]["AddjMulti2"] = AddjMulti2;
std::stringstream s_data;
s_data << int(nValue) << ", " << sValue;
root["result"][ii]["Data"] = s_data.str();
root["result"][ii]["Notifications"] = (m_notifications.HasNotifications(sd[0]) == true) ? "true" : "false";
root["result"][ii]["ShowNotifications"] = true;
bool bHasTimers = false;
if (
(dType == pTypeLighting1) ||
(dType == pTypeLighting2) ||
(dType == pTypeLighting3) ||
(dType == pTypeLighting4) ||
(dType == pTypeLighting5) ||
(dType == pTypeLighting6) ||
(dType == pTypeFan) ||
(dType == pTypeColorSwitch) ||
(dType == pTypeCurtain) ||
(dType == pTypeBlinds) ||
(dType == pTypeRFY) ||
(dType == pTypeChime) ||
(dType == pTypeThermostat2) ||
(dType == pTypeThermostat3) ||
(dType == pTypeThermostat4) ||
(dType == pTypeRemote) ||
(dType == pTypeGeneralSwitch) ||
(dType == pTypeHomeConfort) ||
(dType == pTypeFS20) ||
((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)) ||
((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))
)
{
//add light details
bHasTimers = m_sql.HasTimers(sd[0]);
bHaveTimeout = false;
#ifdef WITH_OPENZWAVE
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
int nodeID = (ID & 0x0000FF00) >> 8;
bHaveTimeout = pZWave->HasNodeFailed(nodeID);
}
}
#endif
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
std::string IconFile = "Light";
std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage);
if (ittIcon != m_custom_light_icons_lookup.end())
{
IconFile = m_custom_light_icons[ittIcon->second].RootFile;
}
root["result"][ii]["Image"] = IconFile;
if (switchtype == STYPE_Dimmer)
{
root["result"][ii]["Level"] = LastLevel;
int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel);
root["result"][ii]["LevelInt"] = iLevel;
if ((dType == pTypeColorSwitch) ||
(dType == pTypeLighting5 && dSubType == sTypeTRC02) ||
(dType == pTypeLighting5 && dSubType == sTypeTRC02_2) ||
(dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02) ||
(dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02_2))
{
_tColor color(sColor);
std::string jsonColor = color.toJSONString();
root["result"][ii]["Color"] = jsonColor;
llevel = LastLevel;
if (lstatus == "Set Level" || lstatus == "Set Color")
{
sprintf(szTmp, "Set Level: %d %%", LastLevel);
root["result"][ii]["Status"] = szTmp;
}
}
}
else
{
root["result"][ii]["Level"] = llevel;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
}
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
std::string DimmerType = "none";
if (switchtype == STYPE_Dimmer)
{
DimmerType = "abs";
if (_hardwareNames.find(hardwareID) != _hardwareNames.end())
{
// Milight V4/V5 bridges do not support absolute dimming for RGB or CW_WW lights
if (_hardwareNames[hardwareID].HardwareTypeVal == HTYPE_LimitlessLights &&
atoi(_hardwareNames[hardwareID].Mode2.c_str()) != CLimitLess::LBTYPE_V6 &&
(atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_RGB ||
atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_White ||
atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_CW_WW))
{
DimmerType = "rel";
}
}
}
root["result"][ii]["DimmerType"] = DimmerType;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(switchtype);
root["result"][ii]["SwitchTypeVal"] = switchtype;
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
bool bIsSubDevice = false;
std::vector<std::vector<std::string> > resultSD;
resultSD = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q')",
sd[0].c_str());
bIsSubDevice = (resultSD.size() > 0);
root["result"][ii]["IsSubDevice"] = bIsSubDevice;
if (switchtype == STYPE_Doorbell)
{
root["result"][ii]["TypeImg"] = "doorbell";
root["result"][ii]["Status"] = "";//"Pressed";
}
else if (switchtype == STYPE_DoorContact)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Open" : "Closed";
if (bIsOn) {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_DoorLock)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Locked" : "Unlocked";
if (bIsOn) {
lstatus = "Locked";
}
else {
lstatus = "Unlocked";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_DoorLockInverted)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Door";
}
root["result"][ii]["TypeImg"] = "door";
bool bIsOn = IsLightSwitchOn(lstatus);
root["result"][ii]["InternalState"] = (bIsOn == true) ? "Unlocked" : "Locked";
if (bIsOn) {
lstatus = "Unlocked";
}
else {
lstatus = "Locked";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_PushOn)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Push";
}
root["result"][ii]["TypeImg"] = "push";
root["result"][ii]["Status"] = "";
root["result"][ii]["InternalState"] = (IsLightSwitchOn(lstatus) == true) ? "On" : "Off";
}
else if (switchtype == STYPE_PushOff)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Push";
}
root["result"][ii]["TypeImg"] = "push";
root["result"][ii]["Status"] = "";
root["result"][ii]["TypeImg"] = "pushoff";
}
else if (switchtype == STYPE_X10Siren)
root["result"][ii]["TypeImg"] = "siren";
else if (switchtype == STYPE_SMOKEDETECTOR)
{
root["result"][ii]["TypeImg"] = "smoke";
root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR);
}
else if (switchtype == STYPE_Contact)
{
if (CustomImage == 0)
{
root["result"][ii]["Image"] = "Contact";
}
root["result"][ii]["TypeImg"] = "contact";
bool bIsOn = IsLightSwitchOn(lstatus);
if (bIsOn) {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_Media)
{
if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_LogitechMediaServer))
root["result"][ii]["TypeImg"] = "LogitechMediaServer";
else
root["result"][ii]["TypeImg"] = "Media";
root["result"][ii]["Status"] = Media_Player_States((_eMediaStatus)nValue);
lstatus = sValue;
}
else if (
(switchtype == STYPE_Blinds) ||
(switchtype == STYPE_VenetianBlindsUS) ||
(switchtype == STYPE_VenetianBlindsEU)
)
{
root["result"][ii]["TypeImg"] = "blinds";
if ((lstatus == "On") || (lstatus == "Close inline relay")) {
lstatus = "Closed";
}
else if ((lstatus == "Stop") || (lstatus == "Stop inline relay")) {
lstatus = "Stopped";
}
else {
lstatus = "Open";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_BlindsInverted)
{
root["result"][ii]["TypeImg"] = "blinds";
if (lstatus == "On") {
lstatus = "Open";
}
else {
lstatus = "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if ((switchtype == STYPE_BlindsPercentage) || (switchtype == STYPE_BlindsPercentageInverted))
{
root["result"][ii]["TypeImg"] = "blinds";
root["result"][ii]["Level"] = LastLevel;
int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel);
root["result"][ii]["LevelInt"] = iLevel;
if (lstatus == "On") {
lstatus = (switchtype == STYPE_BlindsPercentage) ? "Closed" : "Open";
}
else if (lstatus == "Off") {
lstatus = (switchtype == STYPE_BlindsPercentage) ? "Open" : "Closed";
}
root["result"][ii]["Status"] = lstatus;
}
else if (switchtype == STYPE_Dimmer)
{
root["result"][ii]["TypeImg"] = "dimmer";
}
else if (switchtype == STYPE_Motion)
{
root["result"][ii]["TypeImg"] = "motion";
}
else if (switchtype == STYPE_Selector)
{
std::string selectorStyle = options["SelectorStyle"];
std::string levelOffHidden = options["LevelOffHidden"];
std::string levelNames = options["LevelNames"];
std::string levelActions = options["LevelActions"];
if (selectorStyle.empty()) {
selectorStyle.assign("0"); // default is 'button set'
}
if (levelOffHidden.empty()) {
levelOffHidden.assign("false"); // default is 'not hidden'
}
if (levelNames.empty()) {
levelNames.assign("Off"); // default is Off only
}
root["result"][ii]["TypeImg"] = "Light";
root["result"][ii]["SelectorStyle"] = atoi(selectorStyle.c_str());
root["result"][ii]["LevelOffHidden"] = (levelOffHidden == "true");
root["result"][ii]["LevelNames"] = base64_encode(levelNames);
root["result"][ii]["LevelActions"] = base64_encode(levelActions);
}
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
}
else if (dType == pTypeSecurity1)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "Security";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "security";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
if ((dSubType == sTypeKD101) || (dSubType == sTypeSA30) || (switchtype == STYPE_SMOKEDETECTOR))
{
root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR;
root["result"][ii]["TypeImg"] = "smoke";
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR);
}
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeSecurity2)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "Security";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "security";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeEvohome || dType == pTypeEvohomeRelay)
{
std::string lstatus = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd;
root["result"][ii]["SwitchType"] = "evohome";
root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?;
root["result"][ii]["TypeImg"] = "override_mini";
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
sprintf(szData, "%s", lstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = false;
if (dType == pTypeEvohomeRelay)
{
root["result"][ii]["SwitchType"] = "TPI";
root["result"][ii]["Level"] = llevel;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
if (root["result"][ii]["Unit"].asInt() > 100)
root["result"][ii]["Protected"] = true;
sprintf(szData, "%s: %d", lstatus.c_str(), atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
}
}
else if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "override_mini";
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() >= 3)
{
int i = 0;
double tempCelcius = atof(strarray[i++].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
double tempSetPoint;
root["result"][ii]["Temp"] = temp;
if (dType == pTypeEvohomeZone)
{
tempCelcius = atof(strarray[i++].c_str());
tempSetPoint = ConvertTemperature(tempCelcius, tempsign);
root["result"][ii]["SetPoint"] = tempSetPoint;
}
else
root["result"][ii]["State"] = strarray[i++];
std::string strstatus = strarray[i++];
root["result"][ii]["Status"] = strstatus;
if ((dType == pTypeEvohomeZone || dType == pTypeEvohomeWater) && strarray.size() >= 4)
{
root["result"][ii]["Until"] = strarray[i++];
}
if (dType == pTypeEvohomeZone)
{
if (tempCelcius == 325.1)
sprintf(szTmp, "Off");
else
sprintf(szTmp, "%.1f %c", tempSetPoint, tempsign);
if (strarray.size() >= 4)
sprintf(szData, "%.1f %c, (%s), %s until %s", temp, tempsign, szTmp, strstatus.c_str(), strarray[3].c_str());
else
sprintf(szData, "%.1f %c, (%s), %s", temp, tempsign, szTmp, strstatus.c_str());
}
else
if (strarray.size() >= 4)
sprintf(szData, "%.1f %c, %s, %s until %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str(), strarray[3].c_str());
else
sprintf(szData, "%.1f %c, %s, %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if ((dType == pTypeTEMP) || (dType == pTypeRego6XXTemp))
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dType == pTypeThermostat1)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 4)
{
double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if ((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "temperature";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dType == pTypeHUM)
{
root["result"][ii]["Humidity"] = nValue;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(sValue.c_str()));
sprintf(szData, "Humidity %d %%", nValue);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeTEMP_HUM)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 3)
{
double tempCelcius = atof(strarray[0].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
int humidity = atoi(strarray[1].c_str());
root["result"][ii]["Temp"] = temp;
root["result"][ii]["Humidity"] = humidity;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str()));
sprintf(szData, "%.1f %c, %d %%", temp, tempsign, atoi(strarray[1].c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
//Calculate dew point
sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign));
root["result"][ii]["DewPoint"] = szTmp;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeTEMP_HUM_BARO)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 5)
{
double tempCelcius = atof(strarray[0].c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
int humidity = atoi(strarray[1].c_str());
root["result"][ii]["Temp"] = temp;
root["result"][ii]["Humidity"] = humidity;
root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str()));
root["result"][ii]["Forecast"] = atoi(strarray[4].c_str());
sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign));
root["result"][ii]["DewPoint"] = szTmp;
if (dSubType == sTypeTHBFloat)
{
root["result"][ii]["Barometer"] = atof(strarray[3].c_str());
root["result"][ii]["ForecastStr"] = RFX_WSForecast_Desc(atoi(strarray[4].c_str()));
}
else
{
root["result"][ii]["Barometer"] = atoi(strarray[3].c_str());
root["result"][ii]["ForecastStr"] = RFX_Forecast_Desc(atoi(strarray[4].c_str()));
}
if (dSubType == sTypeTHBFloat)
{
sprintf(szData, "%.1f %c, %d %%, %.1f hPa",
temp,
tempsign,
atoi(strarray[1].c_str()),
atof(strarray[3].c_str())
);
}
else
{
sprintf(szData, "%.1f %c, %d %%, %d hPa",
temp,
tempsign,
atoi(strarray[1].c_str()),
atoi(strarray[3].c_str())
);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeTEMP_BARO)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() >= 3)
{
double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
int forecast = atoi(strarray[2].c_str());
root["result"][ii]["Forecast"] = forecast;
root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast);
root["result"][ii]["Barometer"] = atof(strarray[1].c_str());
sprintf(szData, "%.1f %c, %.1f hPa",
tvalue,
tempsign,
atof(strarray[1].c_str())
);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
}
else if (dType == pTypeUV)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
float UVI = static_cast<float>(atof(strarray[0].c_str()));
root["result"][ii]["UVI"] = strarray[0];
if (dSubType == sTypeUV3)
{
double tvalue = ConvertTemperature(atof(strarray[1].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f UVI, %.1f° %c", UVI, tvalue, tempsign);
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else
{
sprintf(szData, "%.1f UVI", UVI);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeWIND)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 6)
{
root["result"][ii]["Direction"] = atof(strarray[0].c_str());
root["result"][ii]["DirectionStr"] = strarray[1];
if (dSubType != sTypeWIND5)
{
int intSpeed = atoi(strarray[2].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
}
else
{
float windms = float(intSpeed) * 0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windms));
}
root["result"][ii]["Speed"] = szTmp;
}
//if (dSubType!=sTypeWIND6) //problem in RFXCOM firmware? gust=speed?
{
int intGust = atoi(strarray[3].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intGust) *m_sql.m_windscale);
}
else
{
float gustms = float(intGust) * 0.1f;
sprintf(szTmp, "%d", MStoBeaufort(gustms));
}
root["result"][ii]["Gust"] = szTmp;
}
if ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp))
{
if (dSubType == sTypeWIND4)
{
double tvalue = ConvertTemperature(atof(strarray[4].c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
}
double tvalue = ConvertTemperature(atof(strarray[5].c_str()), tempsign);
root["result"][ii]["Chill"] = tvalue;
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeRAIN)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
//get lowest value of today, and max rate
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
if (dSubType != sTypeRAINWU)
{
result2 = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total) FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
}
else
{
result2 = m_sql.safe_query(
"SELECT Total, Total FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q') ORDER BY ROWID DESC LIMIT 1", sd[0].c_str(), szDate);
}
if (!result2.empty())
{
double total_real = 0;
float rate = 0;
std::vector<std::string> sd2 = result2[0];
if (dSubType != sTypeRAINWU)
{
double total_min = atof(sd2[0].c_str());
double total_max = atof(strarray[1].c_str());
total_real = total_max - total_min;
}
else
{
total_real = atof(sd2[1].c_str());
}
total_real *= AddjMulti;
rate = (static_cast<float>(atof(strarray[0].c_str())) / 100.0f)*float(AddjMulti);
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["Rain"] = szTmp;
sprintf(szTmp, "%g", rate);
root["result"][ii]["RainRate"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else
{
root["result"][ii]["Rain"] = "0";
root["result"][ii]["RainRate"] = "0";
root["result"][ii]["Data"] = "0";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
}
else if (dType == pTypeRFXMeter)
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min = std::stoull(sd2[0]);
uint64_t total_max = std::stoull(sValue);
uint64_t total_real = total_max - total_min;
sprintf(szTmp, "%" PRIu64, total_real);
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
float musage = 0.0f;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / (divider / 1000.0f);
sprintf(szTmp, "%d Liter", round(musage));
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64, total_real);
if (!ValueUnits.empty())
{
strcat(szTmp, " ");
strcat(szTmp, ValueUnits.c_str());
}
break;
default:
strcpy(szTmp, "?");
break;
}
}
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
double meteroffset = AddjValue;
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
double dvalue = static_cast<double>(atof(sValue.c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min = std::stoull(sd2[0]);
uint64_t total_max = std::stoull(sValue);
uint64_t total_real = total_max - total_min;
sprintf(szTmp, "%" PRIu64, total_real);
float musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64, total_real);
if (!ValueUnits.empty())
{
strcat(szTmp, " ");
strcat(szTmp, ValueUnits.c_str());
}
break;
default:
strcpy(szTmp, "0");
break;
}
}
root["result"][ii]["Counter"] = sValue;
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "counter";
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
double dvalue = static_cast<double>(atof(sValue.c_str()));
double meteroffset = AddjValue;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%" PRIu64 " %s", static_cast<uint64_t>(meteroffset + dvalue), ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
double dvalue;
if (splitresults.size() < 2) {
dvalue = static_cast<double>(atof(sValue.c_str()));
}
else {
dvalue = static_cast<double>(atof(splitresults[1].c_str()));
if (dvalue < 0.0) {
dvalue = static_cast<double>(atof(splitresults[0].c_str()));
}
}
root["result"][ii]["Data"] = root["result"][ii]["Counter"];
root["result"][ii]["SwitchTypeVal"] = metertype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "counter";
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
root["result"][ii]["ShowNotifications"] = false;
double meteroffset = AddjValue;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
root["result"][ii]["Data"] = "?";
root["result"][ii]["Counter"] = "?";
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
}
}
else if (dType == pTypeYouLess)
{
std::string ValueQuantity = options["ValueQuantity"];
std::string ValueUnits = options["ValueUnits"];
float musage = 0;
if (ValueQuantity.empty()) {
ValueQuantity.assign("Count");
}
if (ValueUnits.empty()) {
ValueUnits.assign("");
}
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f kWh", musage);
break;
case MTYPE_GAS:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(total_real) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu %s", total_real, ValueUnits.c_str());
break;
default:
strcpy(szTmp, "0");
break;
}
}
root["result"][ii]["CounterToday"] = szTmp;
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() < 2)
continue;
unsigned long long total_actual = std::strtoull(splitresults[0].c_str(), nullptr, 10);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(total_actual) / divider;
sprintf(szTmp, "%.03f", musage);
break;
case MTYPE_GAS:
case MTYPE_WATER:
musage = float(total_actual) / divider;
sprintf(szTmp, "%.03f", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu", total_actual);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Counter"] = szTmp;
root["result"][ii]["SwitchTypeVal"] = metertype;
unsigned long long acounter = std::strtoull(sValue.c_str(), nullptr, 10);
musage = 0;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f kWh %s Watt", musage, splitresults[1].c_str());
break;
case MTYPE_GAS:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_WATER:
musage = float(acounter) / divider;
sprintf(szTmp, "%.3f m3", musage);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%llu %s", acounter, ValueUnits.c_str());
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["ValueQuantity"] = "";
root["result"][ii]["ValueUnits"] = "";
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%s Watt", splitresults[1].c_str());
break;
case MTYPE_GAS:
sprintf(szTmp, "%s m3", splitresults[1].c_str());
break;
case MTYPE_WATER:
sprintf(szTmp, "%s m3", splitresults[1].c_str());
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%s", splitresults[1].c_str());
root["result"][ii]["ValueQuantity"] = ValueQuantity;
root["result"][ii]["ValueUnits"] = ValueUnits;
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["Usage"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeP1Power)
{
std::vector<std::string> splitresults;
StringSplit(sValue, ";", splitresults);
if (splitresults.size() != 6)
{
root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY;
root["result"][ii]["Counter"] = "0";
root["result"][ii]["CounterDeliv"] = "0";
root["result"][ii]["Usage"] = "Invalid";
root["result"][ii]["UsageDeliv"] = "Invalid";
root["result"][ii]["Data"] = "Invalid!: " + sValue;
root["result"][ii]["HaveTimeout"] = true;
root["result"][ii]["CounterToday"] = "Invalid";
root["result"][ii]["CounterDelivToday"] = "Invalid";
}
else
{
float EnergyDivider = 1000.0f;
int tValue;
if (m_sql.GetPreferencesVar("MeterDividerEnergy", tValue))
{
EnergyDivider = float(tValue);
}
unsigned long long powerusage1 = std::strtoull(splitresults[0].c_str(), nullptr, 10);
unsigned long long powerusage2 = std::strtoull(splitresults[1].c_str(), nullptr, 10);
unsigned long long powerdeliv1 = std::strtoull(splitresults[2].c_str(), nullptr, 10);
unsigned long long powerdeliv2 = std::strtoull(splitresults[3].c_str(), nullptr, 10);
unsigned long long usagecurrent = std::strtoull(splitresults[4].c_str(), nullptr, 10);
unsigned long long delivcurrent = std::strtoull(splitresults[5].c_str(), nullptr, 10);
powerdeliv1 = (powerdeliv1 < 10) ? 0 : powerdeliv1;
powerdeliv2 = (powerdeliv2 < 10) ? 0 : powerdeliv2;
unsigned long long powerusage = powerusage1 + powerusage2;
unsigned long long powerdeliv = powerdeliv1 + powerdeliv2;
if (powerdeliv < 2)
powerdeliv = 0;
double musage = 0;
root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY;
musage = double(powerusage) / EnergyDivider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["Counter"] = szTmp;
musage = double(powerdeliv) / EnergyDivider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["CounterDeliv"] = szTmp;
if (bHaveTimeout)
{
usagecurrent = 0;
delivcurrent = 0;
}
sprintf(szTmp, "%llu Watt", usagecurrent);
root["result"][ii]["Usage"] = szTmp;
sprintf(szTmp, "%llu Watt", delivcurrent);
root["result"][ii]["UsageDeliv"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value1), MIN(Value2), MIN(Value5), MIN(Value6) FROM MultiMeter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min_usage_1 = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_min_deliv_1 = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd2[2].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd2[3].c_str(), nullptr, 10);
unsigned long long total_real_usage, total_real_deliv;
total_real_usage = powerusage - (total_min_usage_1 + total_min_usage_2);
total_real_deliv = powerdeliv - (total_min_deliv_1 + total_min_deliv_2);
musage = double(total_real_usage) / EnergyDivider;
sprintf(szTmp, "%.3f kWh", musage);
root["result"][ii]["CounterToday"] = szTmp;
musage = double(total_real_deliv) / EnergyDivider;
sprintf(szTmp, "%.3f kWh", musage);
root["result"][ii]["CounterDelivToday"] = szTmp;
}
else
{
sprintf(szTmp, "%.3f kWh", 0.0f);
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["CounterDelivToday"] = szTmp;
}
}
}
else if (dType == pTypeP1Gas)
{
root["result"][ii]["SwitchTypeVal"] = MTYPE_GAS;
//get lowest value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
uint64_t total_min_gas = std::stoull(sd2[0]);
uint64_t gasactual = std::stoull(sValue);
uint64_t total_real_gas = gasactual - total_min_gas;
double musage = double(gasactual) / divider;
sprintf(szTmp, "%.03f", musage);
root["result"][ii]["Counter"] = szTmp;
musage = double(total_real_gas) / divider;
sprintf(szTmp, "%.03f m3", musage);
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider);
root["result"][ii]["Data"] = szTmp;
}
else
{
sprintf(szTmp, "%.03f", 0.0f);
root["result"][ii]["Counter"] = szTmp;
sprintf(szTmp, "%.03f m3", 0.0f);
root["result"][ii]["CounterToday"] = szTmp;
sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeCURRENT)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 3)
{
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
double val1 = atof(strarray[0].c_str());
double val2 = atof(strarray[1].c_str());
double val3 = atof(strarray[2].c_str());
if (displaytype == 0)
{
if ((val2 == 0) && (val3 == 0))
sprintf(szData, "%.1f A", val1);
else
sprintf(szData, "%.1f A, %.1f A, %.1f A", val1, val2, val3);
}
else
{
if ((val2 == 0) && (val3 == 0))
sprintf(szData, "%d Watt", int(val1*voltage));
else
sprintf(szData, "%d Watt, %d Watt, %d Watt", int(val1*voltage), int(val2*voltage), int(val3*voltage));
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["displaytype"] = displaytype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (dType == pTypeCURRENTENERGY)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 4)
{
//CM180i
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
double total = atof(strarray[3].c_str());
if (displaytype == 0)
{
sprintf(szData, "%.1f A, %.1f A, %.1f A", atof(strarray[0].c_str()), atof(strarray[1].c_str()), atof(strarray[2].c_str()));
}
else
{
sprintf(szData, "%d Watt, %d Watt, %d Watt", int(atof(strarray[0].c_str())*voltage), int(atof(strarray[1].c_str())*voltage), int(atof(strarray[2].c_str())*voltage));
}
if (total > 0)
{
sprintf(szTmp, ", Total: %.3f kWh", total / 1000.0f);
strcat(szData, szTmp);
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["displaytype"] = displaytype;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
else if (
((dType == pTypeENERGY) || (dType == pTypePOWER)) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
double total = atof(strarray[1].c_str()) / 1000;
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::vector<std::string> sd2 = result2[0];
double minimum = atof(sd2[0].c_str()) / divider;
sprintf(szData, "%.3f kWh", total);
root["result"][ii]["Data"] = szData;
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
{
sprintf(szData, "%ld Watt", atol(strarray[0].c_str()));
}
else
{
sprintf(szData, "%g Watt", atof(strarray[0].c_str()));
}
root["result"][ii]["Usage"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%.3f kWh", total - minimum);
root["result"][ii]["CounterToday"] = szTmp;
}
else
{
sprintf(szData, "%.3f kWh", total);
root["result"][ii]["Data"] = szData;
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
{
sprintf(szData, "%ld Watt", atol(strarray[0].c_str()));
}
else
{
sprintf(szData, "%g Watt", atof(strarray[0].c_str()));
}
root["result"][ii]["Usage"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
sprintf(szTmp, "%d kWh", 0);
root["result"][ii]["CounterToday"] = szTmp;
}
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["SwitchTypeVal"] = switchtype; //MTYPE_ENERGY
root["result"][ii]["EnergyMeterMode"] = options["EnergyMeterMode"]; //for alternate Energy Reading
}
}
else if (dType == pTypeAirQuality)
{
if (bHaveTimeout)
nValue = 0;
sprintf(szTmp, "%d ppm", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
int airquality = nValue;
if (airquality < 700)
root["result"][ii]["Quality"] = "Excellent";
else if (airquality < 900)
root["result"][ii]["Quality"] = "Good";
else if (airquality < 1100)
root["result"][ii]["Quality"] = "Fair";
else if (airquality < 1600)
root["result"][ii]["Quality"] = "Mediocre";
else
root["result"][ii]["Quality"] = "Bad";
}
else if (dType == pTypeThermostat)
{
if (dSubType == sTypeThermSetpoint)
{
bHasTimers = m_sql.HasTimers(sd[0]);
double tempCelcius = atof(sValue.c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
sprintf(szTmp, "%.1f", temp);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["SetPoint"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "override_mini";
}
}
else if (dType == pTypeRadiator1)
{
if (dSubType == sTypeSmartwares)
{
bHasTimers = m_sql.HasTimers(sd[0]);
double tempCelcius = atof(sValue.c_str());
double temp = ConvertTemperature(tempCelcius, tempsign);
sprintf(szTmp, "%.1f", temp);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["SetPoint"] = szTmp;
root["result"][ii]["HaveTimeout"] = false; //this device does not provide feedback, so no timeout!
root["result"][ii]["TypeImg"] = "override_mini";
}
}
else if (dType == pTypeGeneral)
{
if (dSubType == sTypeVisibility)
{
float vis = static_cast<float>(atof(sValue.c_str()));
if (metertype == 0)
{
//km
sprintf(szTmp, "%.1f km", vis);
}
else
{
//miles
sprintf(szTmp, "%.1f mi", vis*0.6214f);
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Visibility"] = atof(sValue.c_str());
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "visibility";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeDistance)
{
float vis = static_cast<float>(atof(sValue.c_str()));
if (metertype == 0)
{
//km
sprintf(szTmp, "%.1f cm", vis);
}
else
{
//miles
sprintf(szTmp, "%.1f in", vis*0.6214f);
}
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "visibility";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSolarRadiation)
{
float radiation = static_cast<float>(atof(sValue.c_str()));
sprintf(szTmp, "%.1f Watt/m2", radiation);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Radiation"] = atof(sValue.c_str());
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "radiation";
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSoilMoisture)
{
sprintf(szTmp, "%d cb", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["Desc"] = Get_Moisture_Desc(nValue);
root["result"][ii]["TypeImg"] = "moisture";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeLeafWetness)
{
sprintf(szTmp, "%d", nValue);
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["TypeImg"] = "leaf";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["SwitchTypeVal"] = metertype;
}
else if (dSubType == sTypeSystemTemp)
{
double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign);
root["result"][ii]["Temp"] = tvalue;
sprintf(szData, "%.1f %c", tvalue, tempsign);
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Computer";
root["result"][ii]["TypeImg"] = "temperature";
root["result"][ii]["Type"] = "temperature";
_tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN;
uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF);
if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end())
{
tstate = m_mainworker.m_trend_calculator[tID].m_state;
}
root["result"][ii]["trend"] = (int)tstate;
}
else if (dSubType == sTypePercentage)
{
sprintf(szData, "%g%%", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Computer";
root["result"][ii]["TypeImg"] = "hardware";
}
else if (dSubType == sTypeWaterflow)
{
sprintf(szData, "%g l/min", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Moisture";
root["result"][ii]["TypeImg"] = "moisture";
}
else if (dSubType == sTypeCustom)
{
std::string szAxesLabel = "";
int SensorType = 1;
std::vector<std::string> sResults;
StringSplit(sOptions, ";", sResults);
if (sResults.size() == 2)
{
SensorType = atoi(sResults[0].c_str());
szAxesLabel = sResults[1];
}
sprintf(szData, "%g %s", atof(sValue.c_str()), szAxesLabel.c_str());
root["result"][ii]["Data"] = szData;
root["result"][ii]["SensorType"] = SensorType;
root["result"][ii]["SensorUnit"] = szAxesLabel;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string IconFile = "Custom";
if (CustomImage != 0)
{
std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage);
if (ittIcon != m_custom_light_icons_lookup.end())
{
IconFile = m_custom_light_icons[ittIcon->second].RootFile;
}
}
root["result"][ii]["Image"] = IconFile;
root["result"][ii]["TypeImg"] = IconFile;
}
else if (dSubType == sTypeFan)
{
sprintf(szData, "%d RPM", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Image"] = "Fan";
root["result"][ii]["TypeImg"] = "Fan";
}
else if (dSubType == sTypeSoundLevel)
{
sprintf(szData, "%d dB", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "Speaker";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dSubType == sTypeVoltage)
{
sprintf(szData, "%g V", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Voltage"] = atof(sValue.c_str());
}
else if (dSubType == sTypeCurrent)
{
sprintf(szData, "%g A", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "current";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Current"] = atof(sValue.c_str());
}
else if (dSubType == sTypeTextStatus)
{
root["result"][ii]["Data"] = sValue;
root["result"][ii]["TypeImg"] = "text";
root["result"][ii]["HaveTimeout"] = false;
root["result"][ii]["ShowNotifications"] = false;
}
else if (dSubType == sTypeAlert)
{
if (nValue > 4)
nValue = 4;
sprintf(szData, "Level: %d", nValue);
root["result"][ii]["Data"] = szData;
if (!sValue.empty())
root["result"][ii]["Data"] = sValue;
else
root["result"][ii]["Data"] = Get_Alert_Desc(nValue);
root["result"][ii]["TypeImg"] = "Alert";
root["result"][ii]["Level"] = nValue;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dSubType == sTypePressure)
{
sprintf(szData, "%.1f Bar", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "gauge";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["Pressure"] = atof(sValue.c_str());
}
else if (dSubType == sTypeBaro)
{
std::vector<std::string> tstrarray;
StringSplit(sValue, ";", tstrarray);
if (tstrarray.empty())
continue;
sprintf(szData, "%g hPa", atof(tstrarray[0].c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "gauge";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
if (tstrarray.size() > 1)
{
root["result"][ii]["Barometer"] = atof(tstrarray[0].c_str());
int forecast = atoi(tstrarray[1].c_str());
root["result"][ii]["Forecast"] = forecast;
root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast);
}
}
else if (dSubType == sTypeZWaveClock)
{
std::vector<std::string> tstrarray;
StringSplit(sValue, ";", tstrarray);
int day = 0;
int hour = 0;
int minute = 0;
if (tstrarray.size() == 3)
{
day = atoi(tstrarray[0].c_str());
hour = atoi(tstrarray[1].c_str());
minute = atoi(tstrarray[2].c_str());
}
sprintf(szData, "%s %02d:%02d", ZWave_Clock_Days(day), hour, minute);
root["result"][ii]["DayTime"] = sValue;
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["TypeImg"] = "clock";
}
else if (dSubType == sTypeZWaveThermostatMode)
{
strcpy(szData, "");
root["result"][ii]["Mode"] = nValue;
root["result"][ii]["TypeImg"] = "mode";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
std::string modes = "";
//Add supported modes
#ifdef WITH_OPENZWAVE
if (pHardware)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
std::vector<std::string> vmodes = pZWave->GetSupportedThermostatModes(ID);
int smode = 0;
char szTmp[200];
for (const auto & itt : vmodes)
{
//Value supported
sprintf(szTmp, "%d;%s;", smode, itt.c_str());
modes += szTmp;
smode++;
}
if (!vmodes.empty())
{
if (nValue < (int)vmodes.size())
{
sprintf(szData, "%s", vmodes[nValue].c_str());
}
}
}
}
#endif
root["result"][ii]["Data"] = szData;
root["result"][ii]["Modes"] = modes;
}
else if (dSubType == sTypeZWaveThermostatFanMode)
{
sprintf(szData, "%s", ZWave_Thermostat_Fan_Modes[nValue]);
root["result"][ii]["Data"] = szData;
root["result"][ii]["Mode"] = nValue;
root["result"][ii]["TypeImg"] = "mode";
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
//Add supported modes (add all for now)
bool bAddedSupportedModes = false;
std::string modes = "";
//Add supported modes
#ifdef WITH_OPENZWAVE
if (pHardware)
{
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware);
unsigned long ID;
std::stringstream s_strid;
s_strid << std::hex << sd[1];
s_strid >> ID;
modes = pZWave->GetSupportedThermostatFanModes(ID);
bAddedSupportedModes = !modes.empty();
}
}
#endif
if (!bAddedSupportedModes)
{
int smode = 0;
while (ZWave_Thermostat_Fan_Modes[smode] != NULL)
{
sprintf(szTmp, "%d;%s;", smode, ZWave_Thermostat_Fan_Modes[smode]);
modes += szTmp;
smode++;
}
}
root["result"][ii]["Modes"] = modes;
}
else if (dSubType == sTypeZWaveAlarm)
{
sprintf(szData, "Event: 0x%02X (%d)", nValue, nValue);
root["result"][ii]["Data"] = szData;
root["result"][ii]["TypeImg"] = "Alert";
root["result"][ii]["Level"] = nValue;
root["result"][ii]["HaveTimeout"] = false;
}
}
else if (dType == pTypeLux)
{
sprintf(szTmp, "%.0f Lux", atof(sValue.c_str()));
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeWEIGHT)
{
sprintf(szTmp, "%g %s", m_sql.m_weightscale * atof(sValue.c_str()), m_sql.m_weightsign.c_str());
root["result"][ii]["Data"] = szTmp;
root["result"][ii]["HaveTimeout"] = false;
}
else if (dType == pTypeUsage)
{
if (dSubType == sTypeElectric)
{
sprintf(szData, "%g Watt", atof(sValue.c_str()));
root["result"][ii]["Data"] = szData;
}
else
{
root["result"][ii]["Data"] = sValue;
}
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeRFXSensor)
{
switch (dSubType)
{
case sTypeRFXSensorAD:
sprintf(szData, "%d mV", atoi(sValue.c_str()));
root["result"][ii]["TypeImg"] = "current";
break;
case sTypeRFXSensorVolt:
sprintf(szData, "%d mV", atoi(sValue.c_str()));
root["result"][ii]["TypeImg"] = "current";
break;
}
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
else if (dType == pTypeRego6XXValue)
{
switch (dSubType)
{
case sTypeRego6XXStatus:
{
std::string lstatus = "On";
if (atoi(sValue.c_str()) == 0)
{
lstatus = "Off";
}
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["HaveDimmer"] = false;
root["result"][ii]["MaxDimLevel"] = 0;
root["result"][ii]["HaveGroupCmd"] = false;
root["result"][ii]["TypeImg"] = "utility";
root["result"][ii]["SwitchTypeVal"] = STYPE_OnOff;
root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_OnOff);
sprintf(szData, "%d", atoi(sValue.c_str()));
root["result"][ii]["Data"] = szData;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
root["result"][ii]["StrParam1"] = strParam1;
root["result"][ii]["StrParam2"] = strParam2;
root["result"][ii]["Protected"] = (iProtected != 0);
if (CustomImage < static_cast<int>(m_custom_light_icons.size()))
root["result"][ii]["Image"] = m_custom_light_icons[CustomImage].RootFile;
else
root["result"][ii]["Image"] = "Light";
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
root["result"][ii]["Level"] = 0;
root["result"][ii]["LevelInt"] = atoi(sValue.c_str());
}
break;
case sTypeRego6XXCounter:
{
//get value of today
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
char szDate[40];
sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday);
std::vector<std::vector<std::string> > result2;
strcpy(szTmp, "0");
result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')",
sd[0].c_str(), szDate);
if (!result2.empty())
{
std::vector<std::string> sd2 = result2[0];
unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
}
root["result"][ii]["SwitchTypeVal"] = MTYPE_COUNTER;
root["result"][ii]["Counter"] = sValue;
root["result"][ii]["CounterToday"] = szTmp;
root["result"][ii]["Data"] = sValue;
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
break;
}
}
#ifdef ENABLE_PYTHON
if (pHardware != NULL)
{
if (pHardware->HwdType == HTYPE_PythonPlugin)
{
Plugins::CPlugin *pPlugin = (Plugins::CPlugin*)pHardware;
bHaveTimeout = pPlugin->HasNodeFailed(atoi(sd[2].c_str()));
root["result"][ii]["HaveTimeout"] = bHaveTimeout;
}
}
#endif
root["result"][ii]["Timers"] = (bHasTimers == true) ? "true" : "false";
ii++;
}
}
}
void CWebServer::UploadFloorplanImage(WebEmSession & session, const request& req, std::string & redirect_uri)
{
redirect_uri = "/index.html";
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string planname = request::findValue(&req, "planname");
std::string scalefactor = request::findValue(&req, "scalefactor");
std::string imagefile = request::findValue(&req, "imagefile");
std::vector<std::vector<std::string> > result;
m_sql.safe_query("INSERT INTO Floorplans ([Name],[ScaleFactor]) VALUES('%s','%s')", planname.c_str(),scalefactor.c_str());
result = m_sql.safe_query("SELECT MAX(ID) FROM Floorplans");
if (!result.empty())
{
if (!m_sql.safe_UpdateBlobInTableWithID("Floorplans", "Image", result[0][0], imagefile))
_log.Log(LOG_ERROR, "SQL: Problem inserting floorplan image into database! ");
}
}
void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)
{
std::string idx = request::findValue(&req, "idx");
if (idx == "") {
return;
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%s", idx.c_str());
if (result.empty())
return;
reply::set_content(&rep, result[0][0].begin(), result[0][0].end());
std::string oname = "floorplan";
if (result[0][0].size() > 10)
{
if (result[0][0][0] == 'P')
oname += ".png";
else if (result[0][0][0] == -1)
oname += ".jpg";
else if (result[0][0][0] == 'B')
oname += ".bmp";
else if (result[0][0][0] == 'G')
oname += ".gif";
}
reply::add_header_attachment(&rep, oname);
}
void CWebServer::GetDatabaseBackup(WebEmSession & session, const request& req, reply & rep)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
#ifdef WIN32
std::string OutputFileName = szUserDataFolder + "backup.db";
#else
std::string OutputFileName = "/tmp/backup.db";
#endif
if (m_sql.BackupDatabase(OutputFileName))
{
std::string szAttachmentName = "domoticz.db";
std::string szVar;
if (m_sql.GetPreferencesVar("Title", szVar))
{
stdreplace(szVar, " ", "_");
stdreplace(szVar, "/", "_");
stdreplace(szVar, "\\", "_");
if (!szVar.empty()) {
szAttachmentName = szVar + ".db";
}
}
reply::set_content_from_file(&rep, OutputFileName, szAttachmentName, true);
}
}
void CWebServer::RType_DeleteDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteDevice";
m_sql.DeleteDevices(idx);
m_mainworker.m_scheduler.ReloadSchedules();
}
void CWebServer::RType_AddScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string name = request::findValue(&req, "name");
if (name.empty())
{
root["status"] = "ERR";
root["message"] = "No Scene Name specified!";
return;
}
std::string stype = request::findValue(&req, "scenetype");
if (stype.empty())
{
root["status"] = "ERR";
root["message"] = "No Scene Type specified!";
return;
}
if (m_sql.DoesSceneByNameExits(name) == true)
{
root["status"] = "ERR";
root["message"] = "A Scene with this Name already Exits!";
return;
}
root["status"] = "OK";
root["title"] = "AddScene";
m_sql.safe_query(
"INSERT INTO Scenes (Name,SceneType) VALUES ('%q',%d)",
name.c_str(),
atoi(stype.c_str())
);
if (m_sql.m_bEnableEventSystem)
{
m_mainworker.m_eventsystem.GetCurrentScenesGroups();
}
}
void CWebServer::RType_DeleteScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "DeleteScene";
m_sql.safe_query("DELETE FROM Scenes WHERE (ID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SceneDevices WHERE (SceneRowID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SceneTimers WHERE (SceneRowID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM SceneLog WHERE (SceneRowID=='%q')", idx.c_str());
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.RemoveSingleState(ullidx, m_mainworker.m_eventsystem.REASON_SCENEGROUP);
}
void CWebServer::RType_UpdateScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string name = request::findValue(&req, "name");
std::string description = request::findValue(&req, "description");
if ((idx.empty()) || (name.empty()))
return;
std::string stype = request::findValue(&req, "scenetype");
if (stype.empty())
{
root["status"] = "ERR";
root["message"] = "No Scene Type specified!";
return;
}
std::string tmpstr = request::findValue(&req, "protected");
int iProtected = (tmpstr == "true") ? 1 : 0;
std::string onaction = base64_decode(request::findValue(&req, "onaction"));
std::string offaction = base64_decode(request::findValue(&req, "offaction"));
root["status"] = "OK";
root["title"] = "UpdateScene";
m_sql.safe_query("UPDATE Scenes SET Name='%q', Description='%q', SceneType=%d, Protected=%d, OnAction='%q', OffAction='%q' WHERE (ID == '%q')",
name.c_str(),
description.c_str(),
atoi(stype.c_str()),
iProtected,
onaction.c_str(),
offaction.c_str(),
idx.c_str()
);
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.WWWUpdateSingleState(ullidx, name, m_mainworker.m_eventsystem.REASON_SCENEGROUP);
}
bool compareIconsByName(const http::server::CWebServer::_tCustomIcon &a, const http::server::CWebServer::_tCustomIcon &b)
{
return a.Title < b.Title;
}
void CWebServer::RType_CustomLightIcons(WebEmSession & session, const request& req, Json::Value &root)
{
int ii = 0;
std::vector<_tCustomIcon> temp_custom_light_icons = m_custom_light_icons;
//Sort by name
std::sort(temp_custom_light_icons.begin(), temp_custom_light_icons.end(), compareIconsByName);
for (const auto & itt : temp_custom_light_icons)
{
root["result"][ii]["idx"] = itt.idx;
root["result"][ii]["imageSrc"] = itt.RootFile;
root["result"][ii]["text"] = itt.Title;
root["result"][ii]["description"] = itt.Description;
ii++;
}
root["status"] = "OK";
}
void CWebServer::RType_Plans(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Plans";
std::string sDisplayHidden = request::findValue(&req, "displayhidden");
bool bDisplayHidden = (sDisplayHidden == "1");
std::vector<std::vector<std::string> > result, result2;
result = m_sql.safe_query("SELECT ID, Name, [Order] FROM Plans ORDER BY [Order]");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string Name = sd[1];
bool bIsHidden = (Name[0] == '$');
if ((bDisplayHidden) || (!bIsHidden))
{
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = Name;
root["result"][ii]["Order"] = sd[2];
unsigned int totDevices = 0;
result2 = m_sql.safe_query("SELECT COUNT(*) FROM DeviceToPlansMap WHERE (PlanID=='%q')",
sd[0].c_str());
if (!result2.empty())
{
totDevices = (unsigned int)atoi(result2[0][0].c_str());
}
root["result"][ii]["Devices"] = totDevices;
ii++;
}
}
}
}
void CWebServer::RType_FloorPlans(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Floorplans";
std::vector<std::vector<std::string> > result, result2, result3;
result = m_sql.safe_query("SELECT Key, nValue, sValue FROM Preferences WHERE Key LIKE 'Floorplan%%'");
if (result.empty())
return;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string Key = sd[0];
int nValue = atoi(sd[1].c_str());
std::string sValue = sd[2];
if (Key == "FloorplanPopupDelay")
{
root["PopupDelay"] = nValue;
}
if (Key == "FloorplanFullscreenMode")
{
root["FullscreenMode"] = nValue;
}
if (Key == "FloorplanAnimateZoom")
{
root["AnimateZoom"] = nValue;
}
if (Key == "FloorplanShowSensorValues")
{
root["ShowSensorValues"] = nValue;
}
if (Key == "FloorplanShowSwitchValues")
{
root["ShowSwitchValues"] = nValue;
}
if (Key == "FloorplanShowSceneNames")
{
root["ShowSceneNames"] = nValue;
}
if (Key == "FloorplanRoomColour")
{
root["RoomColour"] = sValue;
}
if (Key == "FloorplanActiveOpacity")
{
root["ActiveRoomOpacity"] = nValue;
}
if (Key == "FloorplanInactiveOpacity")
{
root["InactiveRoomOpacity"] = nValue;
}
}
result2 = m_sql.safe_query("SELECT ID, Name, ScaleFactor, [Order] FROM Floorplans ORDER BY [Order]");
if (!result2.empty())
{
int ii = 0;
for (const auto & itt : result2)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
std::string ImageURL = "images/floorplans/plan?idx=" + sd[0];
root["result"][ii]["Image"] = ImageURL;
root["result"][ii]["ScaleFactor"] = sd[2];
root["result"][ii]["Order"] = sd[3];
unsigned int totPlans = 0;
result3 = m_sql.safe_query("SELECT COUNT(*) FROM Plans WHERE (FloorplanID=='%q')", sd[0].c_str());
if (!result3.empty())
{
totPlans = (unsigned int)atoi(result3[0][0].c_str());
}
root["result"][ii]["Plans"] = totPlans;
ii++;
}
}
}
void CWebServer::RType_Scenes(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Scenes";
root["AllowWidgetOrdering"] = m_sql.m_bAllowWidgetOrdering;
std::string sDisplayHidden = request::findValue(&req, "displayhidden");
bool bDisplayHidden = (sDisplayHidden == "1");
std::string sLastUpdate = request::findValue(&req, "lastupdate");
time_t LastUpdate = 0;
if (sLastUpdate != "")
{
std::stringstream sstr;
sstr << sLastUpdate;
sstr >> LastUpdate;
}
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
struct tm tLastUpdate;
localtime_r(&now, &tLastUpdate);
root["ActTime"] = static_cast<int>(now);
std::vector<std::vector<std::string> > result, result2;
result = m_sql.safe_query("SELECT ID, Name, Activators, Favorite, nValue, SceneType, LastUpdate, Protected, OnAction, OffAction, Description FROM Scenes ORDER BY [Order]");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string sName = sd[1];
if ((bDisplayHidden == false) && (sName[0] == '$'))
continue;
std::string sLastUpdate = sd[6].c_str();
if (LastUpdate != 0)
{
time_t cLastUpdate;
ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst);
if (cLastUpdate <= LastUpdate)
continue;
}
unsigned char nValue = atoi(sd[4].c_str());
unsigned char scenetype = atoi(sd[5].c_str());
int iProtected = atoi(sd[7].c_str());
std::string onaction = base64_encode(sd[8]);
std::string offaction = base64_encode(sd[9]);
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sName;
root["result"][ii]["Description"] = sd[10];
root["result"][ii]["Favorite"] = atoi(sd[3].c_str());
root["result"][ii]["Protected"] = (iProtected != 0);
root["result"][ii]["OnAction"] = onaction;
root["result"][ii]["OffAction"] = offaction;
if (scenetype == 0)
{
root["result"][ii]["Type"] = "Scene";
}
else
{
root["result"][ii]["Type"] = "Group";
}
root["result"][ii]["LastUpdate"] = sLastUpdate;
if (nValue == 0)
root["result"][ii]["Status"] = "Off";
else if (nValue == 1)
root["result"][ii]["Status"] = "On";
else
root["result"][ii]["Status"] = "Mixed";
root["result"][ii]["Timers"] = (m_sql.HasSceneTimers(sd[0]) == true) ? "true" : "false";
uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(1, sd[0]);
root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false;
if (camIDX != 0) {
std::stringstream scidx;
scidx << camIDX;
root["result"][ii]["CameraIdx"] = scidx.str();
}
ii++;
}
}
if (!m_mainworker.m_LastSunriseSet.empty())
{
std::vector<std::string> strarray;
StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray);
if (strarray.size() == 10)
{
char szTmp[100];
//strftime(szTmp, 80, "%b %d %Y %X", &tm1);
strftime(szTmp, 80, "%Y-%m-%d %X", &tm1);
root["ServerTime"] = szTmp;
root["Sunrise"] = strarray[0];
root["Sunset"] = strarray[1];
root["SunAtSouth"] = strarray[2];
root["CivTwilightStart"] = strarray[3];
root["CivTwilightEnd"] = strarray[4];
root["NautTwilightStart"] = strarray[5];
root["NautTwilightEnd"] = strarray[6];
root["AstrTwilightStart"] = strarray[7];
root["AstrTwilightEnd"] = strarray[8];
root["DayLength"] = strarray[9];
}
}
}
void CWebServer::RType_Hardware(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Hardware";
#ifdef WITH_OPENZWAVE
m_ZW_Hwidx = -1;
#endif
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, Enabled, Type, Address, Port, SerialPort, Username, Password, Extra, Mode1, Mode2, Mode3, Mode4, Mode5, Mode6, DataTimeout FROM Hardware ORDER BY ID ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
_eHardwareTypes hType = (_eHardwareTypes)atoi(sd[3].c_str());
if (hType == HTYPE_DomoticzInternal)
continue;
if (hType == HTYPE_RESERVED_FOR_YOU_1)
continue;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
root["result"][ii]["Enabled"] = (sd[2] == "1") ? "true" : "false";
root["result"][ii]["Type"] = hType;
root["result"][ii]["Address"] = sd[4];
root["result"][ii]["Port"] = atoi(sd[5].c_str());
root["result"][ii]["SerialPort"] = sd[6];
root["result"][ii]["Username"] = sd[7];
root["result"][ii]["Password"] = sd[8];
root["result"][ii]["Extra"] = sd[9];
if (hType == HTYPE_PythonPlugin) {
root["result"][ii]["Mode1"] = sd[10]; // Plugins can have non-numeric values in the Mode fields
root["result"][ii]["Mode2"] = sd[11];
root["result"][ii]["Mode3"] = sd[12];
root["result"][ii]["Mode4"] = sd[13];
root["result"][ii]["Mode5"] = sd[14];
root["result"][ii]["Mode6"] = sd[15];
}
else {
root["result"][ii]["Mode1"] = atoi(sd[10].c_str());
root["result"][ii]["Mode2"] = atoi(sd[11].c_str());
root["result"][ii]["Mode3"] = atoi(sd[12].c_str());
root["result"][ii]["Mode4"] = atoi(sd[13].c_str());
root["result"][ii]["Mode5"] = atoi(sd[14].c_str());
root["result"][ii]["Mode6"] = atoi(sd[15].c_str());
}
root["result"][ii]["DataTimeout"] = atoi(sd[16].c_str());
//Special case for openzwave (status for nodes queried)
CDomoticzHardwareBase *pHardware = m_mainworker.GetHardware(atoi(sd[0].c_str()));
if (pHardware != NULL)
{
if (
(pHardware->HwdType == HTYPE_RFXtrx315) ||
(pHardware->HwdType == HTYPE_RFXtrx433) ||
(pHardware->HwdType == HTYPE_RFXtrx868) ||
(pHardware->HwdType == HTYPE_RFXLAN)
)
{
CRFXBase *pMyHardware = reinterpret_cast<CRFXBase*>(pHardware);
if (!pMyHardware->m_Version.empty())
root["result"][ii]["version"] = pMyHardware->m_Version;
else
root["result"][ii]["version"] = sd[11];
root["result"][ii]["noiselvl"] = pMyHardware->m_NoiseLevel;
}
else if ((pHardware->HwdType == HTYPE_MySensorsUSB) || (pHardware->HwdType == HTYPE_MySensorsTCP) || (pHardware->HwdType == HTYPE_MySensorsMQTT))
{
MySensorsBase *pMyHardware = reinterpret_cast<MySensorsBase*>(pHardware);
root["result"][ii]["version"] = pMyHardware->GetGatewayVersion();
}
else if ((pHardware->HwdType == HTYPE_OpenThermGateway) || (pHardware->HwdType == HTYPE_OpenThermGatewayTCP))
{
OTGWBase *pMyHardware = reinterpret_cast<OTGWBase*>(pHardware);
root["result"][ii]["version"] = pMyHardware->m_Version;
}
else if ((pHardware->HwdType == HTYPE_RFLINKUSB) || (pHardware->HwdType == HTYPE_RFLINKTCP))
{
CRFLinkBase *pMyHardware = reinterpret_cast<CRFLinkBase*>(pHardware);
root["result"][ii]["version"] = pMyHardware->m_Version;
}
else
{
#ifdef WITH_OPENZWAVE
if (pHardware->HwdType == HTYPE_OpenZWave)
{
COpenZWave *pOZWHardware = reinterpret_cast<COpenZWave*>(pHardware);
root["result"][ii]["version"] = pOZWHardware->GetVersionLong();
root["result"][ii]["NodesQueried"] = (pOZWHardware->m_awakeNodesQueried || pOZWHardware->m_allNodesQueried);
}
#endif
}
}
ii++;
}
}
}
void CWebServer::RType_Devices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string rfilter = request::findValue(&req, "filter");
std::string order = request::findValue(&req, "order");
std::string rused = request::findValue(&req, "used");
std::string rid = request::findValue(&req, "rid");
std::string planid = request::findValue(&req, "plan");
std::string floorid = request::findValue(&req, "floor");
std::string sDisplayHidden = request::findValue(&req, "displayhidden");
std::string sFetchFavorites = request::findValue(&req, "favorite");
std::string sDisplayDisabled = request::findValue(&req, "displaydisabled");
bool bDisplayHidden = (sDisplayHidden == "1");
bool bFetchFavorites = (sFetchFavorites == "1");
int HideDisabledHardwareSensors = 0;
m_sql.GetPreferencesVar("HideDisabledHardwareSensors", HideDisabledHardwareSensors);
bool bDisabledDisabled = (HideDisabledHardwareSensors == 0);
if (sDisplayDisabled == "1")
bDisabledDisabled = true;
std::string sLastUpdate = request::findValue(&req, "lastupdate");
std::string hwidx = request::findValue(&req, "hwidx"); // OTO
time_t LastUpdate = 0;
if (sLastUpdate != "")
{
std::stringstream sstr;
sstr << sLastUpdate;
sstr >> LastUpdate;
}
root["status"] = "OK";
root["title"] = "Devices";
root["app_version"] = szAppVersion;
GetJSonDevices(root, rused, rfilter, order, rid, planid, floorid, bDisplayHidden, bDisabledDisabled, bFetchFavorites, LastUpdate, session.username, hwidx);
}
void CWebServer::RType_Users(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
urights = static_cast<int>(m_users[iUser].userrights);
}
if (urights < 2)
return;
root["status"] = "OK";
root["title"] = "Users";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Active, Username, Password, Rights, RemoteSharing, TabsEnabled FROM USERS ORDER BY ID ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Enabled"] = (sd[1] == "1") ? "true" : "false";
root["result"][ii]["Username"] = base64_decode(sd[2]);
root["result"][ii]["Password"] = sd[3];
root["result"][ii]["Rights"] = atoi(sd[4].c_str());
root["result"][ii]["RemoteSharing"] = atoi(sd[5].c_str());
root["result"][ii]["TabsEnabled"] = atoi(sd[6].c_str());
ii++;
}
}
}
void CWebServer::RType_Mobiles(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
urights = static_cast<int>(m_users[iUser].userrights);
}
if (urights < 2)
return;
root["status"] = "OK";
root["title"] = "Mobiles";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Active, Name, UUID, LastUpdate, DeviceType FROM MobileDevices ORDER BY Name ASC");
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Enabled"] = (sd[1] == "1") ? "true" : "false";
root["result"][ii]["Name"] = sd[2];
root["result"][ii]["UUID"] = sd[3];
root["result"][ii]["LastUpdate"] = sd[4];
root["result"][ii]["DeviceType"] = sd[5];
ii++;
}
}
}
void CWebServer::Cmd_SetSetpoint(WebEmSession & session, const request& req, Json::Value &root)
{
bool bHaveUser = (session.username != "");
int iUser = -1;
int urights = 3;
if (bHaveUser)
{
iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
}
}
if (urights < 1)
return;
std::string idx = request::findValue(&req, "idx");
std::string setpoint = request::findValue(&req, "setpoint");
if (
(idx.empty()) ||
(setpoint.empty())
)
return;
root["status"] = "OK";
root["title"] = "SetSetpoint";
if (iUser != -1)
{
_log.Log(LOG_STATUS, "User: %s initiated a SetPoint command", m_users[iUser].Username.c_str());
}
m_mainworker.SetSetPoint(idx, static_cast<float>(atof(setpoint.c_str())));
}
void CWebServer::Cmd_GetSceneActivations(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetSceneActivations";
std::vector<std::vector<std::string> > result, result2;
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID==%q)", idx.c_str());
if (result.empty())
return;
int ii = 0;
std::string Activators = result[0][0];
int SceneType = atoi(result[0][1].c_str());
if (!Activators.empty())
{
//Get Activator device names
std::vector<std::string> arrayActivators;
StringSplit(Activators, ";", arrayActivators);
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
int sCode = 0;
if (arrayCode.size() == 2)
{
sCode = atoi(arrayCode[1].c_str());
}
result2 = m_sql.safe_query("SELECT Name, [Type], SubType, SwitchType FROM DeviceStatus WHERE (ID==%q)", sID.c_str());
if (!result2.empty())
{
std::vector<std::string> sd = result2[0];
std::string lstatus = "-";
if ((SceneType == 0) && (arrayCode.size() == 2))
{
unsigned char devType = (unsigned char)atoi(sd[1].c_str());
unsigned char subType = (unsigned char)atoi(sd[2].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(sd[3].c_str());
int nValue = sCode;
std::string sValue = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(devType, subType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
}
uint64_t dID = std::strtoull(sID.c_str(), nullptr, 10);
root["result"][ii]["idx"] = dID;
root["result"][ii]["name"] = sd[0];
root["result"][ii]["code"] = sCode;
root["result"][ii]["codestr"] = lstatus;
ii++;
}
}
}
}
void CWebServer::Cmd_AddSceneCode(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sceneidx = request::findValue(&req, "sceneidx");
std::string idx = request::findValue(&req, "idx");
std::string cmnd = request::findValue(&req, "cmnd");
if (
(sceneidx.empty()) ||
(idx.empty()) ||
(cmnd.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddSceneCode";
//First check if we do not already have this device as activation code
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID==%q)", sceneidx.c_str());
if (result.empty())
return;
std::string Activators = result[0][0];
unsigned char scenetype = atoi(result[0][1].c_str());
if (!Activators.empty())
{
//Get Activator device names
std::vector<std::string> arrayActivators;
StringSplit(Activators, ";", arrayActivators);
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
std::string sCode = "";
if (arrayCode.size() == 2)
{
sCode = arrayCode[1];
}
if (sID == idx)
{
if (scenetype == 1)
return; //Group does not work with separate codes, so already there
if (sCode == cmnd)
return; //same code, already there!
}
}
}
if (!Activators.empty())
Activators += ";";
Activators += idx;
if (scenetype == 0)
{
Activators += ":" + cmnd;
}
m_sql.safe_query("UPDATE Scenes SET Activators='%q' WHERE (ID==%q)", Activators.c_str(), sceneidx.c_str());
}
void CWebServer::Cmd_RemoveSceneCode(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sceneidx = request::findValue(&req, "sceneidx");
std::string idx = request::findValue(&req, "idx");
std::string code = request::findValue(&req, "code");
if (
(idx.empty()) ||
(sceneidx.empty()) ||
(code.empty())
)
return;
root["status"] = "OK";
root["title"] = "RemoveSceneCode";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID==%q)", sceneidx.c_str());
if (result.empty())
return;
std::string Activators = result[0][0];
int SceneType = atoi(result[0][1].c_str());
if (!Activators.empty())
{
//Get Activator device names
std::vector<std::string> arrayActivators;
StringSplit(Activators, ";", arrayActivators);
std::string newActivation = "";
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
std::string sCode = "";
if (arrayCode.size() == 2)
{
sCode = arrayCode[1];
}
bool bFound = false;
if (sID == idx)
{
if ((SceneType == 1) || (sCode.empty()))
{
bFound = true;
}
else
{
//Also check the code
bFound = (sCode == code);
}
}
if (!bFound)
{
if (!newActivation.empty())
newActivation += ";";
newActivation += sID;
if ((SceneType == 0) && (!sCode.empty()))
{
newActivation += ":" + sCode;
}
}
}
if (Activators != newActivation)
{
m_sql.safe_query("UPDATE Scenes SET Activators='%q' WHERE (ID==%q)", newActivation.c_str(), sceneidx.c_str());
}
}
}
void CWebServer::Cmd_ClearSceneCodes(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sceneidx = request::findValue(&req, "sceneidx");
if (sceneidx.empty())
return;
root["status"] = "OK";
root["title"] = "ClearSceneCode";
m_sql.safe_query("UPDATE Scenes SET Activators='' WHERE (ID==%q)", sceneidx.c_str());
}
void CWebServer::Cmd_GetSerialDevices(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetSerialDevices";
bool bUseDirectPath = false;
std::vector<std::string> serialports = GetSerialPorts(bUseDirectPath);
int ii = 0;
for (const auto & itt : serialports)
{
root["result"][ii]["name"] = itt;
root["result"][ii]["value"] = ii;
ii++;
}
}
void CWebServer::Cmd_GetDevicesList(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetDevicesList";
int ii = 0;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name FROM DeviceStatus WHERE (Used == 1) ORDER BY Name");
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["name"] = sd[1];
root["result"][ii]["value"] = sd[0];
ii++;
}
}
}
void CWebServer::Post_UploadCustomIcon(WebEmSession & session, const request& req, reply & rep)
{
Json::Value root;
root["title"] = "UploadCustomIcon";
root["status"] = "ERROR";
root["error"] = "Invalid";
//Only admin user allowed
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string zipfile = request::findValue(&req, "file");
if (zipfile != "")
{
std::string ErrorMessage;
bool bOK = m_sql.InsertCustomIconFromZip(zipfile, ErrorMessage);
if (bOK)
{
root["status"] = "OK";
}
else
{
root["status"] = "ERROR";
root["error"] = ErrorMessage;
}
}
std::string jcallback = request::findValue(&req, "jsoncallback");
if (jcallback.size() == 0) {
reply::set_content(&rep, root.toStyledString());
return;
}
reply::set_content(&rep, "var data=" + root.toStyledString() + '\n' + jcallback + "(data);");
}
void CWebServer::Cmd_GetCustomIconSet(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetCustomIconSet";
int ii = 0;
for (const auto & itt : m_custom_light_icons)
{
if (itt.idx >= 100)
{
std::string IconFile16 = "images/" + itt.RootFile + ".png";
std::string IconFile48On = "images/" + itt.RootFile + "48_On.png";
std::string IconFile48Off = "images/" + itt.RootFile + "48_Off.png";
root["result"][ii]["idx"] = itt.idx - 100;
root["result"][ii]["Title"] = itt.Title;
root["result"][ii]["Description"] = itt.Description;
root["result"][ii]["IconFile16"] = IconFile16;
root["result"][ii]["IconFile48On"] = IconFile48On;
root["result"][ii]["IconFile48Off"] = IconFile48Off;
ii++;
}
}
}
void CWebServer::Cmd_DeleteCustomIcon(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
if (sidx.empty())
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "DeleteCustomIcon";
m_sql.safe_query("DELETE FROM CustomImages WHERE (ID == %d)", idx);
//Delete icons file from disk
for (const auto & itt : m_custom_light_icons)
{
if (itt.idx == idx + 100)
{
std::string IconFile16 = szWWWFolder + "/images/" + itt.RootFile + ".png";
std::string IconFile48On = szWWWFolder + "/images/" + itt.RootFile + "48_On.png";
std::string IconFile48Off = szWWWFolder + "/images/" + itt.RootFile + "48_Off.png";
std::remove(IconFile16.c_str());
std::remove(IconFile48On.c_str());
std::remove(IconFile48Off.c_str());
break;
}
}
ReloadCustomSwitchIcons();
}
void CWebServer::Cmd_UpdateCustomIcon(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string sname = request::findValue(&req, "name");
std::string sdescription = request::findValue(&req, "description");
if (
(sidx.empty()) ||
(sname.empty()) ||
(sdescription.empty())
)
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "UpdateCustomIcon";
m_sql.safe_query("UPDATE CustomImages SET Name='%q', Description='%q' WHERE (ID == %d)", sname.c_str(), sdescription.c_str(), idx);
ReloadCustomSwitchIcons();
}
void CWebServer::Cmd_RenameDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string sname = request::findValue(&req, "name");
if (
(sidx.empty()) ||
(sname.empty())
)
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "RenameDevice";
m_sql.safe_query("UPDATE DeviceStatus SET Name='%q' WHERE (ID == %d)", sname.c_str(), idx);
uint64_t ullidx = std::strtoull(sidx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.WWWUpdateSingleState(ullidx, sname, m_mainworker.m_eventsystem.REASON_DEVICE);
#ifdef ENABLE_PYTHON
// Notify plugin framework about the change
m_mainworker.m_pluginsystem.DeviceModified(idx);
#endif
}
void CWebServer::Cmd_RenameScene(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string sname = request::findValue(&req, "name");
if (
(sidx.empty()) ||
(sname.empty())
)
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "RenameScene";
m_sql.safe_query("UPDATE Scenes SET Name='%q' WHERE (ID == %d)", sname.c_str(), idx);
uint64_t ullidx = std::strtoull(sidx.c_str(), nullptr, 10);
m_mainworker.m_eventsystem.WWWUpdateSingleState(ullidx, sname, m_mainworker.m_eventsystem.REASON_SCENEGROUP);
}
void CWebServer::Cmd_SetUnused(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
if (sidx.empty())
return;
int idx = atoi(sidx.c_str());
root["status"] = "OK";
root["title"] = "SetUnused";
m_sql.safe_query("UPDATE DeviceStatus SET Used=0 WHERE (ID == %d)", idx);
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.RemoveSingleState(idx, m_mainworker.m_eventsystem.REASON_DEVICE);
#ifdef ENABLE_PYTHON
// Notify plugin framework about the change
m_mainworker.m_pluginsystem.DeviceModified(idx);
#endif
}
void CWebServer::Cmd_AddLogMessage(WebEmSession & session, const request& req, Json::Value &root)
{
std::string smessage = request::findValue(&req, "message");
if (smessage.empty())
return;
root["status"] = "OK";
root["title"] = "AddLogMessage";
_log.Log(LOG_STATUS, "%s", smessage.c_str());
}
void CWebServer::Cmd_ClearShortLog(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "ClearShortLog";
_log.Log(LOG_STATUS, "Clearing Short Log...");
m_sql.ClearShortLog();
_log.Log(LOG_STATUS, "Short Log Cleared!");
}
void CWebServer::Cmd_VacuumDatabase(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
root["status"] = "OK";
root["title"] = "VacuumDatabase";
m_sql.VacuumDatabase();
}
void CWebServer::Cmd_AddMobileDevice(WebEmSession & session, const request& req, Json::Value &root)
{
std::string suuid = request::findValue(&req, "uuid");
std::string ssenderid = request::findValue(&req, "senderid");
std::string sname = request::findValue(&req, "name");
std::string sdevtype = request::findValue(&req, "devicetype");
std::string sactive = request::findValue(&req, "active");
if (
(suuid.empty()) ||
(ssenderid.empty())
)
return;
root["status"] = "OK";
root["title"] = "AddMobileDevice";
if (sactive.empty())
sactive = "1";
int iActive = (sactive == "1") ? 1 : 0;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID, Name, DeviceType FROM MobileDevices WHERE (UUID=='%q')", suuid.c_str());
if (result.empty())
{
//New
m_sql.safe_query("INSERT INTO MobileDevices (Active,UUID,SenderID,Name,DeviceType) VALUES (%d,'%q','%q','%q','%q')",
iActive,
suuid.c_str(),
ssenderid.c_str(),
sname.c_str(),
sdevtype.c_str());
}
else
{
//Update
time_t now = mytime(NULL);
struct tm ltime;
localtime_r(&now, <ime);
m_sql.safe_query("UPDATE MobileDevices SET Active=%d, SenderID='%q', LastUpdate='%04d-%02d-%02d %02d:%02d:%02d' WHERE (UUID == '%q')",
iActive,
ssenderid.c_str(),
ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday, ltime.tm_hour, ltime.tm_min, ltime.tm_sec,
suuid.c_str()
);
std::string dname = result[0][1];
std::string ddevtype = result[0][2];
if (dname.empty() || ddevtype.empty())
{
m_sql.safe_query("UPDATE MobileDevices SET Name='%q', DeviceType='%q' WHERE (UUID == '%q')",
sname.c_str(), sdevtype.c_str(),
suuid.c_str()
);
}
}
}
void CWebServer::Cmd_UpdateMobileDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string enabled = request::findValue(&req, "enabled");
std::string name = request::findValue(&req, "name");
if (
(sidx.empty()) ||
(enabled.empty()) ||
(name.empty())
)
return;
uint64_t idx = std::strtoull(sidx.c_str(), nullptr, 10);
m_sql.safe_query("UPDATE MobileDevices SET Name='%q', Active=%d WHERE (ID==%" PRIu64 ")",
name.c_str(), (enabled == "true") ? 1 : 0, idx);
root["status"] = "OK";
root["title"] = "UpdateMobile";
}
void CWebServer::Cmd_DeleteMobileDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string suuid = request::findValue(&req, "uuid");
if (suuid.empty())
return;
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT ID FROM MobileDevices WHERE (UUID=='%q')", suuid.c_str());
if (result.empty())
return;
m_sql.safe_query("DELETE FROM MobileDevices WHERE (UUID == '%q')", suuid.c_str());
root["status"] = "OK";
root["title"] = "DeleteMobileDevice";
}
void CWebServer::RType_GetTransfers(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "GetTransfers";
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type, SubType FROM DeviceStatus WHERE (ID==%" PRIu64 ")",
idx);
if (!result.empty())
{
int dType = atoi(result[0][0].c_str());
if (
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_HUM)
)
{
result = m_sql.safe_query(
"SELECT ID, Name FROM DeviceStatus WHERE (Type=='%q') AND (ID!=%" PRIu64 ")",
result[0][0].c_str(), idx);
}
else
{
result = m_sql.safe_query(
"SELECT ID, Name FROM DeviceStatus WHERE (Type=='%q') AND (SubType=='%q') AND (ID!=%" PRIu64 ")",
result[0][0].c_str(), result[0][1].c_str(), idx);
}
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Name"] = sd[1];
ii++;
}
}
}
//Will transfer Newest sensor log to OLD sensor,
//then set the HardwareID/DeviceID/Unit/Name/Type/Subtype/Unit for the OLD sensor to the NEW sensor ID/Type/Subtype/Unit
//then delete the NEW sensor
void CWebServer::RType_TransferDevice(WebEmSession & session, const request& req, Json::Value &root)
{
std::string sidx = request::findValue(&req, "idx");
if (sidx.empty())
return;
std::string newidx = request::findValue(&req, "newidx");
if (newidx.empty())
return;
std::vector<std::vector<std::string> > result;
//Check which device is newer
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
struct tm LastUpdateTime_A;
struct tm LastUpdateTime_B;
result = m_sql.safe_query(
"SELECT A.LastUpdate, B.LastUpdate FROM DeviceStatus as A, DeviceStatus as B WHERE (A.ID == '%q') AND (B.ID == '%q')",
sidx.c_str(), newidx.c_str());
if (result.empty())
return;
std::string sLastUpdate_A = result[0][0];
std::string sLastUpdate_B = result[0][1];
time_t timeA, timeB;
ParseSQLdatetime(timeA, LastUpdateTime_A, sLastUpdate_A, tm1.tm_isdst);
ParseSQLdatetime(timeB, LastUpdateTime_B, sLastUpdate_B, tm1.tm_isdst);
if (timeA < timeB)
{
//Swap idx with newidx
sidx.swap(newidx);
}
result = m_sql.safe_query(
"SELECT HardwareID, DeviceID, Unit, Name, Type, SubType, SignalLevel, BatteryLevel, nValue, sValue FROM DeviceStatus WHERE (ID == '%q')",
newidx.c_str());
if (result.empty())
return;
root["status"] = "OK";
root["title"] = "TransferDevice";
//transfer device logs (new to old)
m_sql.TransferDevice(newidx, sidx);
//now delete the NEW device
m_sql.DeleteDevices(newidx);
m_mainworker.m_scheduler.ReloadSchedules();
}
void CWebServer::RType_Notifications(WebEmSession & session, const request& req, Json::Value &root)
{
root["status"] = "OK";
root["title"] = "Notifications";
int ii = 0;
//Add known notification systems
for (const auto & ittNotifiers : m_notifications.m_notifiers)
{
root["notifiers"][ii]["name"] = ittNotifiers.first;
root["notifiers"][ii]["description"] = ittNotifiers.first;
ii++;
}
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<_tNotification> notifications = m_notifications.GetNotifications(idx);
if (notifications.size() > 0)
{
ii = 0;
for (const auto & itt : notifications)
{
root["result"][ii]["idx"] = itt.ID;
std::string sParams = itt.Params;
if (sParams.empty()) {
sParams = "S";
}
root["result"][ii]["Params"] = sParams;
root["result"][ii]["Priority"] = itt.Priority;
root["result"][ii]["SendAlways"] = itt.SendAlways;
root["result"][ii]["CustomMessage"] = itt.CustomMessage;
root["result"][ii]["ActiveSystems"] = itt.ActiveSystems;
ii++;
}
}
}
void CWebServer::RType_GetSharedUserDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetSharedUserDevices";
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == '%q')", idx.c_str());
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["DeviceRowIdx"] = sd[0];
ii++;
}
}
}
void CWebServer::RType_SetSharedUserDevices(WebEmSession & session, const request& req, Json::Value &root)
{
std::string idx = request::findValue(&req, "idx");
std::string userdevices = request::findValue(&req, "devices");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "SetSharedUserDevices";
std::vector<std::string> strarray;
StringSplit(userdevices, ";", strarray);
//First delete all devices for this user, then add the (new) onces
m_sql.safe_query("DELETE FROM SharedDevices WHERE (SharedUserID == '%q')", idx.c_str());
int nDevices = static_cast<int>(strarray.size());
for (int ii = 0; ii < nDevices; ii++)
{
m_sql.safe_query("INSERT INTO SharedDevices (SharedUserID,DeviceRowID) VALUES ('%q','%q')", idx.c_str(), strarray[ii].c_str());
}
LoadUsers();
}
void CWebServer::RType_SetUsed(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
std::string deviceid = request::findValue(&req, "deviceid");
std::string name = request::findValue(&req, "name");
std::string description = request::findValue(&req, "description");
std::string sused = request::findValue(&req, "used");
std::string sswitchtype = request::findValue(&req, "switchtype");
std::string maindeviceidx = request::findValue(&req, "maindeviceidx");
std::string addjvalue = request::findValue(&req, "addjvalue");
std::string addjmulti = request::findValue(&req, "addjmulti");
std::string addjvalue2 = request::findValue(&req, "addjvalue2");
std::string addjmulti2 = request::findValue(&req, "addjmulti2");
std::string setPoint = request::findValue(&req, "setpoint");
std::string state = request::findValue(&req, "state");
std::string mode = request::findValue(&req, "mode");
std::string until = request::findValue(&req, "until");
std::string clock = request::findValue(&req, "clock");
std::string tmode = request::findValue(&req, "tmode");
std::string fmode = request::findValue(&req, "fmode");
std::string sCustomImage = request::findValue(&req, "customimage");
std::string strunit = request::findValue(&req, "unit");
std::string strParam1 = base64_decode(request::findValue(&req, "strparam1"));
std::string strParam2 = base64_decode(request::findValue(&req, "strparam2"));
std::string tmpstr = request::findValue(&req, "protected");
bool bHasstrParam1 = request::hasValue(&req, "strparam1");
int iProtected = (tmpstr == "true") ? 1 : 0;
std::string sOptions = base64_decode(request::findValue(&req, "options"));
std::string devoptions = CURLEncode::URLDecode(request::findValue(&req, "devoptions"));
std::string EnergyMeterMode = CURLEncode::URLDecode(request::findValue(&req, "EnergyMeterMode"));
char szTmp[200];
bool bHaveUser = (session.username != "");
int iUser = -1;
if (bHaveUser)
{
iUser = FindUser(session.username.c_str());
}
int switchtype = -1;
if (sswitchtype != "")
switchtype = atoi(sswitchtype.c_str());
if ((idx.empty()) || (sused.empty()))
return;
int used = (sused == "true") ? 1 : 0;
if (maindeviceidx != "")
used = 0;
int CustomImage = 0;
if (sCustomImage != "")
CustomImage = atoi(sCustomImage.c_str());
//Strip trailing spaces in 'name'
name = stdstring_trim(name);
//Strip trailing spaces in 'description'
description = stdstring_trim(description);
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type,SubType,HardwareID FROM DeviceStatus WHERE (ID == '%q')", idx.c_str());
if (result.empty())
return;
std::vector<std::string> sd = result[0];
unsigned char dType = atoi(sd[0].c_str());
//unsigned char dSubType=atoi(sd[1].c_str());
int HwdID = atoi(sd[2].c_str());
std::string sHwdID = sd[2];
if (setPoint != "" || state != "")
{
double tempcelcius = atof(setPoint.c_str());
if (m_sql.m_tempunit == TEMPUNIT_F)
{
//Convert back to Celsius
tempcelcius = ConvertToCelsius(tempcelcius);
}
sprintf(szTmp, "%.2f", tempcelcius);
if (dType != pTypeEvohomeZone && dType != pTypeEvohomeWater)//sql update now done in setsetpoint for evohome devices
{
m_sql.safe_query("UPDATE DeviceStatus SET Used=%d, sValue='%q' WHERE (ID == '%q')",
used, szTmp, idx.c_str());
}
}
if (name.empty())
{
m_sql.safe_query("UPDATE DeviceStatus SET Used=%d WHERE (ID == '%q')",
used, idx.c_str());
}
else
{
if (switchtype == -1)
{
m_sql.safe_query("UPDATE DeviceStatus SET Used=%d, Name='%q', Description='%q' WHERE (ID == '%q')",
used, name.c_str(), description.c_str(), idx.c_str());
}
else
{
m_sql.safe_query(
"UPDATE DeviceStatus SET Used=%d, Name='%q', Description='%q', SwitchType=%d, CustomImage=%d WHERE (ID == '%q')",
used, name.c_str(), description.c_str(), switchtype, CustomImage, idx.c_str());
}
}
if (bHasstrParam1)
{
m_sql.safe_query("UPDATE DeviceStatus SET StrParam1='%q', StrParam2='%q' WHERE (ID == '%q')",
strParam1.c_str(), strParam2.c_str(), idx.c_str());
}
m_sql.safe_query("UPDATE DeviceStatus SET Protected=%d WHERE (ID == '%q')", iProtected, idx.c_str());
if (!setPoint.empty() || !state.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a SetPoint command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
if (dType == pTypeEvohomeWater)
m_mainworker.SetSetPoint(idx, (state == "On") ? 1.0f : 0.0f, mode, until);//FIXME float not guaranteed precise?
else if (dType == pTypeEvohomeZone)
m_mainworker.SetSetPoint(idx, static_cast<float>(atof(setPoint.c_str())), mode, until);
else
m_mainworker.SetSetPoint(idx, static_cast<float>(atof(setPoint.c_str())));
}
else if (!clock.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a SetClock command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
m_mainworker.SetClock(idx, clock);
}
else if (!tmode.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a Thermostat Mode command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
m_mainworker.SetZWaveThermostatMode(idx, atoi(tmode.c_str()));
}
else if (!fmode.empty())
{
int urights = 3;
if (bHaveUser)
{
int iUser = FindUser(session.username.c_str());
if (iUser != -1)
{
urights = static_cast<int>(m_users[iUser].userrights);
_log.Log(LOG_STATUS, "User: %s initiated a Thermostat Fan Mode command", m_users[iUser].Username.c_str());
}
}
if (urights < 1)
return;
m_mainworker.SetZWaveThermostatFanMode(idx, atoi(fmode.c_str()));
}
if (!strunit.empty())
{
bool bUpdateUnit = true;
#ifdef ENABLE_PYTHON
//check if HW is plugin
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT Type FROM Hardware WHERE (ID == %d)", HwdID);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
_eHardwareTypes Type = (_eHardwareTypes)atoi(sd[0].c_str());
if (Type == HTYPE_PythonPlugin)
{
bUpdateUnit = false;
_log.Log(LOG_ERROR, "CWebServer::RType_SetUsed: Not allowed to change unit of device owned by plugin %u!", HwdID);
}
}
#endif
if (bUpdateUnit)
{
m_sql.safe_query("UPDATE DeviceStatus SET Unit='%q' WHERE (ID == '%q')",
strunit.c_str(), idx.c_str());
}
}
//FIXME evohome ...we need the zone id to update the correct zone...but this should be ok as a generic call?
if (!deviceid.empty())
{
m_sql.safe_query("UPDATE DeviceStatus SET DeviceID='%q' WHERE (ID == '%q')",
deviceid.c_str(), idx.c_str());
}
if (!addjvalue.empty())
{
double faddjvalue = atof(addjvalue.c_str());
m_sql.safe_query("UPDATE DeviceStatus SET AddjValue=%f WHERE (ID == '%q')",
faddjvalue, idx.c_str());
}
if (!addjmulti.empty())
{
double faddjmulti = atof(addjmulti.c_str());
if (faddjmulti == 0)
faddjmulti = 1;
m_sql.safe_query("UPDATE DeviceStatus SET AddjMulti=%f WHERE (ID == '%q')",
faddjmulti, idx.c_str());
}
if (!addjvalue2.empty())
{
double faddjvalue2 = atof(addjvalue2.c_str());
m_sql.safe_query("UPDATE DeviceStatus SET AddjValue2=%f WHERE (ID == '%q')",
faddjvalue2, idx.c_str());
}
if (!addjmulti2.empty())
{
double faddjmulti2 = atof(addjmulti2.c_str());
if (faddjmulti2 == 0)
faddjmulti2 = 1;
m_sql.safe_query("UPDATE DeviceStatus SET AddjMulti2=%f WHERE (ID == '%q')",
faddjmulti2, idx.c_str());
}
if (!EnergyMeterMode.empty())
{
auto options = m_sql.GetDeviceOptions(idx);
options["EnergyMeterMode"] = EnergyMeterMode;
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_sql.SetDeviceOptions(ullidx, options);
}
if (!devoptions.empty())
{
m_sql.safe_query("UPDATE DeviceStatus SET Options='%q' WHERE (ID == '%q')", devoptions.c_str(), idx.c_str());
}
if (used == 0)
{
bool bRemoveSubDevices = (request::findValue(&req, "RemoveSubDevices") == "true");
if (bRemoveSubDevices)
{
//if this device was a slave device, remove it
m_sql.safe_query("DELETE FROM LightSubDevices WHERE (DeviceRowID == '%q')", idx.c_str());
}
m_sql.safe_query("DELETE FROM LightSubDevices WHERE (ParentID == '%q')", idx.c_str());
m_sql.safe_query("DELETE FROM Timers WHERE (DeviceRowID == '%q')", idx.c_str());
}
// Save device options
if (!sOptions.empty())
{
uint64_t ullidx = std::strtoull(idx.c_str(), nullptr, 10);
m_sql.SetDeviceOptions(ullidx, m_sql.BuildDeviceOptions(sOptions, false));
}
if (maindeviceidx != "")
{
if (maindeviceidx != idx)
{
//this is a sub device for another light/switch
//first check if it is not already a sub device
result = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q') AND (ParentID =='%q')",
idx.c_str(), maindeviceidx.c_str());
if (result.empty())
{
//no it is not, add it
m_sql.safe_query(
"INSERT INTO LightSubDevices (DeviceRowID, ParentID) VALUES ('%q','%q')",
idx.c_str(),
maindeviceidx.c_str()
);
}
}
}
if ((used == 0) && (maindeviceidx.empty()))
{
//really remove it, including log etc
m_sql.DeleteDevices(idx);
}
else
{
#ifdef ENABLE_PYTHON
// Notify plugin framework about the change
m_mainworker.m_pluginsystem.DeviceModified(atoi(idx.c_str()));
#endif
}
if (!result.empty())
{
root["status"] = "OK";
root["title"] = "SetUsed";
}
if (m_sql.m_bEnableEventSystem)
m_mainworker.m_eventsystem.GetCurrentStates();
}
void CWebServer::RType_Settings(WebEmSession & session, const request& req, Json::Value &root)
{
std::vector<std::vector<std::string> > result;
char szTmp[100];
result = m_sql.safe_query("SELECT Key, nValue, sValue FROM Preferences");
if (result.empty())
return;
root["status"] = "OK";
root["title"] = "settings";
#ifndef NOCLOUD
root["cloudenabled"] = true;
#else
root["cloudenabled"] = false;
#endif
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string Key = sd[0];
int nValue = atoi(sd[1].c_str());
std::string sValue = sd[2];
if (Key == "Location")
{
std::vector<std::string> strarray;
StringSplit(sValue, ";", strarray);
if (strarray.size() == 2)
{
root["Location"]["Latitude"] = strarray[0];
root["Location"]["Longitude"] = strarray[1];
}
}
/* RK: notification settings */
if (m_notifications.IsInConfig(Key)) {
if (sValue.empty() && nValue > 0) {
root[Key] = nValue;
}
else {
root[Key] = sValue;
}
}
else if (Key == "DashboardType")
{
root["DashboardType"] = nValue;
}
else if (Key == "MobileType")
{
root["MobileType"] = nValue;
}
else if (Key == "LightHistoryDays")
{
root["LightHistoryDays"] = nValue;
}
else if (Key == "5MinuteHistoryDays")
{
root["ShortLogDays"] = nValue;
}
else if (Key == "ShortLogInterval")
{
root["ShortLogInterval"] = nValue;
}
else if (Key == "WebUserName")
{
root["WebUserName"] = base64_decode(sValue);
}
//else if (Key == "WebPassword")
//{
// root["WebPassword"] = sValue;
//}
else if (Key == "SecPassword")
{
root["SecPassword"] = sValue;
}
else if (Key == "ProtectionPassword")
{
root["ProtectionPassword"] = sValue;
}
else if (Key == "WebLocalNetworks")
{
root["WebLocalNetworks"] = sValue;
}
else if (Key == "WebRemoteProxyIPs")
{
root["WebRemoteProxyIPs"] = sValue;
}
else if (Key == "RandomTimerFrame")
{
root["RandomTimerFrame"] = nValue;
}
else if (Key == "MeterDividerEnergy")
{
root["EnergyDivider"] = nValue;
}
else if (Key == "MeterDividerGas")
{
root["GasDivider"] = nValue;
}
else if (Key == "MeterDividerWater")
{
root["WaterDivider"] = nValue;
}
else if (Key == "ElectricVoltage")
{
root["ElectricVoltage"] = nValue;
}
else if (Key == "CM113DisplayType")
{
root["CM113DisplayType"] = nValue;
}
else if (Key == "UseAutoUpdate")
{
root["UseAutoUpdate"] = nValue;
}
else if (Key == "UseAutoBackup")
{
root["UseAutoBackup"] = nValue;
}
else if (Key == "Rego6XXType")
{
root["Rego6XXType"] = nValue;
}
else if (Key == "CostEnergy")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergy"] = szTmp;
}
else if (Key == "CostEnergyT2")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergyT2"] = szTmp;
}
else if (Key == "CostEnergyR1")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergyR1"] = szTmp;
}
else if (Key == "CostEnergyR2")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostEnergyR2"] = szTmp;
}
else if (Key == "CostGas")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostGas"] = szTmp;
}
else if (Key == "CostWater")
{
sprintf(szTmp, "%.4f", (float)(nValue) / 10000.0f);
root["CostWater"] = szTmp;
}
else if (Key == "ActiveTimerPlan")
{
root["ActiveTimerPlan"] = nValue;
}
else if (Key == "DoorbellCommand")
{
root["DoorbellCommand"] = nValue;
}
else if (Key == "SmartMeterType")
{
root["SmartMeterType"] = nValue;
}
else if (Key == "EnableTabFloorplans")
{
root["EnableTabFloorplans"] = nValue;
}
else if (Key == "EnableTabLights")
{
root["EnableTabLights"] = nValue;
}
else if (Key == "EnableTabTemp")
{
root["EnableTabTemp"] = nValue;
}
else if (Key == "EnableTabWeather")
{
root["EnableTabWeather"] = nValue;
}
else if (Key == "EnableTabUtility")
{
root["EnableTabUtility"] = nValue;
}
else if (Key == "EnableTabScenes")
{
root["EnableTabScenes"] = nValue;
}
else if (Key == "EnableTabCustom")
{
root["EnableTabCustom"] = nValue;
}
else if (Key == "NotificationSensorInterval")
{
root["NotificationSensorInterval"] = nValue;
}
else if (Key == "NotificationSwitchInterval")
{
root["NotificationSwitchInterval"] = nValue;
}
else if (Key == "RemoteSharedPort")
{
root["RemoteSharedPort"] = nValue;
}
else if (Key == "Language")
{
root["Language"] = sValue;
}
else if (Key == "Title")
{
root["Title"] = sValue;
}
else if (Key == "WindUnit")
{
root["WindUnit"] = nValue;
}
else if (Key == "TempUnit")
{
root["TempUnit"] = nValue;
}
else if (Key == "WeightUnit")
{
root["WeightUnit"] = nValue;
}
else if (Key == "AuthenticationMethod")
{
root["AuthenticationMethod"] = nValue;
}
else if (Key == "ReleaseChannel")
{
root["ReleaseChannel"] = nValue;
}
else if (Key == "RaspCamParams")
{
root["RaspCamParams"] = sValue;
}
else if (Key == "UVCParams")
{
root["UVCParams"] = sValue;
}
else if (Key == "AcceptNewHardware")
{
root["AcceptNewHardware"] = nValue;
}
else if (Key == "HideDisabledHardwareSensors")
{
root["HideDisabledHardwareSensors"] = nValue;
}
else if (Key == "ShowUpdateEffect")
{
root["ShowUpdateEffect"] = nValue;
}
else if (Key == "DegreeDaysBaseTemperature")
{
root["DegreeDaysBaseTemperature"] = sValue;
}
else if (Key == "EnableEventScriptSystem")
{
root["EnableEventScriptSystem"] = nValue;
}
else if (Key == "DisableDzVentsSystem")
{
root["DisableDzVentsSystem"] = nValue;
}
else if (Key == "DzVentsLogLevel")
{
root["DzVentsLogLevel"] = nValue;
}
else if (Key == "LogEventScriptTrigger")
{
root["LogEventScriptTrigger"] = nValue;
}
else if (Key == "(1WireSensorPollPeriod")
{
root["1WireSensorPollPeriod"] = nValue;
}
else if (Key == "(1WireSwitchPollPeriod")
{
root["1WireSwitchPollPeriod"] = nValue;
}
else if (Key == "SecOnDelay")
{
root["SecOnDelay"] = nValue;
}
else if (Key == "AllowWidgetOrdering")
{
root["AllowWidgetOrdering"] = nValue;
}
else if (Key == "FloorplanPopupDelay")
{
root["FloorplanPopupDelay"] = nValue;
}
else if (Key == "FloorplanFullscreenMode")
{
root["FloorplanFullscreenMode"] = nValue;
}
else if (Key == "FloorplanAnimateZoom")
{
root["FloorplanAnimateZoom"] = nValue;
}
else if (Key == "FloorplanShowSensorValues")
{
root["FloorplanShowSensorValues"] = nValue;
}
else if (Key == "FloorplanShowSwitchValues")
{
root["FloorplanShowSwitchValues"] = nValue;
}
else if (Key == "FloorplanShowSceneNames")
{
root["FloorplanShowSceneNames"] = nValue;
}
else if (Key == "FloorplanRoomColour")
{
root["FloorplanRoomColour"] = sValue;
}
else if (Key == "FloorplanActiveOpacity")
{
root["FloorplanActiveOpacity"] = nValue;
}
else if (Key == "FloorplanInactiveOpacity")
{
root["FloorplanInactiveOpacity"] = nValue;
}
else if (Key == "SensorTimeout")
{
root["SensorTimeout"] = nValue;
}
else if (Key == "BatteryLowNotification")
{
root["BatterLowLevel"] = nValue;
}
else if (Key == "WebTheme")
{
root["WebTheme"] = sValue;
}
#ifndef NOCLOUD
else if (Key == "MyDomoticzInstanceId") {
root["MyDomoticzInstanceId"] = sValue;
}
else if (Key == "MyDomoticzUserId") {
root["MyDomoticzUserId"] = sValue;
}
else if (Key == "MyDomoticzPassword") {
root["MyDomoticzPassword"] = sValue;
}
else if (Key == "MyDomoticzSubsystems") {
root["MyDomoticzSubsystems"] = nValue;
}
#endif
else if (Key == "MyDomoticzSubsystems") {
root["MyDomoticzSubsystems"] = nValue;
}
else if (Key == "SendErrorsAsNotification") {
root["SendErrorsAsNotification"] = nValue;
}
else if (Key == "DeltaTemperatureLog") {
root[Key] = sValue;
}
else if (Key == "IFTTTEnabled") {
root["IFTTTEnabled"] = nValue;
}
else if (Key == "IFTTTAPI") {
root["IFTTTAPI"] = sValue;
}
}
}
void CWebServer::RType_LightLog(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
//First get Device Type/SubType
result = m_sql.safe_query("SELECT Type, SubType, SwitchType, Options FROM DeviceStatus WHERE (ID == %" PRIu64 ")",
idx);
if (result.empty())
return;
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(result[0][2].c_str());
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(result[0][3].c_str());
if (
(dType != pTypeLighting1) &&
(dType != pTypeLighting2) &&
(dType != pTypeLighting3) &&
(dType != pTypeLighting4) &&
(dType != pTypeLighting5) &&
(dType != pTypeLighting6) &&
(dType != pTypeFan) &&
(dType != pTypeColorSwitch) &&
(dType != pTypeSecurity1) &&
(dType != pTypeSecurity2) &&
(dType != pTypeEvohome) &&
(dType != pTypeEvohomeRelay) &&
(dType != pTypeCurtain) &&
(dType != pTypeBlinds) &&
(dType != pTypeRFY) &&
(dType != pTypeRego6XXValue) &&
(dType != pTypeChime) &&
(dType != pTypeThermostat2) &&
(dType != pTypeThermostat3) &&
(dType != pTypeThermostat4) &&
(dType != pTypeRemote) &&
(dType != pTypeGeneralSwitch) &&
(dType != pTypeHomeConfort) &&
(dType != pTypeFS20) &&
(!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)))
)
return; //no light device! we should not be here!
root["status"] = "OK";
root["title"] = "LightLog";
result = m_sql.safe_query("SELECT ROWID, nValue, sValue, Date FROM LightingLog WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date DESC", idx);
if (!result.empty())
{
std::map<std::string, std::string> selectorStatuses;
if (switchtype == STYPE_Selector) {
GetSelectorSwitchStatuses(options, selectorStatuses);
}
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int nValue = atoi(sd[1].c_str());
std::string sValue = sd[2];
//skip 0-values in log for MediaPlayers
if ((switchtype == STYPE_Media) && (sValue == "0")) continue;
root["result"][ii]["idx"] = sd[0];
//add light details
std::string lstatus = "";
std::string ldata = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveSelector = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
if (switchtype == STYPE_Media) {
lstatus = sValue;
ldata = lstatus;
}
else if (switchtype == STYPE_Selector)
{
if (ii == 0) {
bHaveSelector = true;
maxDimLevel = selectorStatuses.size();
}
if (!selectorStatuses.empty()) {
std::string sLevel = selectorStatuses[sValue];
ldata = sLevel;
lstatus = "Set Level: " + sLevel;
llevel = atoi(sValue.c_str());
}
}
else {
GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
ldata = lstatus;
}
if (ii == 0)
{
root["HaveDimmer"] = bHaveDimmer;
root["result"][ii]["MaxDimLevel"] = maxDimLevel;
root["HaveGroupCmd"] = bHaveGroupCmd;
root["HaveSelector"] = bHaveSelector;
}
root["result"][ii]["Date"] = sd[3];
root["result"][ii]["Data"] = ldata;
root["result"][ii]["Status"] = lstatus;
root["result"][ii]["Level"] = llevel;
ii++;
}
}
}
void CWebServer::RType_TextLog(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
root["status"] = "OK";
root["title"] = "TextLog";
result = m_sql.safe_query("SELECT ROWID, sValue, Date FROM LightingLog WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date DESC",
idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Date"] = sd[2];
root["result"][ii]["Data"] = sd[1];
ii++;
}
}
}
void CWebServer::RType_SceneLog(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
root["status"] = "OK";
root["title"] = "SceneLog";
result = m_sql.safe_query("SELECT ROWID, nValue, Date FROM SceneLog WHERE (SceneRowID==%" PRIu64 ") ORDER BY Date DESC", idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
int nValue = atoi(sd[1].c_str());
root["result"][ii]["idx"] = sd[0];
root["result"][ii]["Date"] = sd[2];
root["result"][ii]["Data"] = (nValue == 0) ? "Off" : "On";
ii++;
}
}
}
void CWebServer::RType_HandleGraph(WebEmSession & session, const request& req, Json::Value &root)
{
uint64_t idx = 0;
if (request::findValue(&req, "idx") != "")
{
idx = std::strtoull(request::findValue(&req, "idx").c_str(), nullptr, 10);
}
std::vector<std::vector<std::string> > result;
char szTmp[300];
std::string sensor = request::findValue(&req, "sensor");
if (sensor == "")
return;
std::string srange = request::findValue(&req, "range");
if (srange == "")
return;
time_t now = mytime(NULL);
struct tm tm1;
localtime_r(&now, &tm1);
result = m_sql.safe_query("SELECT Type, SubType, SwitchType, AddjValue, AddjMulti, AddjValue2, Options FROM DeviceStatus WHERE (ID == %" PRIu64 ")",
idx);
if (result.empty())
return;
unsigned char dType = atoi(result[0][0].c_str());
unsigned char dSubType = atoi(result[0][1].c_str());
_eMeterType metertype = (_eMeterType)atoi(result[0][2].c_str());
if (
(dType == pTypeP1Power) ||
(dType == pTypeENERGY) ||
(dType == pTypePOWER) ||
(dType == pTypeCURRENTENERGY) ||
((dType == pTypeGeneral) && (dSubType == sTypeKwh))
)
{
metertype = MTYPE_ENERGY;
}
else if (dType == pTypeP1Gas)
metertype = MTYPE_GAS;
else if ((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))
metertype = MTYPE_COUNTER;
// Special case of managed counter: Usage instead of Value in Meter table, and we don't want to calculate last value
bool bIsManagedCounter = (dType == pTypeGeneral) && (dSubType == sTypeManagedCounter);
double AddjValue = atof(result[0][3].c_str());
double AddjMulti = atof(result[0][4].c_str());
double AddjValue2 = atof(result[0][5].c_str());
std::string sOptions = result[0][6].c_str();
std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sOptions);
float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2));
std::string dbasetable = "";
if (srange == "day") {
if (sensor == "temp")
dbasetable = "Temperature";
else if (sensor == "rain")
dbasetable = "Rain";
else if (sensor == "Percentage")
dbasetable = "Percentage";
else if (sensor == "fan")
dbasetable = "Fan";
else if (sensor == "counter")
{
if ((dType == pTypeP1Power) || (dType == pTypeCURRENT) || (dType == pTypeCURRENTENERGY))
{
dbasetable = "MultiMeter";
}
else
{
dbasetable = "Meter";
}
}
else if ((sensor == "wind") || (sensor == "winddir"))
dbasetable = "Wind";
else if (sensor == "uv")
dbasetable = "UV";
else
return;
}
else
{
//week,year,month
if (sensor == "temp")
dbasetable = "Temperature_Calendar";
else if (sensor == "rain")
dbasetable = "Rain_Calendar";
else if (sensor == "Percentage")
dbasetable = "Percentage_Calendar";
else if (sensor == "fan")
dbasetable = "Fan_Calendar";
else if (sensor == "counter")
{
if (
(dType == pTypeP1Power) ||
(dType == pTypeCURRENT) ||
(dType == pTypeCURRENTENERGY) ||
(dType == pTypeAirQuality) ||
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture)) ||
((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel)) ||
(dType == pTypeLux) ||
(dType == pTypeWEIGHT) ||
(dType == pTypeUsage)
)
dbasetable = "MultiMeter_Calendar";
else
dbasetable = "Meter_Calendar";
}
else if ((sensor == "wind") || (sensor == "winddir"))
dbasetable = "Wind_Calendar";
else if (sensor == "uv")
dbasetable = "UV_Calendar";
else
return;
}
unsigned char tempsign = m_sql.m_tempsign[0];
int iPrev;
if (srange == "day")
{
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Temperature, Chill, Humidity, Barometer, Date, SetPoint FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) ||
(dType == pTypeTEMP) ||
(dType == pTypeTEMP_HUM) ||
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
(dType == pTypeThermostat1) ||
(dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) ||
(dType == pTypeEvohomeWater)
)
{
double tvalue = ConvertTemperature(atof(sd[0].c_str()), tempsign);
root["result"][ii]["te"] = tvalue;
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double tvalue = ConvertTemperature(atof(sd[1].c_str()), tempsign);
root["result"][ii]["ch"] = tvalue;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[2];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[3];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double se = ConvertTemperature(atof(sd[5].c_str()), tempsign);
root["result"][ii]["se"] = se;
}
ii++;
}
}
}
else if (sensor == "Percentage") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Percentage, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (sensor == "fan") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Speed, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (sensor == "counter")
{
if (dType == pTypeP1Power)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Value4, Value5, Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveDeliverd = false;
bool bHaveFirstValue = false;
long long lastUsage1, lastUsage2, lastDeliv1, lastDeliv2;
time_t lastTime = 0;
long long firstUsage1, firstUsage2, firstDeliv1, firstDeliv2;
int nMeterType = 0;
m_sql.GetPreferencesVar("SmartMeterType", nMeterType);
int lastDay = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
if (nMeterType == 0)
{
long long actUsage1 = std::strtoll(sd[0].c_str(), nullptr, 10);
long long actUsage2 = std::strtoll(sd[4].c_str(), nullptr, 10);
long long actDeliv1 = std::strtoll(sd[1].c_str(), nullptr, 10);
long long actDeliv2 = std::strtoll(sd[5].c_str(), nullptr, 10);
actDeliv1 = (actDeliv1 < 10) ? 0 : actDeliv1;
actDeliv2 = (actDeliv2 < 10) ? 0 : actDeliv2;
std::string stime = sd[6];
struct tm ntime;
time_t atime;
ParseSQLdatetime(atime, ntime, stime, -1);
if (lastDay != ntime.tm_mday)
{
lastDay = ntime.tm_mday;
firstUsage1 = actUsage1;
firstUsage2 = actUsage2;
firstDeliv1 = actDeliv1;
firstDeliv2 = actDeliv2;
}
if (bHaveFirstValue)
{
long curUsage1 = (long)(actUsage1 - lastUsage1);
long curUsage2 = (long)(actUsage2 - lastUsage2);
long curDeliv1 = (long)(actDeliv1 - lastDeliv1);
long curDeliv2 = (long)(actDeliv2 - lastDeliv2);
if ((curUsage1 < 0) || (curUsage1 > 100000))
curUsage1 = 0;
if ((curUsage2 < 0) || (curUsage2 > 100000))
curUsage2 = 0;
if ((curDeliv1 < 0) || (curDeliv1 > 100000))
curDeliv1 = 0;
if ((curDeliv2 < 0) || (curDeliv2 > 100000))
curDeliv2 = 0;
float tdiff = static_cast<float>(difftime(atime, lastTime));
if (tdiff == 0)
tdiff = 1;
float tlaps = 3600.0f / tdiff;
curUsage1 *= int(tlaps);
curUsage2 *= int(tlaps);
curDeliv1 *= int(tlaps);
curDeliv2 *= int(tlaps);
root["result"][ii]["d"] = sd[6].substr(0, 16);
if ((curDeliv1 != 0) || (curDeliv2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%ld", curUsage1);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%ld", curUsage2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%ld", curDeliv1);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%ld", curDeliv2);
root["result"][ii]["r2"] = szTmp;
long pUsage1 = (long)(actUsage1 - firstUsage1);
long pUsage2 = (long)(actUsage2 - firstUsage2);
sprintf(szTmp, "%ld", pUsage1 + pUsage2);
root["result"][ii]["eu"] = szTmp;
if (bHaveDeliverd)
{
long pDeliv1 = (long)(actDeliv1 - firstDeliv1);
long pDeliv2 = (long)(actDeliv2 - firstDeliv2);
sprintf(szTmp, "%ld", pDeliv1 + pDeliv2);
root["result"][ii]["eg"] = szTmp;
}
ii++;
}
else
{
bHaveFirstValue = true;
if ((ntime.tm_hour != 0) && (ntime.tm_min != 0))
{
struct tm ltime;
localtime_r(&atime, &tm1);
getNoon(atime, ltime, ntime.tm_year + 1900, ntime.tm_mon + 1, ntime.tm_mday - 1); // We're only interested in finding the date
int year = ltime.tm_year + 1900;
int mon = ltime.tm_mon + 1;
int day = ltime.tm_mday;
sprintf(szTmp, "%04d-%02d-%02d", year, mon, day);
std::vector<std::vector<std::string> > result2;
result2 = m_sql.safe_query(
"SELECT Counter1, Counter2, Counter3, Counter4 FROM Multimeter_Calendar WHERE (DeviceRowID==%" PRIu64 ") AND (Date=='%q')",
idx, szTmp);
if (!result2.empty())
{
std::vector<std::string> sd = result2[0];
firstUsage1 = std::strtoll(sd[0].c_str(), nullptr, 10);
firstDeliv1 = std::strtoll(sd[1].c_str(), nullptr, 10);
firstUsage2 = std::strtoll(sd[2].c_str(), nullptr, 10);
firstDeliv2 = std::strtoll(sd[3].c_str(), nullptr, 10);
lastDay = ntime.tm_mday;
}
}
}
lastUsage1 = actUsage1;
lastUsage2 = actUsage2;
lastDeliv1 = actDeliv1;
lastDeliv2 = actDeliv2;
lastTime = atime;
}
else
{
//this meter has no decimals, so return the use peaks
root["result"][ii]["d"] = sd[6].substr(0, 16);
if (sd[3] != "0")
bHaveDeliverd = true;
root["result"][ii]["v"] = sd[2];
root["result"][ii]["r1"] = sd[3];
ii++;
}
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (dType == pTypeAirQuality)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["co2"] = sd[0];
ii++;
}
}
}
else if ((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness)))
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
float fValue = float(atof(sd[0].c_str())) / vdiv;
if (metertype == 1)
fValue *= 0.6214f;
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue);
else
sprintf(szTmp, "%.1f", fValue);
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
else if ((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = sd[0];
ii++;
}
}
}
else if (dType == pTypeLux)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["lux"] = sd[0];
ii++;
}
}
}
else if (dType == pTypeWEIGHT)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[0].c_str()) / 10.0f);
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
else if (dType == pTypeUsage)
{//day
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["u"] = atof(sd[0].c_str()) / 10.0f;
ii++;
}
}
}
else if (dType == pTypeCURRENT)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
if (fval1 != 0)
bHaveL1 = true;
if (fval2 != 0)
bHaveL2 = true;
if (fval3 != 0)
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if (dType == pTypeCURRENTENERGY)
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
result = m_sql.safe_query("SELECT Value1, Value2, Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
if (fval1 != 0)
bHaveL1 = true;
if (fval2 != 0)
bHaveL2 = true;
if (fval3 != 0)
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if ((dType == pTypeENERGY) || (dType == pTypePOWER) || (dType == pTypeYouLess) || ((dType == pTypeGeneral) && (dSubType == sTypeKwh)))
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
//First check if we had any usage in the short log, if not, its probably a meter without usage
bool bHaveUsage = true;
result = m_sql.safe_query("SELECT MIN([Usage]), MAX([Usage]) FROM %s WHERE (DeviceRowID==%" PRIu64 ")", dbasetable.c_str(), idx);
if (!result.empty())
{
long long minValue = std::strtoll(result[0][0].c_str(), nullptr, 10);
long long maxValue = std::strtoll(result[0][1].c_str(), nullptr, 10);
if ((minValue == 0) && (maxValue == 0))
{
bHaveUsage = false;
}
}
int ii = 0;
result = m_sql.safe_query("SELECT Value,[Usage], Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
int method = 0;
std::string sMethod = request::findValue(&req, "method");
if (sMethod.size() > 0)
method = atoi(sMethod.c_str());
if (bHaveUsage == false)
method = 0;
if ((dType == pTypeYouLess) && ((metertype == MTYPE_ENERGY) || (metertype == MTYPE_ENERGY_GENERATED)))
method = 1;
if (method != 0)
{
//realtime graph
if ((dType == pTypeENERGY) || (dType == pTypePOWER))
divider /= 100.0f;
}
root["method"] = method;
bool bHaveFirstValue = false;
bool bHaveFirstRealValue = false;
float FirstValue = 0;
long long ulFirstRealValue = 0;
long long ulFirstValue = 0;
long long ulLastValue = 0;
std::string LastDateTime = "";
time_t lastTime = 0;
if (!result.empty())
{
std::vector<std::vector<std::string> >::const_iterator itt;
for (itt = result.begin(); itt!=result.end(); ++itt)
{
std::vector<std::string> sd = *itt;
//If method == 1, provide BOTH hourly and instant usage for combined graph
{
//bars / hour
std::string actDateTimeHour = sd[2].substr(0, 13);
long long actValue = std::strtoll(sd[0].c_str(), nullptr, 10);
if (actValue >= ulLastValue)
ulLastValue = actValue;
if (actDateTimeHour != LastDateTime || ((method == 1) && (itt + 1 == result.end())))
{
if (bHaveFirstValue)
{
//root["result"][ii]["d"] = LastDateTime + (method == 1 ? ":30" : ":00");
//^^ not necessarily bad, but is currently inconsistent with all other day graphs
root["result"][ii]["d"] = LastDateTime + ":00";
long long ulTotalValue = ulLastValue - ulFirstValue;
if (ulTotalValue == 0)
{
//Could be the P1 Gas Meter, only transmits one every 1 a 2 hours
ulTotalValue = ulLastValue - ulFirstRealValue;
}
ulFirstRealValue = ulLastValue;
float TotalValue = float(ulTotalValue);
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii][method == 1 ? "eu" : "v"] = szTmp;
ii++;
}
LastDateTime = actDateTimeHour;
bHaveFirstValue = false;
}
if (!bHaveFirstValue)
{
ulFirstValue = ulLastValue;
bHaveFirstValue = true;
}
if (!bHaveFirstRealValue)
{
bHaveFirstRealValue = true;
ulFirstRealValue = ulLastValue;
}
}
if (method == 1)
{
long long actValue = std::strtoll(sd[1].c_str(), nullptr, 10);
root["result"][ii]["d"] = sd[2].substr(0, 16);
float TotalValue = float(actValue);
if ((dType == pTypeGeneral) && (dSubType == sTypeKwh))
TotalValue /= 10.0f;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
}
else
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int ii = 0;
bool bHaveFirstValue = false;
bool bHaveFirstRealValue = false;
float FirstValue = 0;
unsigned long long ulFirstRealValue = 0;
unsigned long long ulFirstValue = 0;
unsigned long long ulLastValue = 0;
std::string LastDateTime = "";
time_t lastTime = 0;
if (bIsManagedCounter) {
result = m_sql.safe_query("SELECT Usage, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
bHaveFirstValue = true;
bHaveFirstRealValue = true;
}
else {
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
}
int method = 0;
std::string sMethod = request::findValue(&req, "method");
if (sMethod.size() > 0)
method = atoi(sMethod.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
if (method == 0)
{
//bars / hour
unsigned long long actValue = std::strtoull(sd[0].c_str(), nullptr, 10);
std::string actDateTimeHour = sd[1].substr(0, 13);
if (actDateTimeHour != LastDateTime)
{
if (bHaveFirstValue)
{
struct tm ntime;
time_t atime;
if (actDateTimeHour.size() == 10)
actDateTimeHour += " 00";
constructTime(atime, ntime,
atoi(actDateTimeHour.substr(0, 4).c_str()),
atoi(actDateTimeHour.substr(5, 2).c_str()),
atoi(actDateTimeHour.substr(8, 2).c_str()),
atoi(actDateTimeHour.substr(11, 2).c_str()) - 1,
0, 0, -1);
char szTime[50];
sprintf(szTime, "%04d-%02d-%02d %02d:00", ntime.tm_year + 1900, ntime.tm_mon + 1, ntime.tm_mday, ntime.tm_hour);
root["result"][ii]["d"] = szTime;
//float TotalValue = float(actValue - ulFirstValue);
//prevents graph from going crazy if the meter counter resets
float TotalValue = (actValue >= ulFirstValue) ? float(actValue - ulFirstValue) : actValue;
//if (TotalValue != 0)
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
if (!bIsManagedCounter) {
ulFirstValue = actValue;
}
LastDateTime = actDateTimeHour;
}
if (!bHaveFirstValue)
{
ulFirstValue = actValue;
bHaveFirstValue = true;
}
ulLastValue = actValue;
}
else
{
//realtime graph
unsigned long long actValue = std::strtoull(sd[0].c_str(), nullptr, 10);
std::string stime = sd[1];
struct tm ntime;
time_t atime;
ParseSQLdatetime(atime, ntime, stime, -1);
if (bHaveFirstRealValue)
{
long long curValue = actValue - ulLastValue;
float tdiff = static_cast<float>(difftime(atime, lastTime));
if (tdiff == 0)
tdiff = 1;
float tlaps = 3600.0f / tdiff;
curValue *= int(tlaps);
root["result"][ii]["d"] = sd[1].substr(0, 16);
float TotalValue = float(curValue);
//if (TotalValue != 0)
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
else
bHaveFirstRealValue = true;
if (!bIsManagedCounter) {
ulLastValue = actValue;
}
lastTime = atime;
}
}
}
if ((!bIsManagedCounter) && (bHaveFirstValue) && (method == 0))
{
//add last value
root["result"][ii]["d"] = LastDateTime + ":00";
unsigned long long ulTotalValue = ulLastValue - ulFirstValue;
float TotalValue = float(ulTotalValue);
//if (TotalValue != 0)
{
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", (TotalValue / divider)*1000.0f); //from kWh -> Watt
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", TotalValue / divider);
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.1f", TotalValue);
break;
default:
strcpy(szTmp, "0");
break;
}
root["result"][ii]["v"] = szTmp;
ii++;
}
}
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int LastHour = -1;
float LastTotalPreviousHour = -1;
float LastValue = -1;
std::string LastDate = "";
result = m_sql.safe_query("SELECT Total, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float ActTotal = static_cast<float>(atof(sd[0].c_str()));
int Hour = atoi(sd[1].substr(11, 2).c_str());
if (Hour != LastHour)
{
if (LastHour != -1)
{
int NextCalculatedHour = (LastHour + 1) % 24;
if (Hour != NextCalculatedHour)
{
//Looks like we have a GAP somewhere, finish the last hour
root["result"][ii]["d"] = LastDate;
double mmval = ActTotal - LastValue;
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
else
{
root["result"][ii]["d"] = sd[1].substr(0, 16);
double mmval = ActTotal - LastTotalPreviousHour;
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
LastHour = Hour;
LastTotalPreviousHour = ActTotal;
}
LastValue = ActTotal;
LastDate = sd[1];
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Direction, Speed, Gust, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
int ii = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[1].c_str());
int intGust = atoi(sd[2].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
}
else if (sensor == "winddir") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Direction, Speed, Gust FROM %s WHERE (DeviceRowID==%" PRIu64 ") ORDER BY Date ASC", dbasetable.c_str(), idx);
if (!result.empty())
{
std::map<int, int> _directions;
int wdirtabletemp[17][8];
std::string szLegendLabels[7];
int ii = 0;
int totalvalues = 0;
//init dir list
int idir;
for (idir = 0; idir < 360 + 1; idir++)
_directions[idir] = 0;
for (ii = 0; ii < 17; ii++)
{
for (int jj = 0; jj < 8; jj++)
{
wdirtabletemp[ii][jj] = 0;
}
}
if (m_sql.m_windunit == WINDUNIT_MS)
{
szLegendLabels[0] = "< 0.5 " + m_sql.m_windsign;
szLegendLabels[1] = "0.5-2 " + m_sql.m_windsign;
szLegendLabels[2] = "2-4 " + m_sql.m_windsign;
szLegendLabels[3] = "4-6 " + m_sql.m_windsign;
szLegendLabels[4] = "6-8 " + m_sql.m_windsign;
szLegendLabels[5] = "8-10 " + m_sql.m_windsign;
szLegendLabels[6] = "> 10" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_KMH)
{
szLegendLabels[0] = "< 2 " + m_sql.m_windsign;
szLegendLabels[1] = "2-4 " + m_sql.m_windsign;
szLegendLabels[2] = "4-6 " + m_sql.m_windsign;
szLegendLabels[3] = "6-10 " + m_sql.m_windsign;
szLegendLabels[4] = "10-20 " + m_sql.m_windsign;
szLegendLabels[5] = "20-36 " + m_sql.m_windsign;
szLegendLabels[6] = "> 36" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_MPH)
{
szLegendLabels[0] = "< 3 " + m_sql.m_windsign;
szLegendLabels[1] = "3-7 " + m_sql.m_windsign;
szLegendLabels[2] = "7-12 " + m_sql.m_windsign;
szLegendLabels[3] = "12-18 " + m_sql.m_windsign;
szLegendLabels[4] = "18-24 " + m_sql.m_windsign;
szLegendLabels[5] = "24-46 " + m_sql.m_windsign;
szLegendLabels[6] = "> 46" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_Knots)
{
szLegendLabels[0] = "< 3 " + m_sql.m_windsign;
szLegendLabels[1] = "3-7 " + m_sql.m_windsign;
szLegendLabels[2] = "7-17 " + m_sql.m_windsign;
szLegendLabels[3] = "17-27 " + m_sql.m_windsign;
szLegendLabels[4] = "27-34 " + m_sql.m_windsign;
szLegendLabels[5] = "34-41 " + m_sql.m_windsign;
szLegendLabels[6] = "> 41" + m_sql.m_windsign;
}
else if (m_sql.m_windunit == WINDUNIT_Beaufort)
{
szLegendLabels[0] = "< 2 " + m_sql.m_windsign;
szLegendLabels[1] = "2-4 " + m_sql.m_windsign;
szLegendLabels[2] = "4-6 " + m_sql.m_windsign;
szLegendLabels[3] = "6-8 " + m_sql.m_windsign;
szLegendLabels[4] = "8-10 " + m_sql.m_windsign;
szLegendLabels[5] = "10-12 " + m_sql.m_windsign;
szLegendLabels[6] = "> 12" + m_sql.m_windsign;
}
else {
//Todo !
szLegendLabels[0] = "< 0.5 " + m_sql.m_windsign;
szLegendLabels[1] = "0.5-2 " + m_sql.m_windsign;
szLegendLabels[2] = "2-4 " + m_sql.m_windsign;
szLegendLabels[3] = "4-6 " + m_sql.m_windsign;
szLegendLabels[4] = "6-8 " + m_sql.m_windsign;
szLegendLabels[5] = "8-10 " + m_sql.m_windsign;
szLegendLabels[6] = "> 10" + m_sql.m_windsign;
}
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float fdirection = static_cast<float>(atof(sd[0].c_str()));
if (fdirection >= 360)
fdirection = 0;
int direction = int(fdirection);
float speedOrg = static_cast<float>(atof(sd[1].c_str()));
float gustOrg = static_cast<float>(atof(sd[2].c_str()));
if ((gustOrg == 0) && (speedOrg != 0))
gustOrg = speedOrg;
if (gustOrg == 0)
continue; //no direction if wind is still
float speed = speedOrg * m_sql.m_windscale;
float gust = gustOrg * m_sql.m_windscale;
int bucket = int(fdirection / 22.5f);
int speedpos = 0;
if (m_sql.m_windunit == WINDUNIT_MS)
{
if (gust < 0.5f) speedpos = 0;
else if (gust < 2.0f) speedpos = 1;
else if (gust < 4.0f) speedpos = 2;
else if (gust < 6.0f) speedpos = 3;
else if (gust < 8.0f) speedpos = 4;
else if (gust < 10.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_KMH)
{
if (gust < 2.0f) speedpos = 0;
else if (gust < 4.0f) speedpos = 1;
else if (gust < 6.0f) speedpos = 2;
else if (gust < 10.0f) speedpos = 3;
else if (gust < 20.0f) speedpos = 4;
else if (gust < 36.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_MPH)
{
if (gust < 3.0f) speedpos = 0;
else if (gust < 7.0f) speedpos = 1;
else if (gust < 12.0f) speedpos = 2;
else if (gust < 18.0f) speedpos = 3;
else if (gust < 24.0f) speedpos = 4;
else if (gust < 46.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_Knots)
{
if (gust < 3.0f) speedpos = 0;
else if (gust < 7.0f) speedpos = 1;
else if (gust < 17.0f) speedpos = 2;
else if (gust < 27.0f) speedpos = 3;
else if (gust < 34.0f) speedpos = 4;
else if (gust < 41.0f) speedpos = 5;
else speedpos = 6;
}
else if (m_sql.m_windunit == WINDUNIT_Beaufort)
{
float gustms = gustOrg * 0.1f;
int iBeaufort = MStoBeaufort(gustms);
if (iBeaufort < 2) speedpos = 0;
else if (iBeaufort < 4) speedpos = 1;
else if (iBeaufort < 6) speedpos = 2;
else if (iBeaufort < 8) speedpos = 3;
else if (iBeaufort < 10) speedpos = 4;
else if (iBeaufort < 12) speedpos = 5;
else speedpos = 6;
}
else
{
//Still todo !
if (gust < 0.5f) speedpos = 0;
else if (gust < 2.0f) speedpos = 1;
else if (gust < 4.0f) speedpos = 2;
else if (gust < 6.0f) speedpos = 3;
else if (gust < 8.0f) speedpos = 4;
else if (gust < 10.0f) speedpos = 5;
else speedpos = 6;
}
wdirtabletemp[bucket][speedpos]++;
_directions[direction]++;
totalvalues++;
}
for (int jj = 0; jj < 7; jj++)
{
root["result_speed"][jj]["label"] = szLegendLabels[jj];
for (ii = 0; ii < 16; ii++)
{
float svalue = 0;
if (totalvalues > 0)
{
svalue = (100.0f / totalvalues)*wdirtabletemp[ii][jj];
}
sprintf(szTmp, "%.2f", svalue);
root["result_speed"][jj]["sp"][ii] = szTmp;
}
}
ii = 0;
for (idir = 0; idir < 360 + 1; idir++)
{
if (_directions[idir] != 0)
{
root["result"][ii]["dig"] = idir;
float percentage = 0;
if (totalvalues > 0)
{
percentage = (float(100.0 / float(totalvalues))*float(_directions[idir]));
}
sprintf(szTmp, "%.2f", percentage);
root["result"][ii]["div"] = szTmp;
ii++;
}
}
}
}
}//day
else if (srange == "week")
{
if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
char szDateStart[40];
char szDateEnd[40];
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
//Subtract one week
time_t weekbefore;
struct tm tm2;
getNoon(weekbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday - 7); // We only want the date
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
result = m_sql.safe_query("SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
//add today (have to calculate it)
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd);
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
double total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
total_real *= AddjMulti;
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
else if (sensor == "counter")
{
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
char szDateStart[40];
char szDateEnd[40];
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
//Subtract one week
time_t weekbefore;
struct tm tm2;
getNoon(weekbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday - 7); // We only want the date
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
int ii = 0;
if (dType == pTypeP1Power)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value5,Value6,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
std::string szValueUsage1 = sd[0];
std::string szValueDeliv1 = sd[1];
std::string szValueUsage2 = sd[2];
std::string szValueDeliv2 = sd[3];
float fUsage1 = (float)(atof(szValueUsage1.c_str()));
float fUsage2 = (float)(atof(szValueUsage2.c_str()));
float fDeliv1 = (float)(atof(szValueDeliv1.c_str()));
float fDeliv2 = (float)(atof(szValueDeliv2.c_str()));
fDeliv1 = (fDeliv1 < 10) ? 0 : fDeliv1;
fDeliv2 = (fDeliv2 < 10) ? 0 : fDeliv2;
if ((fDeliv1 != 0) || (fDeliv2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage1 / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage2 / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv1 / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv2 / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else
{
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_COUNTER:
//value already set above!
break;
default:
szValue = "0";
break;
}
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
//add today (have to calculate it)
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2), MAX(Value2),MIN(Value5), MAX(Value5), MIN(Value6), MAX(Value6) FROM MultiMeter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage_1, total_real_usage_2;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv_1, total_real_deliv_2;
bool bHaveDeliverd = false;
total_real_usage_1 = total_max_usage_1 - total_min_usage_1;
total_real_usage_2 = total_max_usage_2 - total_min_usage_2;
total_real_deliv_1 = total_max_deliv_1 - total_min_deliv_1;
total_real_deliv_2 = total_max_deliv_2 - total_min_deliv_2;
if ((total_real_deliv_1 != 0) || (total_real_deliv_2 != 0))
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%llu", total_real_usage_1);
std::string szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_usage_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_COUNTER:
//value already set above!
break;
default:
szValue = "0";
break;
}
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
}//week
else if ((srange == "month") || (srange == "year"))
{
char szDateStart[40];
char szDateEnd[40];
char szDateStartPrev[40];
char szDateEndPrev[40];
std::string sactmonth = request::findValue(&req, "actmonth");
std::string sactyear = request::findValue(&req, "actyear");
int actMonth = atoi(sactmonth.c_str());
int actYear = atoi(sactyear.c_str());
if ((sactmonth != "") && (sactyear != ""))
{
sprintf(szDateStart, "%04d-%02d-%02d", actYear, actMonth, 1);
sprintf(szDateStartPrev, "%04d-%02d-%02d", actYear - 1, actMonth, 1);
actMonth++;
if (actMonth == 13)
{
actMonth = 1;
actYear++;
}
sprintf(szDateEnd, "%04d-%02d-%02d", actYear, actMonth, 1);
sprintf(szDateEndPrev, "%04d-%02d-%02d", actYear - 1, actMonth, 1);
}
else if (sactyear != "")
{
sprintf(szDateStart, "%04d-%02d-%02d", actYear, 1, 1);
sprintf(szDateStartPrev, "%04d-%02d-%02d", actYear - 1, 1, 1);
actYear++;
sprintf(szDateEnd, "%04d-%02d-%02d", actYear, 1, 1);
sprintf(szDateEndPrev, "%04d-%02d-%02d", actYear - 1, 1, 1);
}
else
{
sprintf(szDateEnd, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
sprintf(szDateEndPrev, "%04d-%02d-%02d", tm1.tm_year + 1900 - 1, tm1.tm_mon + 1, tm1.tm_mday);
struct tm tm2;
if (srange == "month")
{
//Subtract one month
time_t monthbefore;
getNoon(monthbefore, tm2, tm1.tm_year + 1900, tm1.tm_mon, tm1.tm_mday);
}
else
{
//Subtract one year
time_t yearbefore;
getNoon(yearbefore, tm2, tm1.tm_year + 1900 - 1, tm1.tm_mon + 1, tm1.tm_mday);
}
sprintf(szDateStart, "%04d-%02d-%02d", tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday);
sprintf(szDateStartPrev, "%04d-%02d-%02d", tm2.tm_year + 1900 - 1, tm2.tm_mon + 1, tm2.tm_mday);
}
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
//Actual Year
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Temp_Avg, Date, SetPoint_Min,"
" SetPoint_Max, SetPoint_Avg "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[7].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
bool bOK = true;
if (dType == pTypeWIND)
{
bOK = ((dSubType != sTypeWINDNoTemp) && (dSubType != sTypeWINDNoTempNoChill));
}
if (bOK)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sm = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[10].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MIN(Temperature), MAX(Temperature),"
" MIN(Chill), MAX(Chill), AVG(Humidity),"
" AVG(Barometer), AVG(Temperature), MIN(SetPoint),"
" MAX(SetPoint), AVG(SetPoint) "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
if (
((dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["result"][ii]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sx = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sm = ConvertTemperature(atof(sd[7].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[9].c_str()), tempsign);
root["result"][ii]["se"] = se;
root["result"][ii]["sm"] = sm;
root["result"][ii]["sx"] = sx;
}
ii++;
}
//Previous Year
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Temp_Avg, Date, SetPoint_Min,"
" SetPoint_Max, SetPoint_Avg "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[7].substr(0, 16);
if (
(dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
{
bool bOK = true;
if (dType == pTypeWIND)
{
bOK = ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp));
}
if (bOK)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["resultprev"][iPrev]["te"] = te;
root["resultprev"][iPrev]["tm"] = tm;
root["resultprev"][iPrev]["ta"] = ta;
}
}
if (
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp))
)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["resultprev"][iPrev]["ch"] = ch;
root["resultprev"][iPrev]["cm"] = cm;
}
if ((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
{
root["resultprev"][iPrev]["hu"] = sd[4];
}
if (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
else
root["resultprev"][iPrev]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["resultprev"][iPrev]["ba"] = szTmp;
}
}
if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))
{
double sx = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sm = ConvertTemperature(atof(sd[7].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[9].c_str()), tempsign);
root["resultprev"][iPrev]["se"] = se;
root["resultprev"][iPrev]["sm"] = sm;
root["resultprev"][iPrev]["sx"] = sx;
}
iPrev++;
}
}
}
else if (sensor == "Percentage") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Percentage_Min, Percentage_Max, Percentage_Avg, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_avg"] = sd[2];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MIN(Percentage), MAX(Percentage), AVG(Percentage) FROM Percentage WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_avg"] = sd[2];
ii++;
}
}
else if (sensor == "fan") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Speed_Min, Speed_Max, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_min"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query("SELECT MIN(Speed), MAX(Speed) FROM Fan WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_max"] = sd[1];
root["result"][ii]["v_min"] = sd[0];
ii++;
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MAX(Level) FROM UV WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["uvi"] = sd[0];
ii++;
}
//Previous Year
result = m_sql.safe_query("SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
root["resultprev"][iPrev]["uvi"] = sd[0];
iPrev++;
}
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
//add today (have to calculate it)
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd);
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
double total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
total_real *= AddjMulti;
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
//Previous Year
result = m_sql.safe_query(
"SELECT Total, Rate, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[2].substr(0, 16);
double mmval = atof(sd[0].c_str());
mmval *= AddjMulti;
sprintf(szTmp, "%.1f", mmval);
root["resultprev"][iPrev]["mm"] = szTmp;
iPrev++;
}
}
}
else if (sensor == "counter") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int nValue = 0;
std::string sValue = "";
result = m_sql.safe_query("SELECT nValue, sValue FROM DeviceStatus WHERE (ID==%" PRIu64 ")",
idx);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
nValue = atoi(sd[0].c_str());
sValue = sd[1];
}
int ii = 0;
iPrev = 0;
if (dType == pTypeP1Power)
{
//Actual Year
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date,"
" Counter1, Counter2, Counter3, Counter4 "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
double counter_1 = atof(sd[5].c_str());
double counter_2 = atof(sd[6].c_str());
double counter_3 = atof(sd[7].c_str());
double counter_4 = atof(sd[8].c_str());
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage_1 = static_cast<float>(atof(szUsage1.c_str()));
float fUsage_2 = static_cast<float>(atof(szUsage2.c_str()));
float fDeliv_1 = static_cast<float>(atof(szDeliv1.c_str()));
float fDeliv_2 = static_cast<float>(atof(szDeliv2.c_str()));
fDeliv_1 = (fDeliv_1 < 10) ? 0 : fDeliv_1;
fDeliv_2 = (fDeliv_2 < 10) ? 0 : fDeliv_2;
if ((fDeliv_1 != 0) || (fDeliv_2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage_1 / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage_2 / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_1 / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_2 / divider);
root["result"][ii]["r2"] = szTmp;
if (counter_1 != 0)
{
sprintf(szTmp, "%.3f", (counter_1 - fUsage_1) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c1"] = szTmp;
if (counter_2 != 0)
{
sprintf(szTmp, "%.3f", (counter_2 - fDeliv_1) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c2"] = szTmp;
if (counter_3 != 0)
{
sprintf(szTmp, "%.3f", (counter_3 - fUsage_2) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c3"] = szTmp;
if (counter_4 != 0)
{
sprintf(szTmp, "%.3f", (counter_4 - fDeliv_2) / divider);
}
else
{
strcpy(szTmp, "0");
}
root["result"][ii]["c4"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
//Previous Year
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
bool bHaveDeliverd = false;
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[4].substr(0, 16);
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage_1 = static_cast<float>(atof(szUsage1.c_str()));
float fUsage_2 = static_cast<float>(atof(szUsage2.c_str()));
float fDeliv_1 = static_cast<float>(atof(szDeliv1.c_str()));
float fDeliv_2 = static_cast<float>(atof(szDeliv2.c_str()));
if ((fDeliv_1 != 0) || (fDeliv_2 != 0))
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage_1 / divider);
root["resultprev"][iPrev]["v"] = szTmp;
sprintf(szTmp, "%.3f", fUsage_2 / divider);
root["resultprev"][iPrev]["v2"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_1 / divider);
root["resultprev"][iPrev]["r1"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv_2 / divider);
root["resultprev"][iPrev]["r2"] = szTmp;
iPrev++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (dType == pTypeAirQuality)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["co2_min"] = sd[0];
root["result"][ii]["co2_max"] = sd[1];
root["result"][ii]["co2_avg"] = sd[2];
ii++;
}
}
result = m_sql.safe_query("SELECT Value2,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
root["resultprev"][iPrev]["co2_max"] = sd[0];
iPrev++;
}
}
}
else if (
((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness))) ||
((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["v_min"] = sd[0];
root["result"][ii]["v_max"] = sd[1];
ii++;
}
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
float fValue1 = float(atof(sd[0].c_str())) / vdiv;
float fValue2 = float(atof(sd[1].c_str())) / vdiv;
float fValue3 = float(atof(sd[2].c_str())) / vdiv;
root["result"][ii]["d"] = sd[3].substr(0, 16);
if (metertype == 1)
{
fValue1 *= 0.6214f;
fValue2 *= 0.6214f;
}
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
sprintf(szTmp, "%.3f", fValue1);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.3f", fValue2);
root["result"][ii]["v_max"] = szTmp;
if (fValue3 != 0)
{
sprintf(szTmp, "%.3f", fValue3);
root["result"][ii]["v_avg"] = szTmp;
}
}
else
{
sprintf(szTmp, "%.1f", fValue1);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", fValue2);
root["result"][ii]["v_max"] = szTmp;
if (fValue3 != 0)
{
sprintf(szTmp, "%.1f", fValue3);
root["result"][ii]["v_avg"] = szTmp;
}
}
ii++;
}
}
}
else if (dType == pTypeLux)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query("SELECT Value1,Value2,Value3, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[3].substr(0, 16);
root["result"][ii]["lux_min"] = sd[0];
root["result"][ii]["lux_max"] = sd[1];
root["result"][ii]["lux_avg"] = sd[2];
ii++;
}
}
}
else if (dType == pTypeWEIGHT)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[0].c_str()) / 10.0f);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(sd[1].c_str()) / 10.0f);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
}
else if (dType == pTypeUsage)
{//month/year
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Value1,Value2, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["u_min"] = atof(sd[0].c_str()) / 10.0f;
root["result"][ii]["u_max"] = atof(sd[1].c_str()) / 10.0f;
ii++;
}
}
}
else if (dType == pTypeCURRENT)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Value4,Value5,Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
//CM113
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
float fval4 = static_cast<float>(atof(sd[3].c_str()) / 10.0f);
float fval5 = static_cast<float>(atof(sd[4].c_str()) / 10.0f);
float fval6 = static_cast<float>(atof(sd[5].c_str()) / 10.0f);
if ((fval1 != 0) || (fval2 != 0))
bHaveL1 = true;
if ((fval3 != 0) || (fval4 != 0))
bHaveL2 = true;
if ((fval5 != 0) || (fval6 != 0))
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%.1f", fval4);
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%.1f", fval5);
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%.1f", fval6);
root["result"][ii]["v6"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%d", int(fval4*voltage));
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%d", int(fval5*voltage));
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%d", int(fval6*voltage));
root["result"][ii]["v6"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else if (dType == pTypeCURRENTENERGY)
{
result = m_sql.safe_query("SELECT Value1,Value2,Value3,Value4,Value5,Value6, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
//CM180i
int displaytype = 0;
int voltage = 230;
m_sql.GetPreferencesVar("CM113DisplayType", displaytype);
m_sql.GetPreferencesVar("ElectricVoltage", voltage);
root["displaytype"] = displaytype;
bool bHaveL1 = false;
bool bHaveL2 = false;
bool bHaveL3 = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
float fval1 = static_cast<float>(atof(sd[0].c_str()) / 10.0f);
float fval2 = static_cast<float>(atof(sd[1].c_str()) / 10.0f);
float fval3 = static_cast<float>(atof(sd[2].c_str()) / 10.0f);
float fval4 = static_cast<float>(atof(sd[3].c_str()) / 10.0f);
float fval5 = static_cast<float>(atof(sd[4].c_str()) / 10.0f);
float fval6 = static_cast<float>(atof(sd[5].c_str()) / 10.0f);
if ((fval1 != 0) || (fval2 != 0))
bHaveL1 = true;
if ((fval3 != 0) || (fval4 != 0))
bHaveL2 = true;
if ((fval5 != 0) || (fval6 != 0))
bHaveL3 = true;
if (displaytype == 0)
{
sprintf(szTmp, "%.1f", fval1);
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%.1f", fval2);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%.1f", fval3);
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%.1f", fval4);
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%.1f", fval5);
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%.1f", fval6);
root["result"][ii]["v6"] = szTmp;
}
else
{
sprintf(szTmp, "%d", int(fval1*voltage));
root["result"][ii]["v1"] = szTmp;
sprintf(szTmp, "%d", int(fval2*voltage));
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%d", int(fval3*voltage));
root["result"][ii]["v3"] = szTmp;
sprintf(szTmp, "%d", int(fval4*voltage));
root["result"][ii]["v4"] = szTmp;
sprintf(szTmp, "%d", int(fval5*voltage));
root["result"][ii]["v5"] = szTmp;
sprintf(szTmp, "%d", int(fval6*voltage));
root["result"][ii]["v6"] = szTmp;
}
ii++;
}
if (
(!bHaveL1) &&
(!bHaveL2) &&
(!bHaveL3)
) {
root["haveL1"] = true; //show at least something
}
else {
if (bHaveL1)
root["haveL1"] = true;
if (bHaveL2)
root["haveL2"] = true;
if (bHaveL3)
root["haveL3"] = true;
}
}
}
else
{
if (dType == pTypeP1Gas)
{
//Add last counter value
sprintf(szTmp, "%.3f", atof(sValue.c_str()) / 1000.0);
root["counter"] = szTmp;
}
else if (dType == pTypeENERGY)
{
size_t spos = sValue.find(";");
if (spos != std::string::npos)
{
float fvalue = static_cast<float>(atof(sValue.substr(spos + 1).c_str()));
sprintf(szTmp, "%.3f", fvalue / (divider / 100.0f));
root["counter"] = szTmp;
}
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeKwh))
{
size_t spos = sValue.find(";");
if (spos != std::string::npos)
{
float fvalue = static_cast<float>(atof(sValue.substr(spos + 1).c_str()));
sprintf(szTmp, "%.3f", fvalue / divider);
root["counter"] = szTmp;
}
}
else if (dType == pTypeRFXMeter)
{
//Add last counter value
float fvalue = static_cast<float>(atof(sValue.c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", AddjValue + (fvalue / divider));
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", AddjValue + (fvalue / divider));
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", AddjValue + (fvalue / divider));
break;
default:
strcpy(szTmp, "");
break;
}
root["counter"] = szTmp;
}
else if (dType == pTypeYouLess)
{
std::vector<std::string> results;
StringSplit(sValue, ";", results);
if (results.size() == 2)
{
//Add last counter value
float fvalue = static_cast<float>(atof(results[0].c_str()));
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", fvalue / divider);
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", fvalue / divider);
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", fvalue / divider);
break;
default:
strcpy(szTmp, "");
break;
}
root["counter"] = szTmp;
}
}
else if (!bIsManagedCounter)
{
//Add last counter value
sprintf(szTmp, "%d", atoi(sValue.c_str()));
root["counter"] = szTmp;
}
else
{
root["counter"] = "0";
}
//Actual Year
result = m_sql.safe_query("SELECT Value, Date, Counter FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
double fcounter = atof(sd[2].c_str());
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.3f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.2f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.3f", AddjValue + ((fcounter - atof(szValue.c_str())) / divider));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["result"][ii]["v"] = szTmp;
if (fcounter != 0)
sprintf(szTmp, "%.0f", AddjValue + ((fcounter - atof(szValue.c_str()))));
else
strcpy(szTmp, "0");
root["result"][ii]["c"] = szTmp;
break;
}
ii++;
}
}
//Past Year
result = m_sql.safe_query("SELECT Value, Date, Counter FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[1].substr(0, 16);
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["resultprev"][iPrev]["v"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["resultprev"][iPrev]["v"] = szTmp;
break;
}
iPrev++;
}
}
}
//add today (have to calculate it)
if ((sactmonth != "") || (sactyear != ""))
{
struct tm loctime;
time_t now = mytime(NULL);
localtime_r(&now, &loctime);
if ((sactmonth != "") && (sactyear != ""))
{
bool bIsThisMonth = (atoi(sactyear.c_str()) == loctime.tm_year + 1900) && (atoi(sactmonth.c_str()) == loctime.tm_mon + 1);
if (bIsThisMonth)
{
sprintf(szDateEnd, "%04d-%02d-%02d", loctime.tm_year + 1900, loctime.tm_mon + 1, loctime.tm_mday);
}
}
else if (sactyear != "")
{
bool bIsThisYear = (atoi(sactyear.c_str()) == loctime.tm_year + 1900);
if (bIsThisYear)
{
sprintf(szDateEnd, "%04d-%02d-%02d", loctime.tm_year + 1900, loctime.tm_mon + 1, loctime.tm_mday);
}
}
}
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2),"
" MAX(Value2), MIN(Value5), MAX(Value5),"
" MIN(Value6), MAX(Value6) "
"FROM MultiMeter WHERE (DeviceRowID=%" PRIu64 ""
" AND Date>='%q')",
idx, szDateEnd);
bool bHaveDeliverd = false;
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage_1, total_real_usage_2;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv_1, total_real_deliv_2;
total_real_usage_1 = total_max_usage_1 - total_min_usage_1;
total_real_usage_2 = total_max_usage_2 - total_min_usage_2;
total_real_deliv_1 = total_max_deliv_1 - total_min_deliv_1;
total_real_deliv_2 = total_max_deliv_2 - total_min_deliv_2;
if ((total_real_deliv_1 != 0) || (total_real_deliv_2 != 0))
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
std::string szValue;
sprintf(szTmp, "%llu", total_real_usage_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_usage_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_1);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r1"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv_2);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["r2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
else if (dType == pTypeAirQuality)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value), AVG(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["co2_min"] = result[0][0];
root["result"][ii]["co2_max"] = result[0][1];
root["result"][ii]["co2_avg"] = result[0][2];
ii++;
}
}
else if (
((dType == pTypeGeneral) && ((dSubType == sTypeSoilMoisture) || (dSubType == sTypeLeafWetness))) ||
((dType == pTypeRFXSensor) && ((dSubType == sTypeRFXSensorAD) || (dSubType == sTypeRFXSensorVolt)))
)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v_min"] = result[0][0];
root["result"][ii]["v_max"] = result[0][1];
ii++;
}
}
else if (
((dType == pTypeGeneral) && (dSubType == sTypeVisibility)) ||
((dType == pTypeGeneral) && (dSubType == sTypeDistance)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation)) ||
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent)) ||
((dType == pTypeGeneral) && (dSubType == sTypePressure)) ||
((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))
)
{
float vdiv = 10.0f;
if (
((dType == pTypeGeneral) && (dSubType == sTypeVoltage)) ||
((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
)
{
vdiv = 1000.0f;
}
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
float fValue1 = float(atof(result[0][0].c_str())) / vdiv;
float fValue2 = float(atof(result[0][1].c_str())) / vdiv;
if (metertype == 1)
{
fValue1 *= 0.6214f;
fValue2 *= 0.6214f;
}
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue1);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue1);
else
sprintf(szTmp, "%.1f", fValue1);
root["result"][ii]["v_min"] = szTmp;
if ((dType == pTypeGeneral) && (dSubType == sTypeVoltage))
sprintf(szTmp, "%.3f", fValue2);
else if ((dType == pTypeGeneral) && (dSubType == sTypeCurrent))
sprintf(szTmp, "%.3f", fValue2);
else
sprintf(szTmp, "%.1f", fValue2);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
else if (dType == pTypeLux)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value), AVG(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["lux_min"] = result[0][0];
root["result"][ii]["lux_max"] = result[0][1];
root["result"][ii]["lux_avg"] = result[0][2];
ii++;
}
}
else if (dType == pTypeWEIGHT)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%.1f", m_sql.m_weightscale* atof(result[0][0].c_str()) / 10.0f);
root["result"][ii]["v_min"] = szTmp;
sprintf(szTmp, "%.1f", m_sql.m_weightscale * atof(result[0][1].c_str()) / 10.0f);
root["result"][ii]["v_max"] = szTmp;
ii++;
}
}
else if (dType == pTypeUsage)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID=%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["u_min"] = atof(result[0][0].c_str()) / 10.0f;
root["result"][ii]["u_max"] = atof(result[0][1].c_str()) / 10.0f;
ii++;
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
root["result"][ii]["d"] = szDateEnd;
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
{
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
std::vector<std::string> mresults;
StringSplit(sValue, ";", mresults);
if (mresults.size() == 2)
{
sValue = mresults[1];
}
if (dType == pTypeENERGY)
sprintf(szTmp, "%.3f", AddjValue + (((atof(sValue.c_str())*100.0f) - atof(szValue.c_str())) / divider));
else
sprintf(szTmp, "%.3f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
}
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.2f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str())) / divider));
root["result"][ii]["c"] = szTmp;
break;
case MTYPE_COUNTER:
sprintf(szTmp, "%.0f", atof(szValue.c_str()));
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.0f", AddjValue + ((atof(sValue.c_str()) - atof(szValue.c_str()))));
root["result"][ii]["c"] = szTmp;
break;
}
ii++;
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int ii = 0;
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart, szDateEnd);
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[5].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT AVG(Direction), MIN(Speed), MAX(Speed),"
" MIN(Gust), MAX(Gust) "
"FROM Wind WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY Date ASC",
idx, szDateEnd);
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
//Previous Year
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStartPrev, szDateEndPrev);
if (!result.empty())
{
iPrev = 0;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["resultprev"][iPrev]["d"] = sd[5].substr(0, 16);
root["resultprev"][iPrev]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["resultprev"][iPrev]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["resultprev"][iPrev]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["resultprev"][iPrev]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["resultprev"][iPrev]["gu"] = szTmp;
}
iPrev++;
}
}
}
}//month or year
else if ((srange.substr(0, 1) == "2") && (srange.substr(10, 1) == "T") && (srange.substr(11, 1) == "2")) // custom range 2013-01-01T2013-12-31
{
std::string szDateStart = srange.substr(0, 10);
std::string szDateEnd = srange.substr(11, 10);
std::string sgraphtype = request::findValue(&req, "graphtype");
std::string sgraphTemp = request::findValue(&req, "graphTemp");
std::string sgraphChill = request::findValue(&req, "graphChill");
std::string sgraphHum = request::findValue(&req, "graphHum");
std::string sgraphBaro = request::findValue(&req, "graphBaro");
std::string sgraphDew = request::findValue(&req, "graphDew");
std::string sgraphSet = request::findValue(&req, "graphSet");
if (sensor == "temp") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
bool sendTemp = false;
bool sendChill = false;
bool sendHum = false;
bool sendBaro = false;
bool sendDew = false;
bool sendSet = false;
if ((sgraphTemp == "true") &&
((dType == pTypeRego6XXTemp) || (dType == pTypeTEMP) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeTEMP_BARO) || (dType == pTypeWIND) || (dType == pTypeThermostat1) || (dType == pTypeRadiator1) ||
((dType == pTypeUV) && (dSubType == sTypeUV3)) ||
((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) ||
((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint)) ||
(dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)
)
)
{
sendTemp = true;
}
if ((sgraphSet == "true") &&
((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater))) //FIXME cheat for water setpoint is just on or off
{
sendSet = true;
}
if ((sgraphChill == "true") &&
(((dType == pTypeWIND) && (dSubType == sTypeWIND4)) ||
((dType == pTypeWIND) && (dSubType == sTypeWINDNoTemp)))
)
{
sendChill = true;
}
if ((sgraphHum == "true") &&
((dType == pTypeHUM) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO))
)
{
sendHum = true;
}
if ((sgraphBaro == "true") && (
(dType == pTypeTEMP_HUM_BARO) ||
(dType == pTypeTEMP_BARO) ||
((dType == pTypeGeneral) && (dSubType == sTypeBaro))
))
{
sendBaro = true;
}
if ((sgraphDew == "true") && ((dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO)))
{
sendDew = true;
}
if (sgraphtype == "1")
{
// Need to get all values of the end date so 23:59:59 is appended to the date string
result = m_sql.safe_query(
"SELECT Temperature, Chill, Humidity, Barometer,"
" Date, DewPoint, SetPoint "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q' AND Date<='%q 23:59:59') ORDER BY Date ASC",
idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4];//.substr(0,16);
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[1].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[2];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[3];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[3].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[5].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double se = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["se"] = se;
}
ii++;
}
}
}
else
{
result = m_sql.safe_query(
"SELECT Temp_Min, Temp_Max, Chill_Min, Chill_Max,"
" Humidity, Barometer, Date, DewPoint, Temp_Avg,"
" SetPoint_Min, SetPoint_Max, SetPoint_Avg "
"FROM Temperature_Calendar "
"WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[6].substr(0, 16);
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[8].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[4];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[7].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double sm = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[10].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[11].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
char szTmp[1024];
sprintf(szTmp, "%.1f %.1f %.1f", sm, se, sx);
_log.Log(LOG_STATUS, "%s", szTmp);
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MIN(Temperature), MAX(Temperature),"
" MIN(Chill), MAX(Chill), AVG(Humidity),"
" AVG(Barometer), MIN(DewPoint), AVG(Temperature),"
" MIN(SetPoint), MAX(SetPoint), AVG(SetPoint) "
"FROM Temperature WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
if (sendTemp)
{
double te = ConvertTemperature(atof(sd[1].c_str()), tempsign);
double tm = ConvertTemperature(atof(sd[0].c_str()), tempsign);
double ta = ConvertTemperature(atof(sd[7].c_str()), tempsign);
root["result"][ii]["te"] = te;
root["result"][ii]["tm"] = tm;
root["result"][ii]["ta"] = ta;
}
if (sendChill)
{
double ch = ConvertTemperature(atof(sd[3].c_str()), tempsign);
double cm = ConvertTemperature(atof(sd[2].c_str()), tempsign);
root["result"][ii]["ch"] = ch;
root["result"][ii]["cm"] = cm;
}
if (sendHum)
{
root["result"][ii]["hu"] = sd[4];
}
if (sendBaro)
{
if (dType == pTypeTEMP_HUM_BARO)
{
if (dSubType == sTypeTHBFloat)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else
root["result"][ii]["ba"] = sd[5];
}
else if (dType == pTypeTEMP_BARO)
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
else if ((dType == pTypeGeneral) && (dSubType == sTypeBaro))
{
sprintf(szTmp, "%.1f", atof(sd[5].c_str()) / 10.0f);
root["result"][ii]["ba"] = szTmp;
}
}
if (sendDew)
{
double dp = ConvertTemperature(atof(sd[6].c_str()), tempsign);
root["result"][ii]["dp"] = dp;
}
if (sendSet)
{
double sm = ConvertTemperature(atof(sd[8].c_str()), tempsign);
double sx = ConvertTemperature(atof(sd[9].c_str()), tempsign);
double se = ConvertTemperature(atof(sd[10].c_str()), tempsign);
root["result"][ii]["sm"] = sm;
root["result"][ii]["se"] = se;
root["result"][ii]["sx"] = sx;
}
ii++;
}
}
}
else if (sensor == "uv") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Level, Date FROM %s WHERE (DeviceRowID==%" PRIu64 ""
" AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT MAX(Level) FROM UV WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["uvi"] = sd[0];
ii++;
}
}
else if (sensor == "rain") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
result = m_sql.safe_query(
"SELECT Total, Rate, Date FROM %s "
"WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
int ii = 0;
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[2].substr(0, 16);
root["result"][ii]["mm"] = sd[0];
ii++;
}
}
//add today (have to calculate it)
if (dSubType != sTypeRAINWU)
{
result = m_sql.safe_query(
"SELECT MIN(Total), MAX(Total), MAX(Rate) FROM Rain WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
}
else
{
result = m_sql.safe_query(
"SELECT Total, Total, Rate FROM Rain WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY ROWID DESC LIMIT 1",
idx, szDateEnd.c_str());
}
if (!result.empty())
{
std::vector<std::string> sd = result[0];
float total_min = static_cast<float>(atof(sd[0].c_str()));
float total_max = static_cast<float>(atof(sd[1].c_str()));
int rate = atoi(sd[2].c_str());
float total_real = 0;
if (dSubType != sTypeRAINWU)
{
total_real = total_max - total_min;
}
else
{
total_real = total_max;
}
sprintf(szTmp, "%.1f", total_real);
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["mm"] = szTmp;
ii++;
}
}
else if (sensor == "counter") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
root["ValueQuantity"] = options["ValueQuantity"];
root["ValueUnits"] = options["ValueUnits"];
int ii = 0;
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT Value1,Value2,Value5,Value6, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
bool bHaveDeliverd = false;
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[4].substr(0, 16);
std::string szUsage1 = sd[0];
std::string szDeliv1 = sd[1];
std::string szUsage2 = sd[2];
std::string szDeliv2 = sd[3];
float fUsage = (float)(atof(szUsage1.c_str()) + atof(szUsage2.c_str()));
float fDeliv = (float)(atof(szDeliv1.c_str()) + atof(szDeliv2.c_str()));
if (fDeliv != 0)
bHaveDeliverd = true;
sprintf(szTmp, "%.3f", fUsage / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%.3f", fDeliv / divider);
root["result"][ii]["v2"] = szTmp;
ii++;
}
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else
{
result = m_sql.safe_query("SELECT Value, Date FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q' AND Date<='%q') ORDER BY Date ASC", dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
std::string szValue = sd[0];
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
}
root["result"][ii]["d"] = sd[1].substr(0, 16);
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
//add today (have to calculate it)
if (dType == pTypeP1Power)
{
result = m_sql.safe_query(
"SELECT MIN(Value1), MAX(Value1), MIN(Value2),"
" MAX(Value2),MIN(Value5), MAX(Value5),"
" MIN(Value6), MAX(Value6) "
"FROM MultiMeter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
bool bHaveDeliverd = false;
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min_usage_1 = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max_usage_1 = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_min_usage_2 = std::strtoull(sd[4].c_str(), nullptr, 10);
unsigned long long total_max_usage_2 = std::strtoull(sd[5].c_str(), nullptr, 10);
unsigned long long total_real_usage;
unsigned long long total_min_deliv_1 = std::strtoull(sd[2].c_str(), nullptr, 10);
unsigned long long total_max_deliv_1 = std::strtoull(sd[3].c_str(), nullptr, 10);
unsigned long long total_min_deliv_2 = std::strtoull(sd[6].c_str(), nullptr, 10);
unsigned long long total_max_deliv_2 = std::strtoull(sd[7].c_str(), nullptr, 10);
unsigned long long total_real_deliv;
total_real_usage = (total_max_usage_1 + total_max_usage_2) - (total_min_usage_1 + total_min_usage_2);
total_real_deliv = (total_max_deliv_1 + total_max_deliv_2) - (total_min_deliv_1 + total_min_deliv_2);
if (total_real_deliv != 0)
bHaveDeliverd = true;
root["result"][ii]["d"] = szDateEnd;
sprintf(szTmp, "%llu", total_real_usage);
std::string szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v"] = szTmp;
sprintf(szTmp, "%llu", total_real_deliv);
szValue = szTmp;
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
root["result"][ii]["v2"] = szTmp;
ii++;
if (bHaveDeliverd)
{
root["delivered"] = true;
}
}
}
else if (!bIsManagedCounter)
{
result = m_sql.safe_query(
"SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q')",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
unsigned long long total_min = std::strtoull(sd[0].c_str(), nullptr, 10);
unsigned long long total_max = std::strtoull(sd[1].c_str(), nullptr, 10);
unsigned long long total_real;
total_real = total_max - total_min;
sprintf(szTmp, "%llu", total_real);
std::string szValue = szTmp;
switch (metertype)
{
case MTYPE_ENERGY:
case MTYPE_ENERGY_GENERATED:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_GAS:
sprintf(szTmp, "%.2f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
case MTYPE_WATER:
sprintf(szTmp, "%.3f", atof(szValue.c_str()) / divider);
szValue = szTmp;
break;
}
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["v"] = szValue;
ii++;
}
}
}
else if (sensor == "wind") {
root["status"] = "OK";
root["title"] = "Graph " + sensor + " " + srange;
int ii = 0;
result = m_sql.safe_query(
"SELECT Direction, Speed_Min, Speed_Max, Gust_Min,"
" Gust_Max, Date "
"FROM %s WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q'"
" AND Date<='%q') ORDER BY Date ASC",
dbasetable.c_str(), idx, szDateStart.c_str(), szDateEnd.c_str());
if (!result.empty())
{
for (const auto & itt : result)
{
std::vector<std::string> sd = itt;
root["result"][ii]["d"] = sd[5].substr(0, 16);
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
//add today (have to calculate it)
result = m_sql.safe_query(
"SELECT AVG(Direction), MIN(Speed), MAX(Speed), MIN(Gust), MAX(Gust) FROM Wind WHERE (DeviceRowID==%" PRIu64 " AND Date>='%q') ORDER BY Date ASC",
idx, szDateEnd.c_str());
if (!result.empty())
{
std::vector<std::string> sd = result[0];
root["result"][ii]["d"] = szDateEnd;
root["result"][ii]["di"] = sd[0];
int intSpeed = atoi(sd[2].c_str());
int intGust = atoi(sd[4].c_str());
if (m_sql.m_windunit != WINDUNIT_Beaufort)
{
sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale);
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%.1f", float(intGust) * m_sql.m_windscale);
root["result"][ii]["gu"] = szTmp;
}
else
{
float windspeedms = float(intSpeed)*0.1f;
float windgustms = float(intGust)*0.1f;
sprintf(szTmp, "%d", MStoBeaufort(windspeedms));
root["result"][ii]["sp"] = szTmp;
sprintf(szTmp, "%d", MStoBeaufort(windgustms));
root["result"][ii]["gu"] = szTmp;
}
ii++;
}
}
}//custom range
}
/**
* Retrieve user session from store, without remote host.
*/
const WebEmStoredSession CWebServer::GetSession(const std::string & sessionId) {
//_log.Log(LOG_STATUS, "SessionStore : get...");
WebEmStoredSession session;
if (sessionId.empty()) {
_log.Log(LOG_ERROR, "SessionStore : cannot get session without id.");
}
else {
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT SessionID, Username, AuthToken, ExpirationDate FROM UserSessions WHERE SessionID = '%q'",
sessionId.c_str());
if (!result.empty()) {
session.id = result[0][0].c_str();
session.username = base64_decode(result[0][1]);
session.auth_token = result[0][2].c_str();
std::string sExpirationDate = result[0][3];
time_t now = mytime(NULL);
struct tm tExpirationDate;
ParseSQLdatetime(session.expires, tExpirationDate, sExpirationDate);
// RemoteHost is not used to restore the session
// LastUpdate is not used to restore the session
}
}
return session;
}
/**
* Save user session.
*/
void CWebServer::StoreSession(const WebEmStoredSession & session) {
//_log.Log(LOG_STATUS, "SessionStore : store...");
if (session.id.empty()) {
_log.Log(LOG_ERROR, "SessionStore : cannot store session without id.");
return;
}
char szExpires[30];
struct tm ltime;
localtime_r(&session.expires, <ime);
strftime(szExpires, sizeof(szExpires), "%Y-%m-%d %H:%M:%S", <ime);
std::string remote_host = (session.remote_host.size() <= 50) ? // IPv4 : 15, IPv6 : (39|45)
session.remote_host : session.remote_host.substr(0, 50);
WebEmStoredSession storedSession = GetSession(session.id);
if (storedSession.id.empty()) {
m_sql.safe_query(
"INSERT INTO UserSessions (SessionID, Username, AuthToken, ExpirationDate, RemoteHost) VALUES ('%q', '%q', '%q', '%q', '%q')",
session.id.c_str(),
base64_encode(session.username).c_str(),
session.auth_token.c_str(),
szExpires,
remote_host.c_str());
}
else {
m_sql.safe_query(
"UPDATE UserSessions set AuthToken = '%q', ExpirationDate = '%q', RemoteHost = '%q', LastUpdate = datetime('now', 'localtime') WHERE SessionID = '%q'",
session.auth_token.c_str(),
szExpires,
remote_host.c_str(),
session.id.c_str());
}
}
/**
* Remove user session and expired sessions.
*/
void CWebServer::RemoveSession(const std::string & sessionId) {
//_log.Log(LOG_STATUS, "SessionStore : remove...");
if (sessionId.empty()) {
return;
}
m_sql.safe_query(
"DELETE FROM UserSessions WHERE SessionID = '%q'",
sessionId.c_str());
}
/**
* Remove all expired user sessions.
*/
void CWebServer::CleanSessions() {
//_log.Log(LOG_STATUS, "SessionStore : clean...");
m_sql.safe_query(
"DELETE FROM UserSessions WHERE ExpirationDate < datetime('now', 'localtime')");
}
/**
* Delete all user's session, except the session used to modify the username or password.
* username must have been hashed
*
* Note : on the WebUserName modification, this method will not delete the session, but the session will be deleted anyway
* because the username will be unknown (see cWebemRequestHandler::checkAuthToken).
*/
void CWebServer::RemoveUsersSessions(const std::string& username, const WebEmSession & exceptSession) {
m_sql.safe_query("DELETE FROM UserSessions WHERE (Username=='%q') and (SessionID!='%q')", username.c_str(), exceptSession.id.c_str());
}
} //server
}//http
| ./CrossVul/dataset_final_sorted/CWE-89/cpp/bad_762_0 |
crossvul-cpp_data_bad_3567_3 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC1939 POP3 protocol
* RFC2384 POP URL Scheme
* RFC2595 Using TLS with IMAP, POP3 and ACAP
*
***************************************************************************/
#include "setup.h"
#ifndef CURL_DISABLE_POP3
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "if2ip.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "pop3.h"
#include "strtoofft.h"
#include "strequal.h"
#include "sslgen.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "rawstr.h"
#include "strtoofft.h"
#include "http_proxy.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/* Local API functions */
static CURLcode pop3_parse_url_path(struct connectdata *conn);
static CURLcode pop3_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode pop3_do(struct connectdata *conn, bool *done);
static CURLcode pop3_done(struct connectdata *conn,
CURLcode, bool premature);
static CURLcode pop3_connect(struct connectdata *conn, bool *done);
static CURLcode pop3_disconnect(struct connectdata *conn, bool dead);
static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done);
static int pop3_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks);
static CURLcode pop3_doing(struct connectdata *conn,
bool *dophase_done);
static CURLcode pop3_setup_connection(struct connectdata * conn);
/*
* POP3 protocol handler.
*/
const struct Curl_handler Curl_handler_pop3 = {
"POP3", /* scheme */
pop3_setup_connection, /* setup_connection */
pop3_do, /* do_it */
pop3_done, /* done */
ZERO_NULL, /* do_more */
pop3_connect, /* connect_it */
pop3_multi_statemach, /* connecting */
pop3_doing, /* doing */
pop3_getsock, /* proto_getsock */
pop3_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
pop3_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3, /* defport */
CURLPROTO_POP3, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */
};
#ifdef USE_SSL
/*
* POP3S protocol handler.
*/
const struct Curl_handler Curl_handler_pop3s = {
"POP3S", /* scheme */
pop3_setup_connection, /* setup_connection */
pop3_do, /* do_it */
pop3_done, /* done */
ZERO_NULL, /* do_more */
pop3_connect, /* connect_it */
pop3_multi_statemach, /* connecting */
pop3_doing, /* doing */
pop3_getsock, /* proto_getsock */
pop3_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
pop3_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3S, /* defport */
CURLPROTO_POP3 | CURLPROTO_POP3S, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL
| PROTOPT_NOURLQUERY /* flags */
};
#endif
#ifndef CURL_DISABLE_HTTP
/*
* HTTP-proxyed POP3 protocol handler.
*/
static const struct Curl_handler Curl_handler_pop3_proxy = {
"POP3", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* HTTP-proxyed POP3S protocol handler.
*/
static const struct Curl_handler Curl_handler_pop3s_proxy = {
"POP3S", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3S, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#endif
#endif
/* function that checks for a pop3 status code at the start of the given
string */
static int pop3_endofresp(struct pingpong *pp,
int *resp)
{
char *line = pp->linestart_resp;
size_t len = pp->nread_resp;
if(((len >= 3) && !memcmp("+OK", line, 3)) ||
((len >= 4) && !memcmp("-ERR", line, 4))) {
*resp=line[1]; /* O or E */
return TRUE;
}
return FALSE; /* nothing for us */
}
/* This is the ONLY way to change POP3 state! */
static void state(struct connectdata *conn,
pop3state newstate)
{
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[]={
"STOP",
"SERVERGREET",
"USER",
"PASS",
"STARTTLS",
"LIST",
"LIST_SINGLE",
"RETR",
"QUIT",
/* LAST */
};
#endif
struct pop3_conn *pop3c = &conn->proto.pop3c;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
if(pop3c->state != newstate)
infof(conn->data, "POP3 %p state change from %s to %s\n",
pop3c, names[pop3c->state], names[newstate]);
#endif
pop3c->state = newstate;
}
static CURLcode pop3_state_user(struct connectdata *conn)
{
CURLcode result;
struct FTP *pop3 = conn->data->state.proto.pop3;
/* send USER */
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "USER %s",
pop3->user?pop3->user:"");
if(result)
return result;
state(conn, POP3_USER);
return CURLE_OK;
}
/* For the POP3 "protocol connect" and "doing" phases only */
static int pop3_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.pop3c.pp, socks, numsocks);
}
#ifdef USE_SSL
static void pop3_to_pop3s(struct connectdata *conn)
{
conn->handler = &Curl_handler_pop3s;
}
#else
#define pop3_to_pop3s(x) Curl_nop_stmt
#endif
/* for STARTTLS responses */
static CURLcode pop3_state_starttls_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied. %c", pop3code);
result = CURLE_USE_SSL_FAILED;
state(conn, POP3_STOP);
}
else
result = pop3_state_user(conn);
}
else {
/* Curl_ssl_connect is BLOCKING */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(CURLE_OK == result) {
pop3_to_pop3s(conn);
result = pop3_state_user(conn);
}
else {
state(conn, POP3_STOP);
}
}
return result;
}
/* for USER responses */
static CURLcode pop3_state_user_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
failf(data, "Access denied. %c", pop3code);
result = CURLE_LOGIN_DENIED;
}
else
/* send PASS */
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "PASS %s",
pop3->passwd?pop3->passwd:"");
if(result)
return result;
state(conn, POP3_PASS);
return result;
}
/* for PASS responses */
static CURLcode pop3_state_pass_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
failf(data, "Access denied. %c", pop3code);
result = CURLE_LOGIN_DENIED;
}
state(conn, POP3_STOP);
return result;
}
/* for the retr response */
static CURLcode pop3_state_retr_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
(void)instate; /* no use for this yet */
if('O' != pop3code) {
state(conn, POP3_STOP);
return CURLE_RECV_ERROR;
}
/* POP3 download */
Curl_setup_transfer(conn, FIRSTSOCKET, -1, FALSE,
pop3->bytecountp, -1, NULL); /* no upload here */
if(pp->cache) {
/* At this point there is a bunch of data in the header "cache" that is
actually body content, send it as body and then skip it. Do note
that there may even be additional "headers" after the body. */
/* we may get the EOB already here! */
result = Curl_pop3_write(conn, pp->cache, pp->cache_size);
if(result)
return result;
/* cache is drained */
free(pp->cache);
pp->cache = NULL;
pp->cache_size = 0;
}
state(conn, POP3_STOP);
return result;
}
/* for the list response */
static CURLcode pop3_state_list_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
(void)instate; /* no use for this yet */
if('O' != pop3code) {
state(conn, POP3_STOP);
return CURLE_RECV_ERROR;
}
/* This 'OK' line ends with a CR LF pair which is the two first bytes of the
EOB string so count this is two matching bytes. This is necessary to make
the code detect the EOB if the only data than comes now is %2e CR LF like
when there is no body to return. */
pop3c->eob = 2;
/* But since this initial CR LF pair is not part of the actual body, we set
the strip counter here so that these bytes won't be delivered. */
pop3c->strip = 2;
/* POP3 download */
Curl_setup_transfer(conn, FIRSTSOCKET, -1, FALSE, pop3->bytecountp,
-1, NULL); /* no upload here */
if(pp->cache) {
/* cache holds the email ID listing */
/* we may get the EOB already here! */
result = Curl_pop3_write(conn, pp->cache, pp->cache_size);
if(result)
return result;
/* cache is drained */
free(pp->cache);
pp->cache = NULL;
pp->cache_size = 0;
}
state(conn, POP3_STOP);
return result;
}
/* for LIST response with a given message */
static CURLcode pop3_state_list_single_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
failf(data, "Invalid message. %c", pop3code);
result = CURLE_REMOTE_FILE_NOT_FOUND;
}
state(conn, POP3_STOP);
return result;
}
/* start the DO phase for RETR */
static CURLcode pop3_retr(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct pop3_conn *pop3c = &conn->proto.pop3c;
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "RETR %s", pop3c->mailbox);
if(result)
return result;
state(conn, POP3_RETR);
return result;
}
/* start the DO phase for LIST */
static CURLcode pop3_list(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct pop3_conn *pop3c = &conn->proto.pop3c;
if(pop3c->mailbox[0] != '\0')
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "LIST %s", pop3c->mailbox);
else
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "LIST");
if(result)
return result;
if(pop3c->mailbox[0] != '\0')
state(conn, POP3_LIST_SINGLE);
else
state(conn, POP3_LIST);
return result;
}
static CURLcode pop3_statemach_act(struct connectdata *conn)
{
CURLcode result;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct SessionHandle *data=conn->data;
int pop3code;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
size_t nread = 0;
if(pp->sendleft)
return Curl_pp_flushsend(pp);
/* we read a piece of response */
result = Curl_pp_readresp(sock, pp, &pop3code, &nread);
if(result)
return result;
if(pop3code) {
/* we have now received a full POP3 server response */
switch(pop3c->state) {
case POP3_SERVERGREET:
if(pop3code != 'O') {
failf(data, "Got unexpected pop3-server response");
return CURLE_FTP_WEIRD_SERVER_REPLY;
}
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested. Switch
to TLS connection now */
result = Curl_pp_sendf(&pop3c->pp, "STLS");
state(conn, POP3_STARTTLS);
}
else
result = pop3_state_user(conn);
if(result)
return result;
break;
case POP3_USER:
result = pop3_state_user_resp(conn, pop3code, pop3c->state);
break;
case POP3_PASS:
result = pop3_state_pass_resp(conn, pop3code, pop3c->state);
break;
case POP3_STARTTLS:
result = pop3_state_starttls_resp(conn, pop3code, pop3c->state);
break;
case POP3_RETR:
result = pop3_state_retr_resp(conn, pop3code, pop3c->state);
break;
case POP3_LIST:
result = pop3_state_list_resp(conn, pop3code, pop3c->state);
break;
case POP3_LIST_SINGLE:
result = pop3_state_list_single_resp(conn, pop3code, pop3c->state);
break;
case POP3_QUIT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, POP3_STOP);
break;
}
}
return result;
}
/* called repeatedly until done from multi.c */
static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done)
{
struct pop3_conn *pop3c = &conn->proto.pop3c;
CURLcode result = Curl_pp_multi_statemach(&pop3c->pp);
*done = (pop3c->state == POP3_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode pop3_easy_statemach(struct connectdata *conn)
{
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
CURLcode result = CURLE_OK;
while(pop3c->state != POP3_STOP) {
result = Curl_pp_easy_statemach(pp);
if(result)
break;
}
return result;
}
/*
* Allocate and initialize the struct POP3 for the current SessionHandle. If
* need be.
*/
static CURLcode pop3_init(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
if(!pop3) {
pop3 = data->state.proto.pop3 = calloc(sizeof(struct FTP), 1);
if(!pop3)
return CURLE_OUT_OF_MEMORY;
}
/* get some initial data into the pop3 struct */
pop3->bytecountp = &data->req.bytecount;
/* No need to duplicate user+password, the connectdata struct won't change
during a session, but we re-init them here since on subsequent inits
since the conn struct may have changed or been replaced.
*/
pop3->user = conn->user;
pop3->passwd = conn->passwd;
return CURLE_OK;
}
/*
* pop3_connect() should do everything that is to be considered a part of
* the connection phase.
*
* The variable 'done' points to will be TRUE if the protocol-layer connect
* phase is done when this function returns, or FALSE is not. When called as
* a part of the easy interface, it will always be TRUE.
*/
static CURLcode pop3_connect(struct connectdata *conn,
bool *done) /* see description above */
{
CURLcode result;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct SessionHandle *data=conn->data;
struct pingpong *pp = &pop3c->pp;
*done = FALSE; /* default to not done yet */
/* If there already is a protocol-specific struct allocated for this
sessionhandle, deal with it */
Curl_reset_reqproto(conn);
result = pop3_init(conn);
if(CURLE_OK != result)
return result;
/* We always support persistent connections on pop3 */
conn->bits.close = FALSE;
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = pop3_statemach_act;
pp->endofresp = pop3_endofresp;
pp->conn = conn;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
/* for POP3 over HTTP proxy */
struct HTTP http_proxy;
struct FTP *pop3_save;
/* BLOCKING */
/* We want "seamless" POP3 operations through HTTP proxy tunnel */
/* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the member
* conn->proto.http; we want POP3 through HTTP and we have to change the
* member temporarily for connecting to the HTTP proxy. After
* Curl_proxyCONNECT we have to set back the member to the original struct
* POP3 pointer
*/
pop3_save = data->state.proto.pop3;
memset(&http_proxy, 0, sizeof(http_proxy));
data->state.proto.http = &http_proxy;
result = Curl_proxyCONNECT(conn, FIRSTSOCKET,
conn->host.name, conn->remote_port);
data->state.proto.pop3 = pop3_save;
if(CURLE_OK != result)
return result;
}
if(conn->handler->flags & PROTOPT_SSL) {
/* BLOCKING */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(result)
return result;
}
Curl_pp_init(pp); /* init the response reader stuff */
/* When we connect, we start in the state where we await the server greet
response */
state(conn, POP3_SERVERGREET);
if(data->state.used_interface == Curl_if_multi)
result = pop3_multi_statemach(conn, done);
else {
result = pop3_easy_statemach(conn);
if(!result)
*done = TRUE;
}
return result;
}
/***********************************************************************
*
* pop3_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
bool premature)
{
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
struct pop3_conn *pop3c = &conn->proto.pop3c;
CURLcode result=CURLE_OK;
(void)premature;
if(!pop3)
/* When the easy handle is removed from the multi while libcurl is still
* trying to resolve the host name, it seems that the pop3 struct is not
* yet initialized, but the removal action calls Curl_done() which calls
* this function. So we simply return success if no pop3 pointer is set.
*/
return CURLE_OK;
if(status) {
conn->bits.close = TRUE; /* marked for closure */
result = status; /* use the already set error code */
}
Curl_safefree(pop3c->mailbox);
pop3c->mailbox = NULL;
/* clear these for next connection */
pop3->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* pop3_perform()
*
* This is the actual DO function for POP3. Get a file/directory according to
* the options previously setup.
*/
static
CURLcode pop3_perform(struct connectdata *conn,
bool *connected, /* connect status after PASV / PORT */
bool *dophase_done)
{
/* this is POP3 and no proxy */
CURLcode result=CURLE_OK;
struct pop3_conn *pop3c = &conn->proto.pop3c;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(conn->data->set.opt_no_body) {
/* requested no body means no transfer... */
struct FTP *pop3 = conn->data->state.proto.pop3;
pop3->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* start the first command in the DO phase */
/* If mailbox is empty, then assume user wants listing for mail IDs,
* otherwise, attempt to retrieve the mail-id stored in mailbox
*/
if(strlen(pop3c->mailbox) && !conn->data->set.ftp_list_only)
result = pop3_retr(conn);
else
result = pop3_list(conn);
if(result)
return result;
/* run the state-machine */
if(conn->data->state.used_interface == Curl_if_multi)
result = pop3_multi_statemach(conn, dophase_done);
else {
result = pop3_easy_statemach(conn);
*dophase_done = TRUE; /* with the easy interface we are done here */
}
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* pop3_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (pop3_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode pop3_do(struct connectdata *conn, bool *done)
{
CURLcode retcode = CURLE_OK;
*done = FALSE; /* default to false */
/*
Since connections can be re-used between SessionHandles, this might be a
connection already existing but on a fresh SessionHandle struct so we must
make sure we have a good 'struct POP3' to play with. For new connections,
the struct POP3 is allocated and setup in the pop3_connect() function.
*/
Curl_reset_reqproto(conn);
retcode = pop3_init(conn);
if(retcode)
return retcode;
retcode = pop3_parse_url_path(conn);
if(retcode)
return retcode;
retcode = pop3_regular_transfer(conn, done);
return retcode;
}
/***********************************************************************
*
* pop3_quit()
*
* This should be called before calling sclose(). We should then wait for the
* response from the server before returning. The calling code should then try
* to close the connection.
*
*/
static CURLcode pop3_quit(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "QUIT", NULL);
if(result)
return result;
state(conn, POP3_QUIT);
result = pop3_easy_statemach(conn);
return result;
}
/***********************************************************************
*
* pop3_disconnect()
*
* Disconnect from an POP3 server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode pop3_disconnect(struct connectdata *conn, bool dead_connection)
{
struct pop3_conn *pop3c= &conn->proto.pop3c;
/* We cannot send quit unconditionally. If this connection is stale or
bad in any way, sending quit and waiting around here will make the
disconnect wait in vain and cause more problems than we need to.
*/
/* The POP3 session may or may not have been allocated/setup at this
point! */
if(!dead_connection && pop3c->pp.conn)
(void)pop3_quit(conn); /* ignore errors on the LOGOUT */
Curl_pp_disconnect(&pop3c->pp);
return CURLE_OK;
}
/***********************************************************************
*
* pop3_parse_url_path()
*
* Parse the URL path into separate path components.
*
*/
static CURLcode pop3_parse_url_path(struct connectdata *conn)
{
/* the pop3 struct is already inited in pop3_connect() */
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
/* url decode the path and use this mailbox */
pop3c->mailbox = curl_easy_unescape(data, path, 0, NULL);
if(!pop3c->mailbox)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
/* call this when the DO phase has completed */
static CURLcode pop3_dophase_done(struct connectdata *conn,
bool connected)
{
struct FTP *pop3 = conn->data->state.proto.pop3;
(void)connected;
if(pop3->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
return CURLE_OK;
}
/* called from multi.c while DOing */
static CURLcode pop3_doing(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result;
result = pop3_multi_statemach(conn, dophase_done);
if(*dophase_done) {
result = pop3_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* pop3_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*
*/
static
CURLcode pop3_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result=CURLE_OK;
bool connected=FALSE;
struct SessionHandle *data = conn->data;
data->req.size = -1; /* make sure this is unknown at this point */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, 0);
Curl_pgrsSetDownloadSize(data, 0);
result = pop3_perform(conn,
&connected, /* have we connected after PASV/PORT */
dophase_done); /* all commands in the DO-phase done? */
if(CURLE_OK == result) {
if(!*dophase_done)
/* the DO phase has not completed yet */
return CURLE_OK;
result = pop3_dophase_done(conn, connected);
if(result)
return result;
}
return result;
}
static CURLcode pop3_setup_connection(struct connectdata * conn)
{
struct SessionHandle *data = conn->data;
if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
/* Unless we have asked to tunnel pop3 operations through the proxy, we
switch and use HTTP operations only */
#ifndef CURL_DISABLE_HTTP
if(conn->handler == &Curl_handler_pop3)
conn->handler = &Curl_handler_pop3_proxy;
else {
#ifdef USE_SSL
conn->handler = &Curl_handler_pop3s_proxy;
#else
failf(data, "POP3S not supported!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
/*
* We explicitly mark this connection as persistent here as we're doing
* POP3 over HTTP and thus we accidentally avoid setting this value
* otherwise.
*/
conn->bits.close = FALSE;
#else
failf(data, "POP3 over http proxy requires HTTP support built-in!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
/* this is the 5-bytes End-Of-Body marker for POP3 */
#define POP3_EOB "\x0d\x0a\x2e\x0d\x0a"
#define POP3_EOB_LEN 5
/*
* This function scans the body after the end-of-body and writes everything
* until the end is found.
*/
CURLcode Curl_pop3_write(struct connectdata *conn,
char *str,
size_t nread)
{
/* This code could be made into a special function in the handler struct. */
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct SingleRequest *k = &data->req;
struct pop3_conn *pop3c = &conn->proto.pop3c;
bool strip_dot = FALSE;
size_t last = 0;
size_t i;
/* Search through the buffer looking for the end-of-body marker which is
5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches
the eob so the server will have prefixed it with an extra dot which we
need to strip out. Additionally the marker could of course be spread out
over 5 different data chunks */
for(i = 0; i < nread; i++) {
size_t prev = pop3c->eob;
switch(str[i]) {
case 0x0d:
if(pop3c->eob == 0) {
pop3c->eob++;
if(i) {
/* Write out the body part that didn't match */
result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
i - last);
if(result)
return result;
last = i;
}
}
else if(pop3c->eob == 3)
pop3c->eob++;
else
/* If the character match wasn't at position 0 or 3 then restart the
pattern matching */
pop3c->eob = 1;
break;
case 0x0a:
if(pop3c->eob == 1 || pop3c->eob == 4)
pop3c->eob++;
else
/* If the character match wasn't at position 1 or 4 then start the
search again */
pop3c->eob = 0;
break;
case 0x2e:
if(pop3c->eob == 2)
pop3c->eob++;
else if(pop3c->eob == 3) {
/* We have an extra dot after the CRLF which we need to strip off */
strip_dot = TRUE;
pop3c->eob = 0;
}
else
/* If the character match wasn't at position 2 then start the search
again */
pop3c->eob = 0;
break;
default:
pop3c->eob = 0;
break;
}
/* Did we have a partial match which has subsequently failed? */
if(prev && prev >= pop3c->eob) {
/* Strip can only be non-zero for the very first mismatch after CRLF
and then both prev and strip are equal and nothing will be output
below */
while(prev && pop3c->strip) {
prev--;
pop3c->strip--;
}
if(prev) {
/* If the partial match was the CRLF and dot then only write the CRLF
as the server would have inserted the dot */
result = Curl_client_write(conn, CLIENTWRITE_BODY, (char*)POP3_EOB,
strip_dot ? prev - 1 : prev);
if(result)
return result;
last = i;
strip_dot = FALSE;
}
}
}
if(pop3c->eob == POP3_EOB_LEN) {
/* We have a full match so the transfer is done! */
k->keepon &= ~KEEP_RECV;
pop3c->eob = 0;
return CURLE_OK;
}
if(pop3c->eob)
/* While EOB is matching nothing should be output */
return CURLE_OK;
if(nread - last) {
result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
nread - last);
}
return result;
}
#endif /* CURL_DISABLE_POP3 */
| ./CrossVul/dataset_final_sorted/CWE-89/c/bad_3567_3 |
crossvul-cpp_data_bad_3567_2 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC3501 IMAPv4 protocol
* RFC5092 IMAP URL Scheme
*
***************************************************************************/
#include "setup.h"
#ifndef CURL_DISABLE_IMAP
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "if2ip.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "imap.h"
#include "strtoofft.h"
#include "strequal.h"
#include "sslgen.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "rawstr.h"
#include "strtoofft.h"
#include "http_proxy.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/* Local API functions */
static CURLcode imap_parse_url_path(struct connectdata *conn);
static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode imap_do(struct connectdata *conn, bool *done);
static CURLcode imap_done(struct connectdata *conn,
CURLcode, bool premature);
static CURLcode imap_connect(struct connectdata *conn, bool *done);
static CURLcode imap_disconnect(struct connectdata *conn, bool dead);
static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done);
static int imap_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks);
static CURLcode imap_doing(struct connectdata *conn,
bool *dophase_done);
static CURLcode imap_setup_connection(struct connectdata * conn);
static CURLcode imap_state_upgrade_tls(struct connectdata *conn);
/*
* IMAP protocol handler.
*/
const struct Curl_handler Curl_handler_imap = {
"IMAP", /* scheme */
imap_setup_connection, /* setup_connection */
imap_do, /* do_it */
imap_done, /* done */
ZERO_NULL, /* do_more */
imap_connect, /* connect_it */
imap_multi_statemach, /* connecting */
imap_doing, /* doing */
imap_getsock, /* proto_getsock */
imap_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAP, /* defport */
CURLPROTO_IMAP, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD
| PROTOPT_NOURLQUERY /* flags */
};
#ifdef USE_SSL
/*
* IMAPS protocol handler.
*/
const struct Curl_handler Curl_handler_imaps = {
"IMAPS", /* scheme */
imap_setup_connection, /* setup_connection */
imap_do, /* do_it */
imap_done, /* done */
ZERO_NULL, /* do_more */
imap_connect, /* connect_it */
imap_multi_statemach, /* connecting */
imap_doing, /* doing */
imap_getsock, /* proto_getsock */
imap_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAPS, /* defport */
CURLPROTO_IMAP | CURLPROTO_IMAPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL | PROTOPT_NEEDSPWD
| PROTOPT_NOURLQUERY /* flags */
};
#endif
#ifndef CURL_DISABLE_HTTP
/*
* HTTP-proxyed IMAP protocol handler.
*/
static const struct Curl_handler Curl_handler_imap_proxy = {
"IMAP", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAP, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* HTTP-proxyed IMAPS protocol handler.
*/
static const struct Curl_handler Curl_handler_imaps_proxy = {
"IMAPS", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAPS, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#endif
#endif
/***********************************************************************
*
* imapsendf()
*
* Sends the formated string as an IMAP command to a server
*
* Designed to never block.
*/
static CURLcode imapsendf(struct connectdata *conn,
const char *idstr, /* id to wait for at the
completion of this command */
const char *fmt, ...)
{
CURLcode res;
struct imap_conn *imapc = &conn->proto.imapc;
va_list ap;
va_start(ap, fmt);
imapc->idstr = idstr; /* this is the thing */
res = Curl_pp_vsendf(&imapc->pp, fmt, ap);
va_end(ap);
return res;
}
static const char *getcmdid(struct connectdata *conn)
{
static const char * const ids[]= {
"A",
"B",
"C",
"D"
};
struct imap_conn *imapc = &conn->proto.imapc;
/* get the next id, but wrap at end of table */
imapc->cmdid = (int)((imapc->cmdid+1) % (sizeof(ids)/sizeof(ids[0])));
return ids[imapc->cmdid];
}
/* For the IMAP "protocol connect" and "doing" phases only */
static int imap_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.imapc.pp, socks, numsocks);
}
/* function that checks for an imap status code at the start of the
given string */
static int imap_endofresp(struct pingpong *pp, int *resp)
{
char *line = pp->linestart_resp;
size_t len = pp->nread_resp;
struct imap_conn *imapc = &pp->conn->proto.imapc;
const char *id = imapc->idstr;
size_t id_len = strlen(id);
if(len >= id_len + 3) {
if(!memcmp(id, line, id_len) && (line[id_len] == ' ') ) {
/* end of response */
*resp = line[id_len+1]; /* O, N or B */
return TRUE;
}
else if((imapc->state == IMAP_FETCH) &&
!memcmp("* ", line, 2) ) {
/* FETCH response we're interested in */
*resp = '*';
return TRUE;
}
}
return FALSE; /* nothing for us */
}
/* This is the ONLY way to change IMAP state! */
static void state(struct connectdata *conn,
imapstate newstate)
{
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[]={
"STOP",
"SERVERGREET",
"LOGIN",
"STARTTLS",
"UPGRADETLS",
"SELECT",
"FETCH",
"LOGOUT",
/* LAST */
};
#endif
struct imap_conn *imapc = &conn->proto.imapc;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
if(imapc->state != newstate)
infof(conn->data, "IMAP %p state change from %s to %s\n",
imapc, names[imapc->state], names[newstate]);
#endif
imapc->state = newstate;
}
static CURLcode imap_state_login(struct connectdata *conn)
{
CURLcode result;
struct FTP *imap = conn->data->state.proto.imap;
const char *str;
str = getcmdid(conn);
/* send USER and password */
result = imapsendf(conn, str, "%s LOGIN %s %s", str,
imap->user?imap->user:"",
imap->passwd?imap->passwd:"");
if(result)
return result;
state(conn, IMAP_LOGIN);
return CURLE_OK;
}
#ifdef USE_SSL
static void imap_to_imaps(struct connectdata *conn)
{
conn->handler = &Curl_handler_imaps;
}
#else
#define imap_to_imaps(x) Curl_nop_stmt
#endif
/* for STARTTLS responses */
static CURLcode imap_state_starttls_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied. %c", imapcode);
result = CURLE_USE_SSL_FAILED;
}
else
result = imap_state_login(conn);
}
else {
if(data->state.used_interface == Curl_if_multi) {
state(conn, IMAP_UPGRADETLS);
return imap_state_upgrade_tls(conn);
}
else {
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(CURLE_OK == result) {
imap_to_imaps(conn);
result = imap_state_login(conn);
}
}
}
state(conn, IMAP_STOP);
return result;
}
static CURLcode imap_state_upgrade_tls(struct connectdata *conn)
{
struct imap_conn *imapc = &conn->proto.imapc;
CURLcode result;
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
if(imapc->ssldone) {
imap_to_imaps(conn);
result = imap_state_login(conn);
state(conn, IMAP_STOP);
}
return result;
}
/* for LOGIN responses */
static CURLcode imap_state_login_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
failf(data, "Access denied. %c", imapcode);
result = CURLE_LOGIN_DENIED;
}
state(conn, IMAP_STOP);
return result;
}
/* for the (first line of) FETCH BODY[TEXT] response */
static CURLcode imap_state_fetch_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct imap_conn *imapc = &conn->proto.imapc;
struct FTP *imap = data->state.proto.imap;
struct pingpong *pp = &imapc->pp;
const char *ptr = data->state.buffer;
(void)instate; /* no use for this yet */
if('*' != imapcode) {
Curl_pgrsSetDownloadSize(data, 0);
state(conn, IMAP_STOP);
return CURLE_OK;
}
/* Something like this comes "* 1 FETCH (BODY[TEXT] {2021}\r" */
while(*ptr && (*ptr != '{'))
ptr++;
if(*ptr == '{') {
curl_off_t filesize = curlx_strtoofft(ptr+1, NULL, 10);
if(filesize)
Curl_pgrsSetDownloadSize(data, filesize);
infof(data, "Found %" FORMAT_OFF_TU " bytes to download\n", filesize);
if(pp->cache) {
/* At this point there is a bunch of data in the header "cache" that is
actually body content, send it as body and then skip it. Do note
that there may even be additional "headers" after the body. */
size_t chunk = pp->cache_size;
if(chunk > (size_t)filesize)
/* the conversion from curl_off_t to size_t is always fine here */
chunk = (size_t)filesize;
result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
if(result)
return result;
filesize -= chunk;
/* we've now used parts of or the entire cache */
if(pp->cache_size > chunk) {
/* part of, move the trailing data to the start and reduce the size */
memmove(pp->cache, pp->cache+chunk,
pp->cache_size - chunk);
pp->cache_size -= chunk;
}
else {
/* cache is drained */
free(pp->cache);
pp->cache = NULL;
pp->cache_size = 0;
}
}
infof(data, "Filesize left: %" FORMAT_OFF_T "\n", filesize);
if(!filesize)
/* the entire data is already transferred! */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
else
/* IMAP download */
Curl_setup_transfer(conn, FIRSTSOCKET, filesize, FALSE,
imap->bytecountp, -1, NULL); /* no upload here */
data->req.maxdownload = filesize;
}
else
/* We don't know how to parse this line */
result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: fix this code */
state(conn, IMAP_STOP);
return result;
}
/* start the DO phase */
static CURLcode imap_select(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
const char *str;
str = getcmdid(conn);
result = imapsendf(conn, str, "%s SELECT %s", str,
imapc->mailbox?imapc->mailbox:"");
if(result)
return result;
state(conn, IMAP_SELECT);
return result;
}
static CURLcode imap_fetch(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
const char *str;
str = getcmdid(conn);
/* TODO: make this select the correct mail
* Use "1 body[text]" to get the full mail body of mail 1
*/
result = imapsendf(conn, str, "%s FETCH 1 BODY[TEXT]", str);
if(result)
return result;
/*
* When issued, the server will respond with a single line similar to
* '* 1 FETCH (BODY[TEXT] {2021}'
*
* Identifying the fetch and how many bytes of contents we can expect. We
* must extract that number before continuing to "download as usual".
*/
state(conn, IMAP_FETCH);
return result;
}
/* for SELECT responses */
static CURLcode imap_state_select_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
failf(data, "Select failed");
result = CURLE_LOGIN_DENIED;
}
else
result = imap_fetch(conn);
return result;
}
static CURLcode imap_statemach_act(struct connectdata *conn)
{
CURLcode result;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct SessionHandle *data=conn->data;
int imapcode;
struct imap_conn *imapc = &conn->proto.imapc;
struct pingpong *pp = &imapc->pp;
size_t nread = 0;
/* busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
if(imapc->state == IMAP_UPGRADETLS)
return imap_state_upgrade_tls(conn);
if(pp->sendleft)
return Curl_pp_flushsend(pp);
/* we read a piece of response */
result = Curl_pp_readresp(sock, pp, &imapcode, &nread);
if(result)
return result;
if(imapcode)
/* we have now received a full IMAP server response */
switch(imapc->state) {
case IMAP_SERVERGREET:
if(imapcode != 'O') {
failf(data, "Got unexpected imap-server response");
return CURLE_FTP_WEIRD_SERVER_REPLY;
}
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested. Switch
to TLS connection now */
const char *str;
str = getcmdid(conn);
result = imapsendf(conn, str, "%s STARTTLS", str);
state(conn, IMAP_STARTTLS);
}
else
result = imap_state_login(conn);
if(result)
return result;
break;
case IMAP_LOGIN:
result = imap_state_login_resp(conn, imapcode, imapc->state);
break;
case IMAP_STARTTLS:
result = imap_state_starttls_resp(conn, imapcode, imapc->state);
break;
case IMAP_FETCH:
result = imap_state_fetch_resp(conn, imapcode, imapc->state);
break;
case IMAP_SELECT:
result = imap_state_select_resp(conn, imapcode, imapc->state);
break;
case IMAP_LOGOUT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, IMAP_STOP);
break;
}
return result;
}
/* called repeatedly until done from multi.c */
static CURLcode imap_multi_statemach(struct connectdata *conn,
bool *done)
{
struct imap_conn *imapc = &conn->proto.imapc;
CURLcode result;
if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone)
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
else
result = Curl_pp_multi_statemach(&imapc->pp);
*done = (imapc->state == IMAP_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode imap_easy_statemach(struct connectdata *conn)
{
struct imap_conn *imapc = &conn->proto.imapc;
struct pingpong *pp = &imapc->pp;
CURLcode result = CURLE_OK;
while(imapc->state != IMAP_STOP) {
result = Curl_pp_easy_statemach(pp);
if(result)
break;
}
return result;
}
/*
* Allocate and initialize the struct IMAP for the current SessionHandle. If
* need be.
*/
static CURLcode imap_init(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
struct FTP *imap = data->state.proto.imap;
if(!imap) {
imap = data->state.proto.imap = calloc(sizeof(struct FTP), 1);
if(!imap)
return CURLE_OUT_OF_MEMORY;
}
/* get some initial data into the imap struct */
imap->bytecountp = &data->req.bytecount;
/* No need to duplicate user+password, the connectdata struct won't change
during a session, but we re-init them here since on subsequent inits
since the conn struct may have changed or been replaced.
*/
imap->user = conn->user;
imap->passwd = conn->passwd;
return CURLE_OK;
}
/*
* imap_connect() should do everything that is to be considered a part of
* the connection phase.
*
* The variable 'done' points to will be TRUE if the protocol-layer connect
* phase is done when this function returns, or FALSE is not. When called as
* a part of the easy interface, it will always be TRUE.
*/
static CURLcode imap_connect(struct connectdata *conn,
bool *done) /* see description above */
{
CURLcode result;
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data=conn->data;
struct pingpong *pp = &imapc->pp;
*done = FALSE; /* default to not done yet */
/* If there already is a protocol-specific struct allocated for this
sessionhandle, deal with it */
Curl_reset_reqproto(conn);
result = imap_init(conn);
if(CURLE_OK != result)
return result;
/* We always support persistent connections on imap */
conn->bits.close = FALSE;
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = imap_statemach_act;
pp->endofresp = imap_endofresp;
pp->conn = conn;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
/* for IMAP over HTTP proxy */
struct HTTP http_proxy;
struct FTP *imap_save;
/* BLOCKING */
/* We want "seamless" IMAP operations through HTTP proxy tunnel */
/* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the member
* conn->proto.http; we want IMAP through HTTP and we have to change the
* member temporarily for connecting to the HTTP proxy. After
* Curl_proxyCONNECT we have to set back the member to the original struct
* IMAP pointer
*/
imap_save = data->state.proto.imap;
memset(&http_proxy, 0, sizeof(http_proxy));
data->state.proto.http = &http_proxy;
result = Curl_proxyCONNECT(conn, FIRSTSOCKET,
conn->host.name, conn->remote_port);
data->state.proto.imap = imap_save;
if(CURLE_OK != result)
return result;
}
if((conn->handler->flags & PROTOPT_SSL) &&
data->state.used_interface != Curl_if_multi) {
/* BLOCKING */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(result)
return result;
}
Curl_pp_init(pp); /* init generic pingpong data */
/* When we connect, we start in the state where we await the server greeting
response */
state(conn, IMAP_SERVERGREET);
imapc->idstr = "*"; /* we start off waiting for a '*' response */
if(data->state.used_interface == Curl_if_multi)
result = imap_multi_statemach(conn, done);
else {
result = imap_easy_statemach(conn);
if(!result)
*done = TRUE;
}
return result;
}
/***********************************************************************
*
* imap_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode imap_done(struct connectdata *conn, CURLcode status,
bool premature)
{
struct SessionHandle *data = conn->data;
struct FTP *imap = data->state.proto.imap;
CURLcode result=CURLE_OK;
(void)premature;
if(!imap)
/* When the easy handle is removed from the multi while libcurl is still
* trying to resolve the host name, it seems that the imap struct is not
* yet initialized, but the removal action calls Curl_done() which calls
* this function. So we simply return success if no imap pointer is set.
*/
return CURLE_OK;
if(status) {
conn->bits.close = TRUE; /* marked for closure */
result = status; /* use the already set error code */
}
/* clear these for next connection */
imap->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* imap_perform()
*
* This is the actual DO function for IMAP. Get a file/directory according to
* the options previously setup.
*/
static
CURLcode imap_perform(struct connectdata *conn,
bool *connected, /* connect status after PASV / PORT */
bool *dophase_done)
{
/* this is IMAP and no proxy */
CURLcode result=CURLE_OK;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(conn->data->set.opt_no_body) {
/* requested no body means no transfer... */
struct FTP *imap = conn->data->state.proto.imap;
imap->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* start the first command in the DO phase */
result = imap_select(conn);
if(result)
return result;
/* run the state-machine */
if(conn->data->state.used_interface == Curl_if_multi)
result = imap_multi_statemach(conn, dophase_done);
else {
result = imap_easy_statemach(conn);
*dophase_done = TRUE; /* with the easy interface we are done here */
}
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* imap_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (imap_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode imap_do(struct connectdata *conn, bool *done)
{
CURLcode retcode = CURLE_OK;
*done = FALSE; /* default to false */
/*
Since connections can be re-used between SessionHandles, this might be a
connection already existing but on a fresh SessionHandle struct so we must
make sure we have a good 'struct IMAP' to play with. For new connections,
the struct IMAP is allocated and setup in the imap_connect() function.
*/
Curl_reset_reqproto(conn);
retcode = imap_init(conn);
if(retcode)
return retcode;
retcode = imap_parse_url_path(conn);
if(retcode)
return retcode;
retcode = imap_regular_transfer(conn, done);
return retcode;
}
/***********************************************************************
*
* imap_logout()
*
* This should be called before calling sclose(). We should then wait for the
* response from the server before returning. The calling code should then try
* to close the connection.
*
*/
static CURLcode imap_logout(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
const char *str;
str = getcmdid(conn);
result = imapsendf(conn, str, "%s LOGOUT", str, NULL);
if(result)
return result;
state(conn, IMAP_LOGOUT);
result = imap_easy_statemach(conn);
return result;
}
/***********************************************************************
*
* imap_disconnect()
*
* Disconnect from an IMAP server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection)
{
struct imap_conn *imapc= &conn->proto.imapc;
/* The IMAP session may or may not have been allocated/setup at this
point! */
if(!dead_connection && imapc->pp.conn)
(void)imap_logout(conn); /* ignore errors on the LOGOUT */
Curl_pp_disconnect(&imapc->pp);
Curl_safefree(imapc->mailbox);
return CURLE_OK;
}
/***********************************************************************
*
* imap_parse_url_path()
*
* Parse the URL path into separate path components.
*
*/
static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
int len;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
imapc->mailbox = curl_easy_unescape(data, path, 0, &len);
if(!imapc->mailbox)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
/* call this when the DO phase has completed */
static CURLcode imap_dophase_done(struct connectdata *conn,
bool connected)
{
struct FTP *imap = conn->data->state.proto.imap;
(void)connected;
if(imap->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
return CURLE_OK;
}
/* called from multi.c while DOing */
static CURLcode imap_doing(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result;
result = imap_multi_statemach(conn, dophase_done);
if(*dophase_done) {
result = imap_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* imap_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*
*/
static
CURLcode imap_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result=CURLE_OK;
bool connected=FALSE;
struct SessionHandle *data = conn->data;
data->req.size = -1; /* make sure this is unknown at this point */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, 0);
Curl_pgrsSetDownloadSize(data, 0);
result = imap_perform(conn,
&connected, /* have we connected after PASV/PORT */
dophase_done); /* all commands in the DO-phase done? */
if(CURLE_OK == result) {
if(!*dophase_done)
/* the DO phase has not completed yet */
return CURLE_OK;
result = imap_dophase_done(conn, connected);
if(result)
return result;
}
return result;
}
static CURLcode imap_setup_connection(struct connectdata * conn)
{
struct SessionHandle *data = conn->data;
if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
/* Unless we have asked to tunnel imap operations through the proxy, we
switch and use HTTP operations only */
#ifndef CURL_DISABLE_HTTP
if(conn->handler == &Curl_handler_imap)
conn->handler = &Curl_handler_imap_proxy;
else {
#ifdef USE_SSL
conn->handler = &Curl_handler_imaps_proxy;
#else
failf(data, "IMAPS not supported!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
/*
* We explicitly mark this connection as persistent here as we're doing
* IMAP over HTTP and thus we accidentally avoid setting this value
* otherwise.
*/
conn->bits.close = FALSE;
#else
failf(data, "IMAP over http proxy requires HTTP support built-in!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
#endif /* CURL_DISABLE_IMAP */
| ./CrossVul/dataset_final_sorted/CWE-89/c/bad_3567_2 |
crossvul-cpp_data_good_5843_0 | /******************************************************************************
* $Id$
*
* Project: MapServer
* Purpose: PostGIS CONNECTIONTYPE support.
* Author: Paul Ramsey <pramsey@cleverelephant.ca>
* Dave Blasby <dblasby@gmail.com>
*
******************************************************************************
* Copyright (c) 2010 Paul Ramsey
* Copyright (c) 2002 Refractions Research
*
* 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 of this Software or works derived from this 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.
****************************************************************************/
/*
** Some theory of operation:
**
** Build SQL from DATA statement and LAYER state. SQL is always of the form:
**
** SELECT [this, that, other], geometry, uid
** FROM [table|(subquery) as sub]
** WHERE [box] AND [filter]
**
** So the geometry always resides at layer->numitems and the uid always
** resides at layer->numitems + 1
**
** Geometry is requested as Hex encoded WKB. The endian is always requested
** as the client endianness.
**
** msPostGISLayerWhichShapes creates SQL based on DATA and LAYER state,
** executes it, and places the un-read PGresult handle in the layerinfo->pgresult,
** setting the layerinfo->rownum to 0.
**
** msPostGISNextShape reads a row, increments layerinfo->rownum, and returns
** MS_SUCCESS, until rownum reaches ntuples, and it returns MS_DONE instead.
**
*/
/* GNU needs this for strcasestr */
#define _GNU_SOURCE
/* required for MSVC */
#define _USE_MATH_DEFINES
#include <assert.h>
#include <string.h>
#include <math.h>
#include "mapserver.h"
#include "maptime.h"
#include "mappostgis.h"
#define FP_EPSILON 1e-12
#define FP_EQ(a, b) (fabs((a)-(b)) < FP_EPSILON)
#define FP_LEFT -1
#define FP_RIGHT 1
#define FP_COLINEAR 0
#define SEGMENT_ANGLE 10.0
#define SEGMENT_MINPOINTS 10
#ifdef USE_POSTGIS
/*
** msPostGISCloseConnection()
**
** Handler registered witih msConnPoolRegister so that Mapserver
** can clean up open connections during a shutdown.
*/
void msPostGISCloseConnection(void *pgconn)
{
PQfinish((PGconn*)pgconn);
}
/*
** msPostGISCreateLayerInfo()
*/
msPostGISLayerInfo *msPostGISCreateLayerInfo(void)
{
msPostGISLayerInfo *layerinfo = msSmallMalloc(sizeof(msPostGISLayerInfo));
layerinfo->sql = NULL;
layerinfo->srid = NULL;
layerinfo->uid = NULL;
layerinfo->pgconn = NULL;
layerinfo->pgresult = NULL;
layerinfo->geomcolumn = NULL;
layerinfo->fromsource = NULL;
layerinfo->endian = 0;
layerinfo->rownum = 0;
layerinfo->version = 0;
layerinfo->paging = MS_TRUE;
return layerinfo;
}
/*
** msPostGISFreeLayerInfo()
*/
void msPostGISFreeLayerInfo(layerObj *layer)
{
msPostGISLayerInfo *layerinfo = NULL;
layerinfo = (msPostGISLayerInfo*)layer->layerinfo;
if ( layerinfo->sql ) free(layerinfo->sql);
if ( layerinfo->uid ) free(layerinfo->uid);
if ( layerinfo->srid ) free(layerinfo->srid);
if ( layerinfo->geomcolumn ) free(layerinfo->geomcolumn);
if ( layerinfo->fromsource ) free(layerinfo->fromsource);
if ( layerinfo->pgresult ) PQclear(layerinfo->pgresult);
if ( layerinfo->pgconn ) msConnPoolRelease(layer, layerinfo->pgconn);
free(layerinfo);
layer->layerinfo = NULL;
}
/*
** postgresqlNoticeHandler()
**
** Propagate messages from the database to the Mapserver log,
** set in PQsetNoticeProcessor during layer open.
*/
void postresqlNoticeHandler(void *arg, const char *message)
{
layerObj *lp;
lp = (layerObj*)arg;
if (lp->debug) {
msDebug("%s\n", message);
}
}
/*
** Expandable pointObj array. The lineObj unfortunately
** is not useful for this purpose, so we have this one.
*/
pointArrayObj*
pointArrayNew(int maxpoints)
{
pointArrayObj *d = msSmallMalloc(sizeof(pointArrayObj));
if ( maxpoints < 1 ) maxpoints = 1; /* Avoid a degenerate case */
d->maxpoints = maxpoints;
d->data = msSmallMalloc(maxpoints * sizeof(pointObj));
d->npoints = 0;
return d;
}
/*
** Utility function to creal up the pointArrayObj
*/
void
pointArrayFree(pointArrayObj *d)
{
if ( ! d ) return;
if ( d->data ) free(d->data);
free(d);
}
/*
** Add a pointObj to the pointObjArray, allocating
** extra storage space if we've used up our existing
** buffer.
*/
static int
pointArrayAddPoint(pointArrayObj *d, const pointObj *p)
{
if ( !p || !d ) return MS_FAILURE;
/* Avoid overwriting memory buffer */
if ( d->maxpoints - d->npoints == 0 ) {
d->maxpoints *= 2;
d->data = realloc(d->data, d->maxpoints * sizeof(pointObj));
}
d->data[d->npoints] = *p;
d->npoints++;
return MS_SUCCESS;
}
/*
** Pass an input type number through the PostGIS version
** type map array to handle the pre-2.0 incorrect WKB types
*/
static int
wkbTypeMap(wkbObj *w, int type)
{
if ( type < WKB_TYPE_COUNT )
return w->typemap[type];
else
return 0;
}
/*
** Read the WKB type number from a wkbObj without
** advancing the read pointer.
*/
static int
wkbType(wkbObj *w)
{
int t;
memcpy(&t, (w->ptr + 1), sizeof(int));
return wkbTypeMap(w,t);
}
/*
** Read the type number of the first element of a
** collection without advancing the read pointer.
*/
static int
wkbCollectionSubType(wkbObj *w)
{
int t;
memcpy(&t, (w->ptr + 1 + 4 + 4 + 1), sizeof(int));
return wkbTypeMap(w,t);
}
/*
** Read one byte from the WKB and advance the read pointer
*/
static char
wkbReadChar(wkbObj *w)
{
char c;
memcpy(&c, w->ptr, sizeof(char));
w->ptr += sizeof(char);
return c;
}
/*
** Read one integer from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline int
wkbReadInt(wkbObj *w)
{
int i;
memcpy(&i, w->ptr, sizeof(int));
w->ptr += sizeof(int);
return i;
}
/*
** Read one double from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline double
wkbReadDouble(wkbObj *w)
{
double d;
memcpy(&d, w->ptr, sizeof(double));
w->ptr += sizeof(double);
return d;
}
/*
** Read one pointObj (two doubles) from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline void
wkbReadPointP(wkbObj *w, pointObj *p)
{
memcpy(&(p->x), w->ptr, sizeof(double));
w->ptr += sizeof(double);
memcpy(&(p->y), w->ptr, sizeof(double));
w->ptr += sizeof(double);
}
/*
** Read one pointObj (two doubles) from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline pointObj
wkbReadPoint(wkbObj *w)
{
pointObj p;
wkbReadPointP(w, &p);
return p;
}
/*
** Read a "point array" and return an allocated lineObj.
** A point array is a WKB fragment that starts with a
** point count, which is followed by that number of doubles * 2.
** Linestrings, circular strings, polygon rings, all show this
** form.
*/
static void
wkbReadLine(wkbObj *w, lineObj *line)
{
int i;
pointObj p;
int npoints = wkbReadInt(w);
line->numpoints = npoints;
line->point = msSmallMalloc(npoints * sizeof(pointObj));
for ( i = 0; i < npoints; i++ ) {
wkbReadPointP(w, &p);
line->point[i] = p;
}
}
/*
** Advance the read pointer past a geometry without returning any
** values. Used for skipping un-drawable elements in a collection.
*/
static void
wkbSkipGeometry(wkbObj *w)
{
int type, npoints, nrings, ngeoms, i;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
switch(type) {
case WKB_POINT:
w->ptr += 2 * sizeof(double);
break;
case WKB_CIRCULARSTRING:
case WKB_LINESTRING:
npoints = wkbReadInt(w);
w->ptr += npoints * 2 * sizeof(double);
break;
case WKB_POLYGON:
nrings = wkbReadInt(w);
for ( i = 0; i < nrings; i++ ) {
npoints = wkbReadInt(w);
w->ptr += npoints * 2 * sizeof(double);
}
break;
case WKB_MULTIPOINT:
case WKB_MULTILINESTRING:
case WKB_MULTIPOLYGON:
case WKB_GEOMETRYCOLLECTION:
case WKB_COMPOUNDCURVE:
case WKB_CURVEPOLYGON:
case WKB_MULTICURVE:
case WKB_MULTISURFACE:
ngeoms = wkbReadInt(w);
for ( i = 0; i < ngeoms; i++ ) {
wkbSkipGeometry(w);
}
}
}
/*
** Convert a WKB point to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvPointToShape(wkbObj *w, shapeObj *shape)
{
int type;
lineObj line;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_POINT ) return MS_FAILURE;
if( ! (shape->type == MS_SHAPE_POINT) ) return MS_FAILURE;
line.numpoints = 1;
line.point = msSmallMalloc(sizeof(pointObj));
line.point[0] = wkbReadPoint(w);
msAddLineDirectly(shape, &line);
return MS_SUCCESS;
}
/*
** Convert a WKB line string to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvLineStringToShape(wkbObj *w, shapeObj *shape)
{
int type;
lineObj line;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_LINESTRING ) return MS_FAILURE;
wkbReadLine(w,&line);
msAddLineDirectly(shape, &line);
return MS_SUCCESS;
}
/*
** Convert a WKB polygon to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvPolygonToShape(wkbObj *w, shapeObj *shape)
{
int type;
int i, nrings;
lineObj line;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_POLYGON ) return MS_FAILURE;
/* How many rings? */
nrings = wkbReadInt(w);
/* Add each ring to the shape */
for( i = 0; i < nrings; i++ ) {
wkbReadLine(w,&line);
msAddLineDirectly(shape, &line);
}
return MS_SUCCESS;
}
/*
** Convert a WKB curve polygon to a shapeObj, advancing the read pointer as we go.
** The arc portions of the rings will be stroked to linestrings as they
** are read by the underlying circular string handling.
*/
static int
wkbConvCurvePolygonToShape(wkbObj *w, shapeObj *shape)
{
int type, i, ncomponents;
int failures = 0;
int was_poly = ( shape->type == MS_SHAPE_POLYGON );
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
ncomponents = wkbReadInt(w);
if( type != WKB_CURVEPOLYGON ) return MS_FAILURE;
/* Lower the allowed dimensionality so we can
* catch the linear ring components */
shape->type = MS_SHAPE_LINE;
for ( i = 0; i < ncomponents; i++ ) {
if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
wkbSkipGeometry(w);
failures++;
}
}
/* Go back to expected dimensionality */
if ( was_poly) shape->type = MS_SHAPE_POLYGON;
if ( failures == ncomponents )
return MS_FAILURE;
else
return MS_SUCCESS;
}
/*
** Convert a WKB circular string to a shapeObj, advancing the read pointer as we go.
** Arcs will be stroked to linestrings.
*/
static int
wkbConvCircularStringToShape(wkbObj *w, shapeObj *shape)
{
int type;
lineObj line = {0, NULL};
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_CIRCULARSTRING ) return MS_FAILURE;
/* Stroke the string into a point array */
if ( arcStrokeCircularString(w, SEGMENT_ANGLE, &line) == MS_FAILURE ) {
if(line.point) free(line.point);
return MS_FAILURE;
}
/* Fill in the lineObj */
if ( line.numpoints > 0 ) {
msAddLine(shape, &line);
if(line.point) free(line.point);
}
return MS_SUCCESS;
}
/*
** Compound curves need special handling. First we load
** each component of the curve on the a lineObj in a shape.
** Then we merge those lineObjs into a single lineObj. This
** allows compound curves to serve as closed rings in
** curve polygons.
*/
static int
wkbConvCompoundCurveToShape(wkbObj *w, shapeObj *shape)
{
int npoints = 0;
int type, ncomponents, i, j;
lineObj *line;
shapeObj shapebuf;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
/* Init our shape buffer */
msInitShape(&shapebuf);
if( type != WKB_COMPOUNDCURVE ) return MS_FAILURE;
/* How many components in the compound curve? */
ncomponents = wkbReadInt(w);
/* We'll load each component onto a line in a shape */
for( i = 0; i < ncomponents; i++ )
wkbConvGeometryToShape(w, &shapebuf);
/* Do nothing on empty */
if ( shapebuf.numlines == 0 )
return MS_FAILURE;
/* Count the total number of points */
for( i = 0; i < shapebuf.numlines; i++ )
npoints += shapebuf.line[i].numpoints;
/* Do nothing on empty */
if ( npoints == 0 )
return MS_FAILURE;
/* Allocate space for the new line */
line = msSmallMalloc(sizeof(lineObj));
line->numpoints = npoints;
line->point = msSmallMalloc(sizeof(pointObj) * npoints);
/* Copy in the points */
npoints = 0;
for ( i = 0; i < shapebuf.numlines; i++ ) {
for ( j = 0; j < shapebuf.line[i].numpoints; j++ ) {
/* Don't add a start point that duplicates an endpoint */
if( j == 0 && i > 0 &&
memcmp(&(line->point[npoints - 1]),&(shapebuf.line[i].point[j]),sizeof(pointObj)) == 0 ) {
continue;
}
line->point[npoints++] = shapebuf.line[i].point[j];
}
}
line->numpoints = npoints;
/* Clean up */
msFreeShape(&shapebuf);
/* Fill in the lineObj */
msAddLineDirectly(shape, line);
return MS_SUCCESS;
}
/*
** Convert a WKB collection string to a shapeObj, advancing the read pointer as we go.
** Many WKB types (MultiPoint, MultiLineString, MultiPolygon, MultiSurface,
** MultiCurve, GeometryCollection) can be treated identically as collections
** (they start with endian, type number and count of sub-elements, then provide the
** subelements as WKB) so are handled with this one function.
*/
static int
wkbConvCollectionToShape(wkbObj *w, shapeObj *shape)
{
int i, ncomponents;
int failures = 0;
/*endian = */wkbReadChar(w);
/*type = */wkbTypeMap(w,wkbReadInt(w));
ncomponents = wkbReadInt(w);
/*
* If we can draw any portion of the collection, we will,
* but if all the components fail, we will draw nothing.
*/
for ( i = 0; i < ncomponents; i++ ) {
if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
wkbSkipGeometry(w);
failures++;
}
}
if ( failures == ncomponents )
return MS_FAILURE;
else
return MS_SUCCESS;
}
/*
** Generic handler to switch to the appropriate function for the WKB type.
** Note that we also handle switching here to avoid processing shapes
** we will be unable to draw. Example: we can't draw point features as
** a MS_SHAPE_LINE layer, so if the type is WKB_POINT and the layer is
** MS_SHAPE_LINE, we exit before converting.
*/
int
wkbConvGeometryToShape(wkbObj *w, shapeObj *shape)
{
int wkbtype = wkbType(w); /* Peak at the type number */
switch(wkbtype) {
/* Recurse into anonymous collections */
case WKB_GEOMETRYCOLLECTION:
return wkbConvCollectionToShape(w, shape);
/* Handle area types */
case WKB_POLYGON:
return wkbConvPolygonToShape(w, shape);
case WKB_MULTIPOLYGON:
return wkbConvCollectionToShape(w, shape);
case WKB_CURVEPOLYGON:
return wkbConvCurvePolygonToShape(w, shape);
case WKB_MULTISURFACE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into polygons */
if ( shape->type == MS_SHAPE_POLYGON ) return MS_FAILURE;
/* Handle linear types */
switch(wkbtype) {
case WKB_LINESTRING:
return wkbConvLineStringToShape(w, shape);
case WKB_CIRCULARSTRING:
return wkbConvCircularStringToShape(w, shape);
case WKB_COMPOUNDCURVE:
return wkbConvCompoundCurveToShape(w, shape);
case WKB_MULTILINESTRING:
return wkbConvCollectionToShape(w, shape);
case WKB_MULTICURVE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into lines */
if ( shape->type == MS_SHAPE_LINE ) return MS_FAILURE;
/* Handle point types */
switch(wkbtype) {
case WKB_POINT:
return wkbConvPointToShape(w, shape);
case WKB_MULTIPOINT:
return wkbConvCollectionToShape(w, shape);
}
/* This is a WKB type we don't know about! */
return MS_FAILURE;
}
/*
** Calculate determinant of a 3x3 matrix. Handy for
** the circle center calculation.
*/
static inline double
arcDeterminant3x3(double *m)
{
/* This had better be a 3x3 matrix or we'll fall to bits */
return m[0] * ( m[4] * m[8] - m[7] * m[5] ) -
m[3] * ( m[1] * m[8] - m[7] * m[2] ) +
m[6] * ( m[1] * m[5] - m[4] * m[2] );
}
/*
** What side of p1->p2 is q on?
*/
static inline int
arcSegmentSide(const pointObj *p1, const pointObj *p2, const pointObj *q)
{
double side = ( (q->x - p1->x) * (p2->y - p1->y) - (p2->x - p1->x) * (q->y - p1->y) );
if ( FP_EQ(side,0.0) ) {
return FP_COLINEAR;
} else {
if ( side < 0.0 )
return FP_LEFT;
else
return FP_RIGHT;
}
}
/*
** Calculate the center of the circle defined by three points.
** Using matrix approach from http://mathforum.org/library/drmath/view/55239.html
*/
int
arcCircleCenter(const pointObj *p1, const pointObj *p2, const pointObj *p3, pointObj *center, double *radius)
{
pointObj c;
double r;
/* Components of the matrices. */
double x1sq = p1->x * p1->x;
double x2sq = p2->x * p2->x;
double x3sq = p3->x * p3->x;
double y1sq = p1->y * p1->y;
double y2sq = p2->y * p2->y;
double y3sq = p3->y * p3->y;
double matrix_num_x[9];
double matrix_num_y[9];
double matrix_denom[9];
/* Intialize matrix_num_x */
matrix_num_x[0] = x1sq+y1sq;
matrix_num_x[1] = p1->y;
matrix_num_x[2] = 1.0;
matrix_num_x[3] = x2sq+y2sq;
matrix_num_x[4] = p2->y;
matrix_num_x[5] = 1.0;
matrix_num_x[6] = x3sq+y3sq;
matrix_num_x[7] = p3->y;
matrix_num_x[8] = 1.0;
/* Intialize matrix_num_y */
matrix_num_y[0] = p1->x;
matrix_num_y[1] = x1sq+y1sq;
matrix_num_y[2] = 1.0;
matrix_num_y[3] = p2->x;
matrix_num_y[4] = x2sq+y2sq;
matrix_num_y[5] = 1.0;
matrix_num_y[6] = p3->x;
matrix_num_y[7] = x3sq+y3sq;
matrix_num_y[8] = 1.0;
/* Intialize matrix_denom */
matrix_denom[0] = p1->x;
matrix_denom[1] = p1->y;
matrix_denom[2] = 1.0;
matrix_denom[3] = p2->x;
matrix_denom[4] = p2->y;
matrix_denom[5] = 1.0;
matrix_denom[6] = p3->x;
matrix_denom[7] = p3->y;
matrix_denom[8] = 1.0;
/* Circle is closed, so p2 must be opposite p1 & p3. */
if ( FP_EQ(p1->x,p3->x) && FP_EQ(p1->y,p3->y) ) {
c.x = (p1->x + p2->x) / 2.0;
c.y = (p1->y + p2->y) / 2.0;
r = sqrt( (p1->x - p2->x) * (p1->x - p2->x) + (p1->y - p2->y) * (p1->y - p2->y) ) / 2.0;
}
/* There is no circle here, the points are actually co-linear */
else if ( arcSegmentSide(p1, p3, p2) == FP_COLINEAR ) {
return MS_FAILURE;
}
/* Calculate the center and radius. */
else {
double denom = 2.0 * arcDeterminant3x3(matrix_denom);
/* Center components */
c.x = arcDeterminant3x3(matrix_num_x) / denom;
c.y = arcDeterminant3x3(matrix_num_y) / denom;
/* Radius */
r = sqrt((p1->x-c.x) * (p1->x-c.x) + (p1->y-c.y) * (p1->y-c.y));
}
if ( radius ) *radius = r;
if ( center ) *center = c;
return MS_SUCCESS;
}
/*
** Write a stroked version of the circle defined by three points into a
** point buffer. The segment_angle (degrees) is the coverage of each stroke segment,
** and depending on whether this is the first arc in a circularstring,
** you might want to include_first
*/
int
arcStrokeCircle(const pointObj *p1, const pointObj *p2, const pointObj *p3,
double segment_angle, int include_first, pointArrayObj *pa)
{
pointObj center; /* Center of our circular arc */
double radius; /* Radius of our circular arc */
double sweep_angle_r; /* Total angular size of our circular arc in radians */
double segment_angle_r; /* Segment angle in radians */
double a1, /*a2,*/ a3; /* Angles represented by p1, p2, p3 relative to center */
int side = arcSegmentSide(p1, p3, p2); /* What side of p1,p3 is the middle point? */
int num_edges; /* How many edges we will be generating */
double current_angle_r; /* What angle are we generating now (radians)? */
int i; /* Counter */
pointObj p; /* Temporary point */
int is_closed = MS_FALSE;
/* We need to know if we're dealing with a circle early */
if ( FP_EQ(p1->x, p3->x) && FP_EQ(p1->y, p3->y) )
is_closed = MS_TRUE;
/* Check if the "arc" is actually straight */
if ( ! is_closed && side == FP_COLINEAR ) {
/* We just need to write in the end points */
if ( include_first )
pointArrayAddPoint(pa, p1);
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/* We should always be able to find the center of a non-linear arc */
if ( arcCircleCenter(p1, p2, p3, ¢er, &radius) == MS_FAILURE )
return MS_FAILURE;
/* Calculate the angles that our three points represent */
a1 = atan2(p1->y - center.y, p1->x - center.x);
/* UNUSED
a2 = atan2(p2->y - center.y, p2->x - center.x);
*/
a3 = atan2(p3->y - center.y, p3->x - center.x);
segment_angle_r = M_PI * segment_angle / 180.0;
/* Closed-circle case, we sweep the whole circle! */
if ( is_closed ) {
sweep_angle_r = 2.0 * M_PI;
}
/* Clockwise sweep direction */
else if ( side == FP_LEFT ) {
if ( a3 > a1 ) /* Wrapping past 180? */
sweep_angle_r = a1 + (2.0 * M_PI - a3);
else
sweep_angle_r = a1 - a3;
}
/* Counter-clockwise sweep direction */
else if ( side == FP_RIGHT ) {
if ( a3 > a1 ) /* Wrapping past 180? */
sweep_angle_r = a3 - a1;
else
sweep_angle_r = a3 + (2.0 * M_PI - a1);
} else
sweep_angle_r = 0.0;
/* We don't have enough resolution, let's invert our strategy. */
if ( (sweep_angle_r / segment_angle_r) < SEGMENT_MINPOINTS ) {
segment_angle_r = sweep_angle_r / (SEGMENT_MINPOINTS + 1);
}
/* We don't have enough resolution to stroke this arc,
* so just join the start to the end. */
if ( sweep_angle_r < segment_angle_r ) {
if ( include_first )
pointArrayAddPoint(pa, p1);
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/* How many edges to generate (we add the final edge
* by sticking on the last point */
num_edges = floor(sweep_angle_r / fabs(segment_angle_r));
/* Go backwards (negative angular steps) if we are stroking clockwise */
if ( side == FP_LEFT )
segment_angle_r *= -1;
/* What point should we start with? */
if( include_first ) {
current_angle_r = a1;
} else {
current_angle_r = a1 + segment_angle_r;
num_edges--;
}
/* For each edge, increment or decrement by our segment angle */
for( i = 0; i < num_edges; i++ ) {
if (segment_angle_r > 0.0 && current_angle_r > M_PI)
current_angle_r -= 2*M_PI;
if (segment_angle_r < 0.0 && current_angle_r < -1*M_PI)
current_angle_r -= 2*M_PI;
p.x = center.x + radius*cos(current_angle_r);
p.y = center.y + radius*sin(current_angle_r);
pointArrayAddPoint(pa, &p);
current_angle_r += segment_angle_r;
}
/* Add the last point */
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/*
** This function does not actually take WKB as input, it takes the
** WKB starting from the numpoints integer. Each three-point edge
** is stroked into a linestring and appended into the lineObj
** argument.
*/
int
arcStrokeCircularString(wkbObj *w, double segment_angle, lineObj *line)
{
pointObj p1, p2, p3;
int npoints, nedges;
int edge = 0;
pointArrayObj *pa;
if ( ! w || ! line ) return MS_FAILURE;
npoints = wkbReadInt(w);
nedges = npoints / 2;
/* All CircularStrings have an odd number of points */
if ( npoints < 3 || npoints % 2 != 1 )
return MS_FAILURE;
/* Make a large guess at how much space we'll need */
pa = pointArrayNew(nedges * 180 / segment_angle);
wkbReadPointP(w,&p3);
/* Fill out the point array with stroked arcs */
while( edge < nedges ) {
p1 = p3;
wkbReadPointP(w,&p2);
wkbReadPointP(w,&p3);
if ( arcStrokeCircle(&p1, &p2, &p3, segment_angle, edge ? 0 : 1, pa) == MS_FAILURE ) {
pointArrayFree(pa);
return MS_FAILURE;
}
edge++;
}
/* Copy the point array into the line */
line->numpoints = pa->npoints;
line->point = msSmallMalloc(line->numpoints * sizeof(pointObj));
memcpy(line->point, pa->data, line->numpoints * sizeof(pointObj));
/* Clean up */
pointArrayFree(pa);
return MS_SUCCESS;
}
/*
** For LAYER types that are not the usual ones (charts,
** annotations, etc) we will convert to a shape type
** that "makes sense" given the WKB input. We do this
** by peaking at the type number of the first collection
** sub-element.
*/
static int
msPostGISFindBestType(wkbObj *w, shapeObj *shape)
{
int wkbtype;
/* What kind of geometry is this? */
wkbtype = wkbType(w);
/* Generic collection, we need to look a little deeper. */
if ( wkbtype == WKB_GEOMETRYCOLLECTION )
wkbtype = wkbCollectionSubType(w);
switch ( wkbtype ) {
case WKB_POLYGON:
case WKB_CURVEPOLYGON:
case WKB_MULTIPOLYGON:
shape->type = MS_SHAPE_POLYGON;
break;
case WKB_LINESTRING:
case WKB_CIRCULARSTRING:
case WKB_COMPOUNDCURVE:
case WKB_MULTICURVE:
case WKB_MULTILINESTRING:
shape->type = MS_SHAPE_LINE;
break;
case WKB_POINT:
case WKB_MULTIPOINT:
shape->type = MS_SHAPE_POINT;
break;
default:
return MS_FAILURE;
}
return wkbConvGeometryToShape(w, shape);
}
/*
** Recent versions of PgSQL provide the version as an int in a
** simple call to the connection handle. For earlier ones we have
** to parse the version string into a usable number.
*/
static int
msPostGISRetrievePgVersion(PGconn *pgconn)
{
#ifndef POSTGIS_HAS_SERVER_VERSION
int pgVersion = 0;
char *strVersion = NULL;
char *strParts[3] = { NULL, NULL, NULL };
int i = 0, j = 0, len = 0;
int factor = 10000;
if (pgconn == NULL) {
msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePgVersion()");
return MS_FAILURE;
}
if (! PQparameterStatus(pgconn, "server_version") )
return MS_FAILURE;
strVersion = msStrdup(PQparameterStatus(pgconn, "server_version"));
if( ! strVersion )
return MS_FAILURE;
strParts[j] = strVersion;
j++;
len = strlen(strVersion);
for( i = 0; i < len; i++ ) {
if( strVersion[i] == '.' ) {
strVersion[i] = '\0';
if( j < 3 ) {
strParts[j] = strVersion + i + 1;
j++;
} else {
free(strVersion);
msSetError(MS_QUERYERR, "Too many parts in version string.", "msPostGISRetrievePgVersion()");
return MS_FAILURE;
}
}
}
for( j = 0; j < 3 && strParts[j]; j++ ) {
pgVersion += factor * atoi(strParts[j]);
factor = factor / 100;
}
free(strVersion);
return pgVersion;
#else
return PQserverVersion(pgconn);
#endif
}
/*
** Get the PostGIS version number from the database as integer.
** Versions are multiplied out as with PgSQL: 1.5.2 -> 10502, 2.0.0 -> 20000.
*/
static int
msPostGISRetrieveVersion(PGconn *pgconn)
{
static char* sql = "SELECT postgis_version()";
int version = 0;
size_t strSize;
char *strVersion = NULL;
char *ptr;
char *strParts[3] = { NULL, NULL, NULL };
int i = 0, j = 0;
int factor = 10000;
PGresult *pgresult = NULL;
if ( ! pgconn ) {
msSetError(MS_QUERYERR, "No open connection.", "msPostGISRetrieveVersion()");
return MS_FAILURE;
}
pgresult = PQexecParams(pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISRetrieveVersion()", sql);
return MS_FAILURE;
}
if (PQgetisnull(pgresult, 0, 0)) {
PQclear(pgresult);
msSetError(MS_QUERYERR,"Null result returned.","msPostGISRetrieveVersion()");
return MS_FAILURE;
}
strSize = PQgetlength(pgresult, 0, 0) + 1;
strVersion = (char*)msSmallMalloc(strSize);
strlcpy(strVersion, PQgetvalue(pgresult, 0, 0), strSize);
PQclear(pgresult);
ptr = strVersion;
strParts[j++] = strVersion;
while( ptr != '\0' && j < 3 ) {
if ( *ptr == '.' ) {
*ptr = '\0';
strParts[j++] = ptr + 1;
}
if ( *ptr == ' ' ) {
*ptr = '\0';
break;
}
ptr++;
}
for( i = 0; i < j; i++ ) {
version += factor * atoi(strParts[i]);
factor = factor / 100;
}
free(strVersion);
return version;
}
/*
** msPostGISRetrievePK()
**
** Find out that the primary key is for this layer.
** The layerinfo->fromsource must already be populated and
** must not be a subquery.
*/
static int
msPostGISRetrievePK(layerObj *layer)
{
PGresult *pgresult = NULL;
char *sql = 0;
size_t size;
msPostGISLayerInfo *layerinfo = 0;
int length;
int pgVersion;
char *pos_sep;
char *schema = NULL;
char *table = NULL;
if (layer->debug) {
msDebug("msPostGISRetrievePK called.\n");
}
layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
/* Attempt to separate fromsource into schema.table */
pos_sep = strstr(layerinfo->fromsource, ".");
if (pos_sep) {
length = strlen(layerinfo->fromsource) - strlen(pos_sep) + 1;
schema = (char*)msSmallMalloc(length);
strlcpy(schema, layerinfo->fromsource, length);
length = strlen(pos_sep);
table = (char*)msSmallMalloc(length);
strlcpy(table, pos_sep + 1, length);
if (layer->debug) {
msDebug("msPostGISRetrievePK(): Found schema %s, table %s.\n", schema, table);
}
}
if (layerinfo->pgconn == NULL) {
msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
return MS_FAILURE;
}
pgVersion = msPostGISRetrievePgVersion(layerinfo->pgconn);
if (pgVersion < 70000) {
if (layer->debug) {
msDebug("msPostGISRetrievePK(): Major version below 7.\n");
}
return MS_FAILURE;
}
if (pgVersion < 70200) {
if (layer->debug) {
msDebug("msPostGISRetrievePK(): Version below 7.2.\n");
}
return MS_FAILURE;
}
if (pgVersion < 70300) {
/*
** PostgreSQL v7.2 has a different representation of primary keys that
** later versions. This currently does not explicitly exclude
** multicolumn primary keys.
*/
static char *v72sql = "select b.attname from pg_class as a, pg_attribute as b, (select oid from pg_class where relname = '%s') as c, pg_index as d where d.indexrelid = a.oid and d.indrelid = c.oid and d.indisprimary and b.attrelid = a.oid and a.relnatts = 1";
sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v72sql));
sprintf(sql, v72sql, layerinfo->fromsource);
} else {
/*
** PostgreSQL v7.3 and later treat primary keys as constraints.
** We only support single column primary keys, so multicolumn
** pks are explicitly excluded from the query.
*/
if (schema && table) {
static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class, pg_namespace where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_class.relnamespace = pg_namespace.oid and pg_namespace.nspname = '%s' and pg_constraint.conkey[2] is null";
sql = msSmallMalloc(strlen(schema) + strlen(table) + strlen(v73sql));
sprintf(sql, v73sql, table, schema);
free(table);
free(schema);
} else {
static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_table_is_visible(pg_class.oid) and pg_constraint.conkey[2] is null";
sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v73sql));
sprintf(sql, v73sql, layerinfo->fromsource);
}
}
if (layer->debug > 1) {
msDebug("msPostGISRetrievePK: %s\n", sql);
}
layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
if (layerinfo->pgconn == NULL) {
msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
free(sql);
return MS_FAILURE;
}
pgresult = PQexecParams(layerinfo->pgconn, sql, 0, NULL, NULL, NULL, NULL, 0);
if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
static char *tmp1 = "Error executing SQL: ";
char *tmp2 = NULL;
size_t size2;
size2 = sizeof(char)*(strlen(tmp1) + strlen(sql) + 1);
tmp2 = (char*)msSmallMalloc(size2);
strlcpy(tmp2, tmp1, size2);
strlcat(tmp2, sql, size2);
msSetError(MS_QUERYERR, tmp2, "msPostGISRetrievePK()");
free(tmp2);
free(sql);
return MS_FAILURE;
}
if (PQntuples(pgresult) < 1) {
if (layer->debug) {
msDebug("msPostGISRetrievePK: No results found.\n");
}
PQclear(pgresult);
free(sql);
return MS_FAILURE;
}
if (PQntuples(pgresult) > 1) {
if (layer->debug) {
msDebug("msPostGISRetrievePK: Multiple results found.\n");
}
PQclear(pgresult);
free(sql);
return MS_FAILURE;
}
if (PQgetisnull(pgresult, 0, 0)) {
if (layer->debug) {
msDebug("msPostGISRetrievePK: Null result returned.\n");
}
PQclear(pgresult);
free(sql);
return MS_FAILURE;
}
size = PQgetlength(pgresult, 0, 0) + 1;
layerinfo->uid = (char*)msSmallMalloc(size);
strlcpy(layerinfo->uid, PQgetvalue(pgresult, 0, 0), size);
PQclear(pgresult);
free(sql);
return MS_SUCCESS;
}
/*
** msPostGISParseData()
**
** Parse the DATA string for geometry column name, table name,
** unique id column, srid, and SQL string.
*/
int msPostGISParseData(layerObj *layer)
{
char *pos_opt, *pos_scn, *tmp, *pos_srid, *pos_uid, *pos_geom, *data;
int slength;
msPostGISLayerInfo *layerinfo;
assert(layer != NULL);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*)(layer->layerinfo);
if (layer->debug) {
msDebug("msPostGISParseData called.\n");
}
if (!layer->data) {
msSetError(MS_QUERYERR, "Missing DATA clause. DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as sub'.", "msPostGISParseData()");
return MS_FAILURE;
}
data = layer->data;
/*
** Clean up any existing strings first, as we will be populating these fields.
*/
if( layerinfo->srid ) {
free(layerinfo->srid);
layerinfo->srid = NULL;
}
if( layerinfo->uid ) {
free(layerinfo->uid);
layerinfo->uid = NULL;
}
if( layerinfo->geomcolumn ) {
free(layerinfo->geomcolumn);
layerinfo->geomcolumn = NULL;
}
if( layerinfo->fromsource ) {
free(layerinfo->fromsource);
layerinfo->fromsource = NULL;
}
/*
** Look for the optional ' using unique ID' string first.
*/
pos_uid = strcasestr(data, " using unique ");
if (pos_uid) {
/* Find the end of this case 'using unique ftab_id using srid=33' */
tmp = strstr(pos_uid + 14, " ");
/* Find the end of this case 'using srid=33 using unique ftab_id' */
if (!tmp) {
tmp = pos_uid + strlen(pos_uid);
}
layerinfo->uid = (char*) msSmallMalloc((tmp - (pos_uid + 14)) + 1);
strlcpy(layerinfo->uid, pos_uid + 14, tmp - (pos_uid + 14)+1);
msStringTrim(layerinfo->uid);
}
/*
** Look for the optional ' using srid=333 ' string next.
*/
pos_srid = strcasestr(data, " using srid=");
if (!pos_srid) {
layerinfo->srid = (char*) msSmallMalloc(1);
(layerinfo->srid)[0] = '\0'; /* no SRID, so return just null terminator*/
} else {
slength = strspn(pos_srid + 12, "-0123456789");
if (!slength) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. You specified 'USING SRID' but didnt have any numbers! %s", "msPostGISParseData()", data);
return MS_FAILURE;
} else {
layerinfo->srid = (char*) msSmallMalloc(slength + 1);
strlcpy(layerinfo->srid, pos_srid + 12, slength+1);
msStringTrim(layerinfo->srid);
}
}
/*
** This is a little hack so the rest of the code works.
** pos_opt should point to the start of the optional blocks.
**
** If they are both set, return the smaller one.
*/
if (pos_srid && pos_uid) {
pos_opt = (pos_srid > pos_uid) ? pos_uid : pos_srid;
}
/* If one or none is set, return the larger one. */
else {
pos_opt = (pos_srid > pos_uid) ? pos_srid : pos_uid;
}
/* No pos_opt? Move it to the end of the string. */
if (!pos_opt) {
pos_opt = data + strlen(data);
}
/*
** Scan for the 'geometry from table' or 'geometry from () as foo' clause.
*/
/* Find the first non-white character to start from */
pos_geom = data;
while( *pos_geom == ' ' || *pos_geom == '\t' || *pos_geom == '\n' || *pos_geom == '\r' )
pos_geom++;
/* Find the end of the geom column name */
pos_scn = strcasestr(data, " from ");
if (!pos_scn) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
return MS_FAILURE;
}
/* Copy the geometry column name */
layerinfo->geomcolumn = (char*) msSmallMalloc((pos_scn - pos_geom) + 1);
strlcpy(layerinfo->geomcolumn, pos_geom, pos_scn - pos_geom+1);
msStringTrim(layerinfo->geomcolumn);
/* Copy the table name or sub-select clause */
layerinfo->fromsource = (char*) msSmallMalloc((pos_opt - (pos_scn + 6)) + 1);
strlcpy(layerinfo->fromsource, pos_scn + 6, pos_opt - (pos_scn + 6)+1);
msStringTrim(layerinfo->fromsource);
/* Something is wrong, our goemetry column and table references are not there. */
if (strlen(layerinfo->fromsource) < 1 || strlen(layerinfo->geomcolumn) < 1) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
return MS_FAILURE;
}
/*
** We didn't find a ' using unique ' in the DATA string so try and find a
** primary key on the table.
*/
if ( ! (layerinfo->uid) ) {
if ( strstr(layerinfo->fromsource, " ") ) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. You must specify 'using unique' when supplying a subselect in the data definition.", "msPostGISParseData()");
return MS_FAILURE;
}
if ( msPostGISRetrievePK(layer) != MS_SUCCESS ) {
/* No user specified unique id so we will use the PostgreSQL oid */
/* TODO: Deprecate this, oids are deprecated in PostgreSQL */
layerinfo->uid = msStrdup("oid");
}
}
if (layer->debug) {
msDebug("msPostGISParseData: unique_column=%s, srid=%s, geom_column_name=%s, table_name=%s\n", layerinfo->uid, layerinfo->srid, layerinfo->geomcolumn, layerinfo->fromsource);
}
return MS_SUCCESS;
}
/*
** Decode a hex character.
*/
static unsigned char msPostGISHexDecodeChar[256] = {
/* not Hex characters */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
/* 0-9 */
0,1,2,3,4,5,6,7,8,9,
/* not Hex characters */
64,64,64,64,64,64,64,
/* A-F */
10,11,12,13,14,15,
/* not Hex characters */
64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,
/* a-f */
10,11,12,13,14,15,
64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
/* not Hex characters (upper 128 characters) */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
};
/*
** Decode hex string "src" (null terminated)
** into "dest" (not null terminated).
** Returns length of decoded array or 0 on failure.
*/
int msPostGISHexDecode(unsigned char *dest, const char *src, int srclen)
{
if (src && *src && (srclen % 2 == 0) ) {
unsigned char *p = dest;
int i;
for ( i=0; i<srclen; i+=2 ) {
register unsigned char b1=0, b2=0;
register unsigned char c1 = src[i];
register unsigned char c2 = src[i + 1];
b1 = msPostGISHexDecodeChar[c1];
b2 = msPostGISHexDecodeChar[c2];
*p++ = (b1 << 4) | b2;
}
return(p-dest);
}
return 0;
}
/*
** Decode a base64 character.
*/
static unsigned char msPostGISBase64DecodeChar[256] = {
/* not Base64 characters */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,
/* + */
62,
/* not Base64 characters */
64,64,64,
/* / */
63,
/* 0-9 */
52,53,54,55,56,57,58,59,60,61,
/* not Base64 characters */
64,64,64,64,64,64,64,
/* A-Z */
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,
/* not Base64 characters */
64,64,64,64,64,64,
/* a-z */
26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,
/* not Base64 characters */
64,64,64,64,64,
/* not Base64 characters (upper 128 characters) */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
};
/*
** Decode base64 string "src" (null terminated)
** into "dest" (not null terminated).
** Returns length of decoded array or 0 on failure.
*/
int msPostGISBase64Decode(unsigned char *dest, const char *src, int srclen)
{
if (src && *src) {
unsigned char *p = dest;
int i, j, k;
unsigned char *buf = calloc(srclen + 1, sizeof(unsigned char));
/* Drop illegal chars first */
for (i=0, j=0; src[i]; i++) {
unsigned char c = src[i];
if ( (msPostGISBase64DecodeChar[c] != 64) || (c == '=') ) {
buf[j++] = c;
}
}
for (k=0; k<j; k+=4) {
register unsigned char c1='A', c2='A', c3='A', c4='A';
register unsigned char b1=0, b2=0, b3=0, b4=0;
c1 = buf[k];
if (k+1<j) {
c2 = buf[k+1];
}
if (k+2<j) {
c3 = buf[k+2];
}
if (k+3<j) {
c4 = buf[k+3];
}
b1 = msPostGISBase64DecodeChar[c1];
b2 = msPostGISBase64DecodeChar[c2];
b3 = msPostGISBase64DecodeChar[c3];
b4 = msPostGISBase64DecodeChar[c4];
*p++=((b1<<2)|(b2>>4) );
if (c3 != '=') {
*p++=(((b2&0xf)<<4)|(b3>>2) );
}
if (c4 != '=') {
*p++=(((b3&0x3)<<6)|b4 );
}
}
free(buf);
return(p-dest);
}
return 0;
}
/*
** msPostGISBuildSQLBox()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLBox(layerObj *layer, rectObj *rect, char *strSRID)
{
char *strBox = NULL;
size_t sz;
if (layer->debug) {
msDebug("msPostGISBuildSQLBox called.\n");
}
if ( strSRID ) {
static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)";
/* 10 doubles + 1 integer + template characters */
sz = 10 * 22 + strlen(strSRID) + strlen(strBoxTemplate);
strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
if ( sz <= snprintf(strBox, sz, strBoxTemplate,
rect->minx, rect->miny,
rect->minx, rect->maxy,
rect->maxx, rect->maxy,
rect->maxx, rect->miny,
rect->minx, rect->miny,
strSRID)) {
msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
return NULL;
}
} else {
static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))')";
/* 10 doubles + template characters */
sz = 10 * 22 + strlen(strBoxTemplate);
strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
if ( sz <= snprintf(strBox, sz, strBoxTemplate,
rect->minx, rect->miny,
rect->minx, rect->maxy,
rect->maxx, rect->maxy,
rect->maxx, rect->miny,
rect->minx, rect->miny) ) {
msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
return NULL;
}
}
return strBox;
}
/*
** msPostGISBuildSQLItems()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLItems(layerObj *layer)
{
char *strEndian = NULL;
char *strGeom = NULL;
char *strItems = NULL;
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISBuildSQLItems called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
if ( ! layerinfo->geomcolumn ) {
msSetError(MS_MISCERR, "layerinfo->geomcolumn is not initialized.", "msPostGISBuildSQLItems()");
return NULL;
}
/*
** Get the server to transform the geometry into our
** native endian before transmitting it to us..
*/
if (layerinfo->endian == LITTLE_ENDIAN) {
strEndian = "NDR";
} else {
strEndian = "XDR";
}
{
/*
** We transfer the geometry from server to client as a
** hex or base64 encoded WKB byte-array. We will have to decode this
** data once we get it. Forcing to 2D (via the AsBinary function
** which includes a 2D force in it) removes ordinates we don't
** need, saving transfer and encode/decode time.
*/
#if TRANSFER_ENCODING == 64
static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'base64') as geom,\"%s\"";
#else
static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'hex') as geom,\"%s\"";
#endif
strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid));
sprintf(strGeom, strGeomTemplate, layerinfo->geomcolumn, strEndian, layerinfo->uid);
}
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLItems: %d items requested.\n",layer->numitems);
}
/*
** Not requesting items? We just need geometry and unique id.
*/
if (layer->numitems == 0) {
strItems = msStrdup(strGeom);
}
/*
** Build SQL to pull all the items.
*/
else {
int length = strlen(strGeom) + 2;
int t;
for ( t = 0; t < layer->numitems; t++ ) {
length += strlen(layer->items[t]) + 3; /* itemname + "", */
}
strItems = (char*)msSmallMalloc(length);
strItems[0] = '\0';
for ( t = 0; t < layer->numitems; t++ ) {
strlcat(strItems, "\"", length);
strlcat(strItems, layer->items[t], length);
strlcat(strItems, "\",", length);
}
strlcat(strItems, strGeom, length);
}
free(strGeom);
return strItems;
}
/*
** msPostGISBuildSQLSRID()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLSRID(layerObj *layer)
{
char *strSRID = NULL;
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISBuildSQLSRID called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
/* An SRID was already provided in the DATA line. */
if ( layerinfo->srid && (strlen(layerinfo->srid) > 0) ) {
strSRID = msStrdup(layerinfo->srid);
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLSRID: SRID provided (%s)\n", strSRID);
}
}
/*
** No SRID in data line, so extract target table from the 'fromsource'.
** Either of form "thetable" (one word) or "(select ... from thetable)"
** or "(select ... from thetable where ...)".
*/
else {
char *f_table_name;
char *strSRIDTemplate = "find_srid('','%s','%s')";
char *pos = strstr(layerinfo->fromsource, " ");
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLSRID: Building find_srid line.\n", strSRID);
}
if ( ! pos ) {
/* target table is one word */
f_table_name = msStrdup(layerinfo->fromsource);
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLSRID: Found table (%s)\n", f_table_name);
}
} else {
/* target table is hiding in sub-select clause */
pos = strcasestr(layerinfo->fromsource, " from ");
if ( pos ) {
char *pos_paren;
char *pos_space;
pos += 6; /* should be start of table name */
pos_paren = strstr(pos, ")"); /* first ) after table name */
pos_space = strstr(pos, " "); /* first space after table name */
if ( pos_space < pos_paren ) {
/* found space first */
f_table_name = (char*)msSmallMalloc(pos_space - pos + 1);
strlcpy(f_table_name, pos, pos_space - pos+1);
} else {
/* found ) first */
f_table_name = (char*)msSmallMalloc(pos_paren - pos + 1);
strlcpy(f_table_name, pos, pos_paren - pos+1);
}
} else {
/* should not happen */
return NULL;
}
}
strSRID = msSmallMalloc(strlen(strSRIDTemplate) + strlen(f_table_name) + strlen(layerinfo->geomcolumn));
sprintf(strSRID, strSRIDTemplate, f_table_name, layerinfo->geomcolumn);
if ( f_table_name ) free(f_table_name);
}
return strSRID;
}
/*
** msPostGISReplaceBoxToken()
**
** Convert a fromsource data statement into something usable by replacing the !BOX! token.
**
** Returns malloc'ed char* that must be freed by caller.
*/
static char *msPostGISReplaceBoxToken(layerObj *layer, rectObj *rect, const char *fromsource)
{
char *result = NULL;
if ( strstr(fromsource, BOXTOKEN) && rect ) {
char *strBox = NULL;
char *strSRID = NULL;
/* We see to set the SRID on the box, but to what SRID? */
strSRID = msPostGISBuildSQLSRID(layer);
if ( ! strSRID ) {
return NULL;
}
/* Create a suitable SQL string from the rectangle and SRID. */
strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
if ( ! strBox ) {
msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISReplaceBoxToken()");
if (strSRID) free(strSRID);
return NULL;
}
/* Do the substitution. */
while ( strstr(fromsource, BOXTOKEN) ) {
char *start, *end;
char *oldresult = result;
size_t buffer_size = 0;
start = strstr(fromsource, BOXTOKEN);
end = start + BOXTOKENLENGTH;
buffer_size = (start - fromsource) + strlen(strBox) + strlen(end) +1;
result = (char*)msSmallMalloc(buffer_size);
strlcpy(result, fromsource, start - fromsource +1);
strlcpy(result + (start - fromsource), strBox, buffer_size-(start - fromsource));
strlcat(result, end, buffer_size);
fromsource = result;
if (oldresult != NULL)
free(oldresult);
}
if (strSRID) free(strSRID);
if (strBox) free(strBox);
} else {
result = msStrdup(fromsource);
}
return result;
}
/*
** msPostGISBuildSQLFrom()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLFrom(layerObj *layer, rectObj *rect)
{
char *strFrom = 0;
msPostGISLayerInfo *layerinfo;
if (layer->debug) {
msDebug("msPostGISBuildSQLFrom called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
if ( ! layerinfo->fromsource ) {
msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLFrom()");
return NULL;
}
/*
** If there's a '!BOX!' in our source we need to substitute the
** current rectangle for it...
*/
strFrom = msPostGISReplaceBoxToken(layer, rect, layerinfo->fromsource);
return strFrom;
}
/*
** msPostGISBuildSQLWhere()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid)
{
char *strRect = 0;
char *strFilter = 0;
char *strUid = 0;
char *strWhere = 0;
char *strLimit = 0;
char *strOffset = 0;
size_t strRectLength = 0;
size_t strFilterLength = 0;
size_t strUidLength = 0;
size_t strLimitLength = 0;
size_t strOffsetLength = 0;
size_t bufferSize = 0;
int insert_and = 0;
msPostGISLayerInfo *layerinfo;
if (layer->debug) {
msDebug("msPostGISBuildSQLWhere called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
if ( ! layerinfo->fromsource ) {
msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLWhere()");
return NULL;
}
/* Populate strLimit, if necessary. */
if ( layerinfo->paging && layer->maxfeatures >= 0 ) {
static char *strLimitTemplate = " limit %d";
strLimit = msSmallMalloc(strlen(strLimitTemplate) + 12);
sprintf(strLimit, strLimitTemplate, layer->maxfeatures);
strLimitLength = strlen(strLimit);
}
/* Populate strOffset, if necessary. */
if ( layerinfo->paging && layer->startindex > 0 ) {
static char *strOffsetTemplate = " offset %d";
strOffset = msSmallMalloc(strlen(strOffsetTemplate) + 12);
sprintf(strOffset, strOffsetTemplate, layer->startindex-1);
strOffsetLength = strlen(strOffset);
}
/* Populate strRect, if necessary. */
if ( rect && layerinfo->geomcolumn ) {
char *strBox = 0;
char *strSRID = 0;
size_t strBoxLength = 0;
static char *strRectTemplate = "%s && %s";
/* We see to set the SRID on the box, but to what SRID? */
strSRID = msPostGISBuildSQLSRID(layer);
if ( ! strSRID ) {
return NULL;
}
strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
if ( strBox ) {
strBoxLength = strlen(strBox);
} else {
msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISBuildSQLWhere()");
return NULL;
}
strRect = (char*)msSmallMalloc(strlen(strRectTemplate) + strBoxLength + strlen(layerinfo->geomcolumn));
sprintf(strRect, strRectTemplate, layerinfo->geomcolumn, strBox);
strRectLength = strlen(strRect);
if (strBox) free(strBox);
if (strSRID) free(strSRID);
}
/* Populate strFilter, if necessary. */
if ( layer->filter.string ) {
static char *strFilterTemplate = "(%s)";
strFilter = (char*)msSmallMalloc(strlen(strFilterTemplate) + strlen(layer->filter.string));
sprintf(strFilter, strFilterTemplate, layer->filter.string);
strFilterLength = strlen(strFilter);
}
/* Populate strUid, if necessary. */
if ( uid ) {
static char *strUidTemplate = "\"%s\" = %ld";
strUid = (char*)msSmallMalloc(strlen(strUidTemplate) + strlen(layerinfo->uid) + 64);
sprintf(strUid, strUidTemplate, layerinfo->uid, *uid);
strUidLength = strlen(strUid);
}
bufferSize = strRectLength + 5 + strFilterLength + 5 + strUidLength
+ strLimitLength + strOffsetLength;
strWhere = (char*)msSmallMalloc(bufferSize);
*strWhere = '\0';
if ( strRect ) {
strlcat(strWhere, strRect, bufferSize);
insert_and++;
free(strRect);
}
if ( strFilter ) {
if ( insert_and ) {
strlcat(strWhere, " and ", bufferSize);
}
strlcat(strWhere, strFilter, bufferSize);
free(strFilter);
insert_and++;
}
if ( strUid ) {
if ( insert_and ) {
strlcat(strWhere, " and ", bufferSize);
}
strlcat(strWhere, strUid, bufferSize);
free(strUid);
insert_and++;
}
if ( strLimit ) {
strlcat(strWhere, strLimit, bufferSize);
free(strLimit);
}
if ( strOffset ) {
strlcat(strWhere, strOffset, bufferSize);
free(strOffset);
}
return strWhere;
}
/*
** msPostGISBuildSQL()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQL(layerObj *layer, rectObj *rect, long *uid)
{
msPostGISLayerInfo *layerinfo = 0;
char *strFrom = 0;
char *strItems = 0;
char *strWhere = 0;
char *strSQL = 0;
static char *strSQLTemplate0 = "select %s from %s where %s";
static char *strSQLTemplate1 = "select %s from %s%s";
char *strSQLTemplate = 0;
if (layer->debug) {
msDebug("msPostGISBuildSQL called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
strItems = msPostGISBuildSQLItems(layer);
if ( ! strItems ) {
msSetError(MS_MISCERR, "Failed to build SQL items.", "msPostGISBuildSQL()");
return NULL;
}
strFrom = msPostGISBuildSQLFrom(layer, rect);
if ( ! strFrom ) {
msSetError(MS_MISCERR, "Failed to build SQL 'from'.", "msPostGISBuildSQL()");
return NULL;
}
/* If there's BOX hackery going on, we don't want to append a box index test at
the end of the query, the user is going to be responsible for making things
work with their hackery. */
if ( strstr(layerinfo->fromsource, BOXTOKEN) )
strWhere = msPostGISBuildSQLWhere(layer, NULL, uid);
else
strWhere = msPostGISBuildSQLWhere(layer, rect, uid);
if ( ! strWhere ) {
msSetError(MS_MISCERR, "Failed to build SQL 'where'.", "msPostGISBuildSQL()");
return NULL;
}
strSQLTemplate = strlen(strWhere) ? strSQLTemplate0 : strSQLTemplate1;
strSQL = msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom) + strlen(strItems) + strlen(strWhere));
sprintf(strSQL, strSQLTemplate, strItems, strFrom, strWhere);
if (strItems) free(strItems);
if (strFrom) free(strFrom);
if (strWhere) free(strWhere);
return strSQL;
}
#define wkbstaticsize 4096
int msPostGISReadShape(layerObj *layer, shapeObj *shape)
{
char *wkbstr = NULL;
unsigned char wkbstatic[wkbstaticsize];
unsigned char *wkb = NULL;
wkbObj w;
msPostGISLayerInfo *layerinfo = NULL;
int result = 0;
int wkbstrlen = 0;
if (layer->debug) {
msDebug("msPostGISReadShape called.\n");
}
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Retrieve the geometry. */
wkbstr = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, layer->numitems );
wkbstrlen = PQgetlength(layerinfo->pgresult, layerinfo->rownum, layer->numitems);
if ( ! wkbstr ) {
msSetError(MS_QUERYERR, "Base64 WKB returned is null!", "msPostGISReadShape()");
return MS_FAILURE;
}
if(wkbstrlen > wkbstaticsize) {
wkb = calloc(wkbstrlen, sizeof(char));
} else {
wkb = wkbstatic;
}
#if TRANSFER_ENCODING == 64
result = msPostGISBase64Decode(wkb, wkbstr, wkbstrlen - 1);
#else
result = msPostGISHexDecode(wkb, wkbstr, wkbstrlen);
#endif
if( ! result ) {
if(wkb!=wkbstatic) free(wkb);
return MS_FAILURE;
}
/* Initialize our wkbObj */
w.wkb = (char*)wkb;
w.ptr = w.wkb;
w.size = (wkbstrlen - 1)/2;
/* Set the type map according to what version of PostGIS we are dealing with */
if( layerinfo->version >= 20000 ) /* PostGIS 2.0+ */
w.typemap = wkb_postgis20;
else
w.typemap = wkb_postgis15;
switch (layer->type) {
case MS_LAYER_POINT:
shape->type = MS_SHAPE_POINT;
result = wkbConvGeometryToShape(&w, shape);
break;
case MS_LAYER_LINE:
shape->type = MS_SHAPE_LINE;
result = wkbConvGeometryToShape(&w, shape);
break;
case MS_LAYER_POLYGON:
shape->type = MS_SHAPE_POLYGON;
result = wkbConvGeometryToShape(&w, shape);
break;
case MS_LAYER_ANNOTATION:
case MS_LAYER_QUERY:
case MS_LAYER_CHART:
result = msPostGISFindBestType(&w, shape);
break;
case MS_LAYER_RASTER:
msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
break;
case MS_LAYER_CIRCLE:
msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
break;
default:
msDebug("Unsupported layer type in msPostGISReadShape()!\n");
break;
}
/* All done with WKB geometry, free it! */
if(wkb!=wkbstatic) free(wkb);
if (result != MS_FAILURE) {
int t;
long uid;
char *tmp;
/* Found a drawable shape, so now retreive the attributes. */
shape->values = (char**) msSmallMalloc(sizeof(char*) * layer->numitems);
for ( t = 0; t < layer->numitems; t++) {
int size = PQgetlength(layerinfo->pgresult, layerinfo->rownum, t);
char *val = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t);
int isnull = PQgetisnull(layerinfo->pgresult, layerinfo->rownum, t);
if ( isnull ) {
shape->values[t] = msStrdup("");
} else {
shape->values[t] = (char*) msSmallMalloc(size + 1);
memcpy(shape->values[t], val, size);
shape->values[t][size] = '\0'; /* null terminate it */
msStringTrimBlanks(shape->values[t]);
}
if( layer->debug > 4 ) {
msDebug("msPostGISReadShape: PQgetlength = %d\n", size);
}
if( layer->debug > 1 ) {
msDebug("msPostGISReadShape: [%s] \"%s\"\n", layer->items[t], shape->values[t]);
}
}
/* t is the geometry, t+1 is the uid */
tmp = PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t + 1);
if( tmp ) {
uid = strtol( tmp, NULL, 10 );
} else {
uid = 0;
}
if( layer->debug > 4 ) {
msDebug("msPostGISReadShape: Setting shape->index = %d\n", uid);
msDebug("msPostGISReadShape: Setting shape->resultindex = %d\n", layerinfo->rownum);
}
shape->index = uid;
shape->resultindex = layerinfo->rownum;
if( layer->debug > 2 ) {
msDebug("msPostGISReadShape: [index] %d\n", shape->index);
}
shape->numvalues = layer->numitems;
msComputeBounds(shape);
}
if( layer->debug > 2 ) {
char *tmp = msShapeToWKT(shape);
msDebug("msPostGISReadShape: [shape] %s\n", tmp);
free(tmp);
}
return MS_SUCCESS;
}
#endif /* USE_POSTGIS */
/*
** msPostGISLayerOpen()
**
** Registered vtable->LayerOpen function.
*/
int msPostGISLayerOpen(layerObj *layer)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo;
int order_test = 1;
assert(layer != NULL);
if (layer->debug) {
msDebug("msPostGISLayerOpen called: %s\n", layer->data);
}
if (layer->layerinfo) {
if (layer->debug) {
msDebug("msPostGISLayerOpen: Layer is already open!\n");
}
return MS_SUCCESS; /* already open */
}
if (!layer->data) {
msSetError(MS_QUERYERR, "Nothing specified in DATA statement.", "msPostGISLayerOpen()");
return MS_FAILURE;
}
/*
** Initialize the layerinfo
**/
layerinfo = msPostGISCreateLayerInfo();
if (((char*) &order_test)[0] == 1) {
layerinfo->endian = LITTLE_ENDIAN;
} else {
layerinfo->endian = BIG_ENDIAN;
}
/*
** Get a database connection from the pool.
*/
layerinfo->pgconn = (PGconn *) msConnPoolRequest(layer);
/* No connection in the pool, so set one up. */
if (!layerinfo->pgconn) {
char *conn_decrypted;
if (layer->debug) {
msDebug("msPostGISLayerOpen: No connection in pool, creating a fresh one.\n");
}
if (!layer->connection) {
msSetError(MS_MISCERR, "Missing CONNECTION keyword.", "msPostGISLayerOpen()");
return MS_FAILURE;
}
/*
** Decrypt any encrypted token in connection string and attempt to connect.
*/
conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
if (conn_decrypted == NULL) {
return MS_FAILURE; /* An error should already have been produced */
}
layerinfo->pgconn = PQconnectdb(conn_decrypted);
msFree(conn_decrypted);
conn_decrypted = NULL;
/*
** Connection failed, return error message with passwords ***ed out.
*/
if (!layerinfo->pgconn || PQstatus(layerinfo->pgconn) == CONNECTION_BAD) {
char *index, *maskeddata;
if (layer->debug)
msDebug("msPostGISLayerOpen: Connection failure.\n");
maskeddata = msStrdup(layer->connection);
index = strstr(maskeddata, "password=");
if (index != NULL) {
index = (char*)(index + 9);
while (*index != '\0' && *index != ' ') {
*index = '*';
index++;
}
}
msSetError(MS_QUERYERR, "Database connection failed (%s) with connect string '%s'\nIs the database running? Is it allowing connections? Does the specified user exist? Is the password valid? Is the database on the standard port?", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn), maskeddata);
free(maskeddata);
free(layerinfo);
return MS_FAILURE;
}
/* Register to receive notifications from the database. */
PQsetNoticeProcessor(layerinfo->pgconn, postresqlNoticeHandler, (void *) layer);
/* Save this connection in the pool for later. */
msConnPoolRegister(layer, layerinfo->pgconn, msPostGISCloseConnection);
} else {
/* Connection in the pool should be tested to see if backend is alive. */
if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
/* Uh oh, bad connection. Can we reset it? */
PQreset(layerinfo->pgconn);
if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
/* Nope, time to bail out. */
msSetError(MS_QUERYERR, "PostgreSQL database connection gone bad (%s)", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn));
return MS_FAILURE;
}
}
}
/* Get the PostGIS version number from the database */
layerinfo->version = msPostGISRetrieveVersion(layerinfo->pgconn);
if( layerinfo->version == MS_FAILURE ) return MS_FAILURE;
if (layer->debug)
msDebug("msPostGISLayerOpen: Got PostGIS version %d.\n", layerinfo->version);
/* Save the layerinfo in the layerObj. */
layer->layerinfo = (void*)layerinfo;
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerOpen()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerClose()
**
** Registered vtable->LayerClose function.
*/
int msPostGISLayerClose(layerObj *layer)
{
#ifdef USE_POSTGIS
if (layer->debug) {
msDebug("msPostGISLayerClose called: %s\n", layer->data);
}
if( layer->layerinfo ) {
msPostGISFreeLayerInfo(layer);
}
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerClose()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerIsOpen()
**
** Registered vtable->LayerIsOpen function.
*/
int msPostGISLayerIsOpen(layerObj *layer)
{
#ifdef USE_POSTGIS
if (layer->debug) {
msDebug("msPostGISLayerIsOpen called.\n");
}
if (layer->layerinfo)
return MS_TRUE;
else
return MS_FALSE;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerIsOpen()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerFreeItemInfo()
**
** Registered vtable->LayerFreeItemInfo function.
*/
void msPostGISLayerFreeItemInfo(layerObj *layer)
{
#ifdef USE_POSTGIS
if (layer->debug) {
msDebug("msPostGISLayerFreeItemInfo called.\n");
}
if (layer->iteminfo) {
free(layer->iteminfo);
}
layer->iteminfo = NULL;
#endif
}
/*
** msPostGISLayerInitItemInfo()
**
** Registered vtable->LayerInitItemInfo function.
** Our iteminfo is list of indexes from 1..numitems.
*/
int msPostGISLayerInitItemInfo(layerObj *layer)
{
#ifdef USE_POSTGIS
int i;
int *itemindexes ;
if (layer->debug) {
msDebug("msPostGISLayerInitItemInfo called.\n");
}
if (layer->numitems == 0) {
return MS_SUCCESS;
}
if (layer->iteminfo) {
free(layer->iteminfo);
}
layer->iteminfo = msSmallMalloc(sizeof(int) * layer->numitems);
if (!layer->iteminfo) {
msSetError(MS_MEMERR, "Out of memory.", "msPostGISLayerInitItemInfo()");
return MS_FAILURE;
}
itemindexes = (int*)layer->iteminfo;
for (i = 0; i < layer->numitems; i++) {
itemindexes[i] = i; /* Last item is always the geometry. The rest are non-geometry. */
}
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerInitItemInfo()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerWhichShapes()
**
** Registered vtable->LayerWhichShapes function.
*/
int msPostGISLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
char *strSQL = NULL;
PGresult *pgresult = NULL;
char** layer_bind_values = (char**)msSmallMalloc(sizeof(char*) * 1000);
char* bind_value;
char* bind_key = (char*)msSmallMalloc(3);
int num_bind_values = 0;
/* try to get the first bind value */
bind_value = msLookupHashTable(&layer->bindvals, "1");
while(bind_value != NULL) {
/* put the bind value on the stack */
layer_bind_values[num_bind_values] = bind_value;
/* increment the counter */
num_bind_values++;
/* create a new lookup key */
sprintf(bind_key, "%d", num_bind_values+1);
/* get the bind_value */
bind_value = msLookupHashTable(&layer->bindvals, bind_key);
}
assert(layer != NULL);
assert(layer->layerinfo != NULL);
if (layer->debug) {
msDebug("msPostGISLayerWhichShapes called.\n");
}
/* Fill out layerinfo with our current DATA state. */
if ( msPostGISParseData(layer) != MS_SUCCESS) {
return MS_FAILURE;
}
/*
** This comes *after* parsedata, because parsedata fills in
** layer->layerinfo.
*/
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Build a SQL query based on our current state. */
strSQL = msPostGISBuildSQL(layer, &rect, NULL);
if ( ! strSQL ) {
msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerWhichShapes()");
return MS_FAILURE;
}
if (layer->debug) {
msDebug("msPostGISLayerWhichShapes query: %s\n", strSQL);
}
if(num_bind_values > 0) {
pgresult = PQexecParams(layerinfo->pgconn, strSQL, num_bind_values, NULL, (const char**)layer_bind_values, NULL, NULL, 1);
} else {
pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
}
/* free bind values */
free(bind_key);
free(layer_bind_values);
if ( layer->debug > 1 ) {
msDebug("msPostGISLayerWhichShapes query status: %s (%d)\n", PQresStatus(PQresultStatus(pgresult)), PQresultStatus(pgresult));
}
/* Something went wrong. */
if (!pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
if ( layer->debug ) {
msDebug("Error (%s) executing query: %s", "msPostGISLayerWhichShapes()\n", PQerrorMessage(layerinfo->pgconn), strSQL);
}
msSetError(MS_QUERYERR, "Error executing query: %s ", "msPostGISLayerWhichShapes()", PQerrorMessage(layerinfo->pgconn));
free(strSQL);
if (pgresult) {
PQclear(pgresult);
}
return MS_FAILURE;
}
if ( layer->debug ) {
msDebug("msPostGISLayerWhichShapes got %d records in result.\n", PQntuples(pgresult));
}
/* Clean any existing pgresult before storing current one. */
if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
layerinfo->pgresult = pgresult;
/* Clean any existing SQL before storing current. */
if(layerinfo->sql) free(layerinfo->sql);
layerinfo->sql = strSQL;
layerinfo->rownum = 0;
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerWhichShapes()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerNextShape()
**
** Registered vtable->LayerNextShape function.
*/
int msPostGISLayerNextShape(layerObj *layer, shapeObj *shape)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo;
if (layer->debug) {
msDebug("msPostGISLayerNextShape called.\n");
}
assert(layer != NULL);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
shape->type = MS_SHAPE_NULL;
/*
** Roll through pgresult until we hit non-null shape (usually right away).
*/
while (shape->type == MS_SHAPE_NULL) {
if (layerinfo->rownum < PQntuples(layerinfo->pgresult)) {
/* Retrieve this shape, cursor access mode. */
msPostGISReadShape(layer, shape);
if( shape->type != MS_SHAPE_NULL ) {
(layerinfo->rownum)++; /* move to next shape */
return MS_SUCCESS;
} else {
(layerinfo->rownum)++; /* move to next shape */
}
} else {
return MS_DONE;
}
}
/* Found nothing, clean up and exit. */
msFreeShape(shape);
return MS_FAILURE;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerNextShape()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerGetShape()
**
** Registered vtable->LayerGetShape function. For pulling from a prepared and
** undisposed result set.
*/
int msPostGISLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
{
#ifdef USE_POSTGIS
PGresult *pgresult = NULL;
msPostGISLayerInfo *layerinfo = NULL;
long shapeindex = record->shapeindex;
int resultindex = record->resultindex;
assert(layer != NULL);
assert(layer->layerinfo != NULL);
if (layer->debug) {
msDebug("msPostGISLayerGetShape called for record = %i\n", resultindex);
}
/* If resultindex is set, fetch the shape from the resultcache, otherwise fetch it from the DB */
if (resultindex >= 0) {
int status;
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Check the validity of the open result. */
pgresult = layerinfo->pgresult;
if ( ! pgresult ) {
msSetError( MS_MISCERR,
"PostgreSQL result set is null.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
}
status = PQresultStatus(pgresult);
if ( layer->debug > 1 ) {
msDebug("msPostGISLayerGetShape query status: %s (%d)\n", PQresStatus(status), status);
}
if( ! ( status == PGRES_COMMAND_OK || status == PGRES_TUPLES_OK) ) {
msSetError( MS_MISCERR,
"PostgreSQL result set is not ready.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
}
/* Check the validity of the requested record number. */
if( resultindex >= PQntuples(pgresult) ) {
msDebug("msPostGISLayerGetShape got request for (%d) but only has %d tuples.\n", resultindex, PQntuples(pgresult));
msSetError( MS_MISCERR,
"Got request larger than result set.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
}
layerinfo->rownum = resultindex; /* Only return one result. */
/* We don't know the shape type until we read the geometry. */
shape->type = MS_SHAPE_NULL;
/* Return the shape, cursor access mode. */
msPostGISReadShape(layer, shape);
return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : MS_SUCCESS;
} else { /* no resultindex, fetch the shape from the DB */
int num_tuples;
char *strSQL = 0;
/* Fill out layerinfo with our current DATA state. */
if ( msPostGISParseData(layer) != MS_SUCCESS) {
return MS_FAILURE;
}
/*
** This comes *after* parsedata, because parsedata fills in
** layer->layerinfo.
*/
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Build a SQL query based on our current state. */
strSQL = msPostGISBuildSQL(layer, 0, &shapeindex);
if ( ! strSQL ) {
msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerGetShape()");
return MS_FAILURE;
}
if (layer->debug) {
msDebug("msPostGISLayerGetShape query: %s\n", strSQL);
}
pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
/* Something went wrong. */
if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
if ( layer->debug ) {
msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetShape()\n", PQerrorMessage(layerinfo->pgconn), strSQL );
}
msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetShape()", PQerrorMessage(layerinfo->pgconn));
if (pgresult) {
PQclear(pgresult);
}
free(strSQL);
return MS_FAILURE;
}
/* Clean any existing pgresult before storing current one. */
if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
layerinfo->pgresult = pgresult;
/* Clean any existing SQL before storing current. */
if(layerinfo->sql) free(layerinfo->sql);
layerinfo->sql = strSQL;
layerinfo->rownum = 0; /* Only return one result. */
/* We don't know the shape type until we read the geometry. */
shape->type = MS_SHAPE_NULL;
num_tuples = PQntuples(pgresult);
if (layer->debug) {
msDebug("msPostGISLayerGetShape number of records: %d\n", num_tuples);
}
if (num_tuples > 0) {
/* Get shape in random access mode. */
msPostGISReadShape(layer, shape);
}
return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : ( (num_tuples > 0) ? MS_SUCCESS : MS_DONE );
}
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
#endif
}
/**********************************************************************
* msPostGISPassThroughFieldDefinitions()
*
* Pass the field definitions through to the layer metadata in the
* "gml_[item]_{type,width,precision}" set of metadata items for
* defining fields.
**********************************************************************/
/* These are the OIDs for some builtin types, as returned by PQftype(). */
/* They were copied from pg_type.h in src/include/catalog/pg_type.h */
#ifndef BOOLOID
#define BOOLOID 16
#define BYTEAOID 17
#define CHAROID 18
#define NAMEOID 19
#define INT8OID 20
#define INT2OID 21
#define INT2VECTOROID 22
#define INT4OID 23
#define REGPROCOID 24
#define TEXTOID 25
#define OIDOID 26
#define TIDOID 27
#define XIDOID 28
#define CIDOID 29
#define OIDVECTOROID 30
#define FLOAT4OID 700
#define FLOAT8OID 701
#define INT4ARRAYOID 1007
#define TEXTARRAYOID 1009
#define BPCHARARRAYOID 1014
#define VARCHARARRAYOID 1015
#define FLOAT4ARRAYOID 1021
#define FLOAT8ARRAYOID 1022
#define BPCHAROID 1042
#define VARCHAROID 1043
#define DATEOID 1082
#define TIMEOID 1083
#define TIMESTAMPOID 1114
#define TIMESTAMPTZOID 1184
#define NUMERICOID 1700
#endif
#ifdef USE_POSTGIS
static void
msPostGISPassThroughFieldDefinitions( layerObj *layer,
PGresult *pgresult )
{
int i, numitems = PQnfields(pgresult);
msPostGISLayerInfo *layerinfo = layer->layerinfo;
for(i=0; i<numitems; i++) {
int oid, fmod;
const char *gml_type = "Character";
const char *item = PQfname(pgresult,i);
char md_item_name[256];
char gml_width[32], gml_precision[32];
gml_width[0] = '\0';
gml_precision[0] = '\0';
/* skip geometry column */
if( strcmp(item, layerinfo->geomcolumn) == 0 )
continue;
oid = PQftype(pgresult,i);
fmod = PQfmod(pgresult,i);
if( (oid == BPCHAROID || oid == VARCHAROID) && fmod >= 4 ) {
sprintf( gml_width, "%d", fmod-4 );
} else if( oid == BOOLOID ) {
gml_type = "Integer";
sprintf( gml_width, "%d", 1 );
} else if( oid == INT2OID ) {
gml_type = "Integer";
sprintf( gml_width, "%d", 5 );
} else if( oid == INT4OID || oid == INT8OID ) {
gml_type = "Integer";
} else if( oid == FLOAT4OID || oid == FLOAT8OID ) {
gml_type = "Real";
} else if( oid == NUMERICOID ) {
gml_type = "Real";
if( fmod >= 4 && ((fmod - 4) & 0xFFFF) == 0 ) {
gml_type = "Integer";
sprintf( gml_width, "%d", (fmod - 4) >> 16 );
} else if( fmod >= 4 ) {
sprintf( gml_width, "%d", (fmod - 4) >> 16 );
sprintf( gml_precision, "%d", ((fmod-4) & 0xFFFF) );
}
} else if( oid == DATEOID
|| oid == TIMESTAMPOID || oid == TIMESTAMPTZOID ) {
gml_type = "Date";
}
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
if( strlen(gml_width) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
if( strlen(gml_precision) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
}
}
#endif /* defined(USE_POSTGIS) */
/*
** msPostGISLayerGetItems()
**
** Registered vtable->LayerGetItems function. Query the database for
** column information about the requested layer. Rather than look in
** system tables, we just run a zero-cost query and read out of the
** result header.
*/
int msPostGISLayerGetItems(layerObj *layer)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
static char *strSQLTemplate = "select * from %s where false limit 0";
PGresult *pgresult = NULL;
char *col = NULL;
char *sql = NULL;
char *strFrom = NULL;
char found_geom = 0;
const char *value;
int t, item_num;
rectObj rect;
/* A useless rectangle for our useless query */
rect.minx = rect.miny = rect.maxx = rect.maxy = 0.0;
assert(layer != NULL);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
assert(layerinfo->pgconn);
if (layer->debug) {
msDebug("msPostGISLayerGetItems called.\n");
}
/* Fill out layerinfo with our current DATA state. */
if ( msPostGISParseData(layer) != MS_SUCCESS) {
return MS_FAILURE;
}
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* This allocates a fresh string, so remember to free it... */
strFrom = msPostGISReplaceBoxToken(layer, &rect, layerinfo->fromsource);
/*
** Both the "table" and "(select ...) as sub" cases can be handled with the
** same SQL.
*/
sql = (char*) msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom));
sprintf(sql, strSQLTemplate, strFrom);
free(strFrom);
if (layer->debug) {
msDebug("msPostGISLayerGetItems executing SQL: %s\n", sql);
}
pgresult = PQexecParams(layerinfo->pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
if ( layer->debug ) {
msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetItems()\n", PQerrorMessage(layerinfo->pgconn), sql);
}
msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetItems()", PQerrorMessage(layerinfo->pgconn));
if (pgresult) {
PQclear(pgresult);
}
free(sql);
return MS_FAILURE;
}
free(sql);
layer->numitems = PQnfields(pgresult) - 1; /* dont include the geometry column (last entry)*/
layer->items = msSmallMalloc(sizeof(char*) * (layer->numitems + 1)); /* +1 in case there is a problem finding geometry column */
found_geom = 0; /* havent found the geom field */
item_num = 0;
for (t = 0; t < PQnfields(pgresult); t++) {
col = PQfname(pgresult, t);
if ( strcmp(col, layerinfo->geomcolumn) != 0 ) {
/* this isnt the geometry column */
layer->items[item_num] = msStrdup(col);
item_num++;
} else {
found_geom = 1;
}
}
/*
** consider populating the field definitions in metadata.
*/
if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
&& strcasecmp(value,"auto") == 0 )
msPostGISPassThroughFieldDefinitions( layer, pgresult );
/*
** Cleanup
*/
PQclear(pgresult);
if (!found_geom) {
msSetError(MS_QUERYERR, "Tried to find the geometry column in the database, but couldn't find it. Is it mis-capitalized? '%s'", "msPostGISLayerGetItems()", layerinfo->geomcolumn);
return MS_FAILURE;
}
return msPostGISLayerInitItemInfo(layer);
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerGetItems()");
return MS_FAILURE;
#endif
}
/*
* make sure that the timestring is complete and acceptable
* to the date_trunc function :
* - if the resolution is year (2004) or month (2004-01),
* a complete string for time would be 2004-01-01
* - if the resolluion is hour or minute (2004-01-01 15), a
* complete time is 2004-01-01 15:00:00
*/
int postgresTimeStampForTimeString(const char *timestring, char *dest, size_t destsize)
{
int nlength = strlen(timestring);
int timeresolution = msTimeGetResolution(timestring);
int bNoDate = (*timestring == 'T');
if (timeresolution < 0)
return MS_FALSE;
switch(timeresolution) {
case TIME_RESOLUTION_YEAR:
if (timestring[nlength-1] != '-') {
snprintf(dest, destsize,"date '%s-01-01'",timestring);
} else {
snprintf(dest, destsize,"date '%s01-01'",timestring);
}
break;
case TIME_RESOLUTION_MONTH:
if (timestring[nlength-1] != '-') {
snprintf(dest, destsize,"date '%s-01'",timestring);
} else {
snprintf(dest, destsize,"date '%s01'",timestring);
}
break;
case TIME_RESOLUTION_DAY:
snprintf(dest, destsize,"date '%s'",timestring);
break;
case TIME_RESOLUTION_HOUR:
if (timestring[nlength-1] != ':') {
if(bNoDate)
snprintf(dest, destsize,"time '%s:00:00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s:00:00'", timestring);
} else {
if(bNoDate)
snprintf(dest, destsize,"time '%s00:00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s00:00'", timestring);
}
break;
case TIME_RESOLUTION_MINUTE:
if (timestring[nlength-1] != ':') {
if(bNoDate)
snprintf(dest, destsize,"time '%s:00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s:00'", timestring);
} else {
if(bNoDate)
snprintf(dest, destsize,"time '%s00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s00'", timestring);
}
break;
case TIME_RESOLUTION_SECOND:
if(bNoDate)
snprintf(dest, destsize,"time '%s'", timestring);
else
snprintf(dest, destsize,"timestamp '%s'", timestring);
break;
default:
return MS_FAILURE;
}
return MS_SUCCESS;
}
/*
* create a postgresql where clause for the given timestring, taking into account
* the resolution (e.g. second, day, month...) of the given timestring
* we apply the date_trunc function on the given timestring and not on the time
* column in order for postgres to take advantage of an eventual index on the
* time column
*
* the generated sql is
*
* (
* timecol >= date_trunc(timestring,resolution)
* and
* timecol < date_trunc(timestring,resolution) + interval '1 resolution'
* )
*/
int createPostgresTimeCompareSimple(const char *timecol, const char *timestring, char *dest, size_t destsize)
{
int timeresolution = msTimeGetResolution(timestring);
char timeStamp[100];
char *interval;
if (timeresolution < 0)
return MS_FALSE;
postgresTimeStampForTimeString(timestring,timeStamp,100);
switch(timeresolution) {
case TIME_RESOLUTION_YEAR:
interval = "year";
break;
case TIME_RESOLUTION_MONTH:
interval = "month";
break;
case TIME_RESOLUTION_DAY:
interval = "day";
break;
case TIME_RESOLUTION_HOUR:
interval = "hour";
break;
case TIME_RESOLUTION_MINUTE:
interval = "minute";
break;
case TIME_RESOLUTION_SECOND:
interval = "second";
break;
default:
return MS_FAILURE;
}
snprintf(dest, destsize,"(%s >= date_trunc('%s',%s) and %s < date_trunc('%s',%s) + interval '1 %s')",
timecol, interval, timeStamp, timecol, interval, timeStamp, interval);
return MS_SUCCESS;
}
/*
* create a postgresql where clause for the range given by the two input timestring,
* taking into account the resolution (e.g. second, day, month...) of each of the
* given timestrings (both timestrings can have different resolutions, although I don't
* know if that's a valid TIME range
* we apply the date_trunc function on the given timestrings and not on the time
* column in order for postgres to take advantage of an eventual index on the
* time column
*
* the generated sql is
*
* (
* timecol >= date_trunc(mintimestring,minresolution)
* and
* timecol < date_trunc(maxtimestring,maxresolution) + interval '1 maxresolution'
* )
*/
int createPostgresTimeCompareRange(const char *timecol, const char *mintime, const char *maxtime,
char *dest, size_t destsize)
{
int mintimeresolution = msTimeGetResolution(mintime);
int maxtimeresolution = msTimeGetResolution(maxtime);
char minTimeStamp[100];
char maxTimeStamp[100];
char *minTimeInterval,*maxTimeInterval;
if (mintimeresolution < 0 || maxtimeresolution < 0)
return MS_FALSE;
postgresTimeStampForTimeString(mintime,minTimeStamp,100);
postgresTimeStampForTimeString(maxtime,maxTimeStamp,100);
switch(maxtimeresolution) {
case TIME_RESOLUTION_YEAR:
maxTimeInterval = "year";
break;
case TIME_RESOLUTION_MONTH:
maxTimeInterval = "month";
break;
case TIME_RESOLUTION_DAY:
maxTimeInterval = "day";
break;
case TIME_RESOLUTION_HOUR:
maxTimeInterval = "hour";
break;
case TIME_RESOLUTION_MINUTE:
maxTimeInterval = "minute";
break;
case TIME_RESOLUTION_SECOND:
maxTimeInterval = "second";
break;
default:
return MS_FAILURE;
}
switch(mintimeresolution) {
case TIME_RESOLUTION_YEAR:
minTimeInterval = "year";
break;
case TIME_RESOLUTION_MONTH:
minTimeInterval = "month";
break;
case TIME_RESOLUTION_DAY:
minTimeInterval = "day";
break;
case TIME_RESOLUTION_HOUR:
minTimeInterval = "hour";
break;
case TIME_RESOLUTION_MINUTE:
minTimeInterval = "minute";
break;
case TIME_RESOLUTION_SECOND:
minTimeInterval = "second";
break;
default:
return MS_FAILURE;
}
snprintf(dest, destsize,"(%s >= date_trunc('%s',%s) and %s < date_trunc('%s',%s) + interval '1 %s')",
timecol, minTimeInterval, minTimeStamp,
timecol, maxTimeInterval, maxTimeStamp, maxTimeInterval);
return MS_SUCCESS;
}
int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
if( strchr(timestring,'\'') || strchr(timestring, '\\') ) {
msSetError(MS_MISCERR, "Invalid time filter.", "msPostGISLayerSetTimeFilter()");
return MS_FALSE;
}
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
char *msPostGISEscapeSQLParam(layerObj *layer, const char *pszString)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
int nError;
size_t nSrcLen;
char* pszEscapedStr =NULL;
if (layer && pszString && strlen(pszString) > 0) {
if(!msPostGISLayerIsOpen(layer))
msPostGISLayerOpen(layer);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
nSrcLen = strlen(pszString);
pszEscapedStr = (char*) msSmallMalloc( 2 * nSrcLen + 1);
PQescapeStringConn (layerinfo->pgconn, pszEscapedStr, pszString, nSrcLen, &nError);
if (nError != 0) {
free(pszEscapedStr);
pszEscapedStr = NULL;
}
}
return pszEscapedStr;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISEscapeSQLParam()");
return NULL;
#endif
}
void msPostGISEnablePaging(layerObj *layer, int value)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISEnablePaging called.\n");
}
if(!msPostGISLayerIsOpen(layer))
msPostGISLayerOpen(layer);
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
layerinfo->paging = value;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISEnablePaging()");
#endif
return;
}
int msPostGISGetPaging(layerObj *layer)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISGetPaging called.\n");
}
if(!msPostGISLayerIsOpen(layer))
return MS_TRUE;
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
return layerinfo->paging;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISEnablePaging()");
return MS_FAILURE;
#endif
}
int msPostGISLayerInitializeVirtualTable(layerObj *layer)
{
assert(layer != NULL);
assert(layer->vtable != NULL);
layer->vtable->LayerInitItemInfo = msPostGISLayerInitItemInfo;
layer->vtable->LayerFreeItemInfo = msPostGISLayerFreeItemInfo;
layer->vtable->LayerOpen = msPostGISLayerOpen;
layer->vtable->LayerIsOpen = msPostGISLayerIsOpen;
layer->vtable->LayerWhichShapes = msPostGISLayerWhichShapes;
layer->vtable->LayerNextShape = msPostGISLayerNextShape;
layer->vtable->LayerGetShape = msPostGISLayerGetShape;
layer->vtable->LayerClose = msPostGISLayerClose;
layer->vtable->LayerGetItems = msPostGISLayerGetItems;
/* layer->vtable->LayerGetExtent = msPostGISLayerGetExtent; */
layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
/* layer->vtable->LayerGetAutoStyle, not supported for this layer */
/* layer->vtable->LayerCloseConnection = msPostGISLayerClose; */
layer->vtable->LayerSetTimeFilter = msPostGISLayerSetTimeFilter;
/* layer->vtable->LayerCreateItems, use default */
/* layer->vtable->LayerGetNumFeatures, use default */
/* layer->vtable->LayerGetAutoProjection, use defaut*/
layer->vtable->LayerEscapeSQLParam = msPostGISEscapeSQLParam;
layer->vtable->LayerEnablePaging = msPostGISEnablePaging;
layer->vtable->LayerGetPaging = msPostGISGetPaging;
return MS_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-89/c/good_5843_0 |
crossvul-cpp_data_bad_3567_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* Escape and unescape URL encoding in strings. The functions return a new
* allocated string or NULL if an error occurred. */
#include "setup.h"
#include <curl/curl.h>
#include "curl_memory.h"
#include "urldata.h"
#include "warnless.h"
#include "non-ascii.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
/* The last #include file should be: */
#include "memdebug.h"
/* Portable character check (remember EBCDIC). Do not use isalnum() because
its behavior is altered by the current locale.
See http://tools.ietf.org/html/rfc3986#section-2.3
*/
static bool Curl_isunreserved(unsigned char in)
{
switch (in) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
case '-': case '.': case '_': case '~':
return TRUE;
default:
break;
}
return FALSE;
}
/* for ABI-compatibility with previous versions */
char *curl_escape(const char *string, int inlength)
{
return curl_easy_escape(NULL, string, inlength);
}
/* for ABI-compatibility with previous versions */
char *curl_unescape(const char *string, int length)
{
return curl_easy_unescape(NULL, string, length, NULL);
}
char *curl_easy_escape(CURL *handle, const char *string, int inlength)
{
size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;
char *ns;
char *testing_ptr = NULL;
unsigned char in; /* we need to treat the characters unsigned */
size_t newlen = alloc;
int strindex=0;
size_t length;
CURLcode res;
ns = malloc(alloc);
if(!ns)
return NULL;
length = alloc-1;
while(length--) {
in = *string;
if(Curl_isunreserved(in))
/* just copy this */
ns[strindex++]=in;
else {
/* encode it */
newlen += 2; /* the size grows with two, since this'll become a %XX */
if(newlen > alloc) {
alloc *= 2;
testing_ptr = realloc(ns, alloc);
if(!testing_ptr) {
free( ns );
return NULL;
}
else {
ns = testing_ptr;
}
}
res = Curl_convert_to_network(handle, &in, 1);
if(res) {
/* Curl_convert_to_network calls failf if unsuccessful */
free(ns);
return NULL;
}
snprintf(&ns[strindex], 4, "%%%02X", in);
strindex+=3;
}
string++;
}
ns[strindex]=0; /* terminate it */
return ns;
}
/*
* Unescapes the given URL escaped string of given length. Returns a
* pointer to a malloced string with length given in *olen.
* If length == 0, the length is assumed to be strlen(string).
* If olen == NULL, no output length is stored.
*/
char *curl_easy_unescape(CURL *handle, const char *string, int length,
int *olen)
{
int alloc = (length?length:(int)strlen(string))+1;
char *ns = malloc(alloc);
unsigned char in;
int strindex=0;
unsigned long hex;
CURLcode res;
if(!ns)
return NULL;
while(--alloc > 0) {
in = *string;
if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
res = Curl_convert_from_network(handle, &in, 1);
if(res) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return NULL;
}
string+=2;
alloc-=2;
}
ns[strindex++] = in;
string++;
}
ns[strindex]=0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
return ns;
}
/* For operating systems/environments that use different malloc/free
systems for the app and for this library, we provide a free that uses
the library's memory system */
void curl_free(void *p)
{
if(p)
free(p);
}
| ./CrossVul/dataset_final_sorted/CWE-89/c/bad_3567_0 |
crossvul-cpp_data_good_3567_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* Escape and unescape URL encoding in strings. The functions return a new
* allocated string or NULL if an error occurred. */
#include "setup.h"
#include <curl/curl.h>
#include "curl_memory.h"
#include "urldata.h"
#include "warnless.h"
#include "non-ascii.h"
#include "escape.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
/* The last #include file should be: */
#include "memdebug.h"
/* Portable character check (remember EBCDIC). Do not use isalnum() because
its behavior is altered by the current locale.
See http://tools.ietf.org/html/rfc3986#section-2.3
*/
static bool Curl_isunreserved(unsigned char in)
{
switch (in) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
case '-': case '.': case '_': case '~':
return TRUE;
default:
break;
}
return FALSE;
}
/* for ABI-compatibility with previous versions */
char *curl_escape(const char *string, int inlength)
{
return curl_easy_escape(NULL, string, inlength);
}
/* for ABI-compatibility with previous versions */
char *curl_unescape(const char *string, int length)
{
return curl_easy_unescape(NULL, string, length, NULL);
}
char *curl_easy_escape(CURL *handle, const char *string, int inlength)
{
size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;
char *ns;
char *testing_ptr = NULL;
unsigned char in; /* we need to treat the characters unsigned */
size_t newlen = alloc;
size_t strindex=0;
size_t length;
CURLcode res;
ns = malloc(alloc);
if(!ns)
return NULL;
length = alloc-1;
while(length--) {
in = *string;
if(Curl_isunreserved(in))
/* just copy this */
ns[strindex++]=in;
else {
/* encode it */
newlen += 2; /* the size grows with two, since this'll become a %XX */
if(newlen > alloc) {
alloc *= 2;
testing_ptr = realloc(ns, alloc);
if(!testing_ptr) {
free( ns );
return NULL;
}
else {
ns = testing_ptr;
}
}
res = Curl_convert_to_network(handle, &in, 1);
if(res) {
/* Curl_convert_to_network calls failf if unsuccessful */
free(ns);
return NULL;
}
snprintf(&ns[strindex], 4, "%%%02X", in);
strindex+=3;
}
string++;
}
ns[strindex]=0; /* terminate it */
return ns;
}
/*
* Curl_urldecode() URL decodes the given string.
*
* Optionally detects control characters (byte codes lower than 32) in the
* data and rejects such data.
*
* Returns a pointer to a malloced string in *ostring with length given in
* *olen. If length == 0, the length is assumed to be strlen(string).
*
*/
CURLcode Curl_urldecode(struct SessionHandle *data,
const char *string, size_t length,
char **ostring, size_t *olen,
bool reject_ctrl)
{
size_t alloc = (length?length:strlen(string))+1;
char *ns = malloc(alloc);
unsigned char in;
size_t strindex=0;
unsigned long hex;
CURLcode res;
if(!ns)
return CURLE_OUT_OF_MEMORY;
while(--alloc > 0) {
in = *string;
if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
res = Curl_convert_from_network(data, &in, 1);
if(res) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return res;
}
string+=2;
alloc-=2;
}
if(reject_ctrl && (in < 0x20)) {
free(ns);
return CURLE_URL_MALFORMAT;
}
ns[strindex++] = in;
string++;
}
ns[strindex]=0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
if(ostring)
/* store output string */
*ostring = ns;
return CURLE_OK;
}
/*
* Unescapes the given URL escaped string of given length. Returns a
* pointer to a malloced string with length given in *olen.
* If length == 0, the length is assumed to be strlen(string).
* If olen == NULL, no output length is stored.
*/
char *curl_easy_unescape(CURL *handle, const char *string, int length,
int *olen)
{
char *str = NULL;
size_t inputlen = length;
size_t outputlen;
CURLcode res = Curl_urldecode(handle, string, inputlen, &str, &outputlen,
FALSE);
if(res)
return NULL;
if(olen)
*olen = curlx_uztosi(outputlen);
return str;
}
/* For operating systems/environments that use different malloc/free
systems for the app and for this library, we provide a free that uses
the library's memory system */
void curl_free(void *p)
{
if(p)
free(p);
}
| ./CrossVul/dataset_final_sorted/CWE-89/c/good_3567_0 |
crossvul-cpp_data_good_3567_3 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC1939 POP3 protocol
* RFC2384 POP URL Scheme
* RFC2595 Using TLS with IMAP, POP3 and ACAP
*
***************************************************************************/
#include "setup.h"
#ifndef CURL_DISABLE_POP3
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "if2ip.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "pop3.h"
#include "strtoofft.h"
#include "strequal.h"
#include "sslgen.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "rawstr.h"
#include "strtoofft.h"
#include "http_proxy.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/* Local API functions */
static CURLcode pop3_parse_url_path(struct connectdata *conn);
static CURLcode pop3_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode pop3_do(struct connectdata *conn, bool *done);
static CURLcode pop3_done(struct connectdata *conn,
CURLcode, bool premature);
static CURLcode pop3_connect(struct connectdata *conn, bool *done);
static CURLcode pop3_disconnect(struct connectdata *conn, bool dead);
static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done);
static int pop3_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks);
static CURLcode pop3_doing(struct connectdata *conn,
bool *dophase_done);
static CURLcode pop3_setup_connection(struct connectdata * conn);
/*
* POP3 protocol handler.
*/
const struct Curl_handler Curl_handler_pop3 = {
"POP3", /* scheme */
pop3_setup_connection, /* setup_connection */
pop3_do, /* do_it */
pop3_done, /* done */
ZERO_NULL, /* do_more */
pop3_connect, /* connect_it */
pop3_multi_statemach, /* connecting */
pop3_doing, /* doing */
pop3_getsock, /* proto_getsock */
pop3_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
pop3_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3, /* defport */
CURLPROTO_POP3, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */
};
#ifdef USE_SSL
/*
* POP3S protocol handler.
*/
const struct Curl_handler Curl_handler_pop3s = {
"POP3S", /* scheme */
pop3_setup_connection, /* setup_connection */
pop3_do, /* do_it */
pop3_done, /* done */
ZERO_NULL, /* do_more */
pop3_connect, /* connect_it */
pop3_multi_statemach, /* connecting */
pop3_doing, /* doing */
pop3_getsock, /* proto_getsock */
pop3_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
pop3_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3S, /* defport */
CURLPROTO_POP3 | CURLPROTO_POP3S, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL
| PROTOPT_NOURLQUERY /* flags */
};
#endif
#ifndef CURL_DISABLE_HTTP
/*
* HTTP-proxyed POP3 protocol handler.
*/
static const struct Curl_handler Curl_handler_pop3_proxy = {
"POP3", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* HTTP-proxyed POP3S protocol handler.
*/
static const struct Curl_handler Curl_handler_pop3s_proxy = {
"POP3S", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_POP3S, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#endif
#endif
/* function that checks for a pop3 status code at the start of the given
string */
static int pop3_endofresp(struct pingpong *pp,
int *resp)
{
char *line = pp->linestart_resp;
size_t len = pp->nread_resp;
if(((len >= 3) && !memcmp("+OK", line, 3)) ||
((len >= 4) && !memcmp("-ERR", line, 4))) {
*resp=line[1]; /* O or E */
return TRUE;
}
return FALSE; /* nothing for us */
}
/* This is the ONLY way to change POP3 state! */
static void state(struct connectdata *conn,
pop3state newstate)
{
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[]={
"STOP",
"SERVERGREET",
"USER",
"PASS",
"STARTTLS",
"LIST",
"LIST_SINGLE",
"RETR",
"QUIT",
/* LAST */
};
#endif
struct pop3_conn *pop3c = &conn->proto.pop3c;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
if(pop3c->state != newstate)
infof(conn->data, "POP3 %p state change from %s to %s\n",
pop3c, names[pop3c->state], names[newstate]);
#endif
pop3c->state = newstate;
}
static CURLcode pop3_state_user(struct connectdata *conn)
{
CURLcode result;
struct FTP *pop3 = conn->data->state.proto.pop3;
/* send USER */
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "USER %s",
pop3->user?pop3->user:"");
if(result)
return result;
state(conn, POP3_USER);
return CURLE_OK;
}
/* For the POP3 "protocol connect" and "doing" phases only */
static int pop3_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.pop3c.pp, socks, numsocks);
}
#ifdef USE_SSL
static void pop3_to_pop3s(struct connectdata *conn)
{
conn->handler = &Curl_handler_pop3s;
}
#else
#define pop3_to_pop3s(x) Curl_nop_stmt
#endif
/* for STARTTLS responses */
static CURLcode pop3_state_starttls_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied. %c", pop3code);
result = CURLE_USE_SSL_FAILED;
state(conn, POP3_STOP);
}
else
result = pop3_state_user(conn);
}
else {
/* Curl_ssl_connect is BLOCKING */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(CURLE_OK == result) {
pop3_to_pop3s(conn);
result = pop3_state_user(conn);
}
else {
state(conn, POP3_STOP);
}
}
return result;
}
/* for USER responses */
static CURLcode pop3_state_user_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
failf(data, "Access denied. %c", pop3code);
result = CURLE_LOGIN_DENIED;
}
else
/* send PASS */
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "PASS %s",
pop3->passwd?pop3->passwd:"");
if(result)
return result;
state(conn, POP3_PASS);
return result;
}
/* for PASS responses */
static CURLcode pop3_state_pass_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
failf(data, "Access denied. %c", pop3code);
result = CURLE_LOGIN_DENIED;
}
state(conn, POP3_STOP);
return result;
}
/* for the retr response */
static CURLcode pop3_state_retr_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
(void)instate; /* no use for this yet */
if('O' != pop3code) {
state(conn, POP3_STOP);
return CURLE_RECV_ERROR;
}
/* POP3 download */
Curl_setup_transfer(conn, FIRSTSOCKET, -1, FALSE,
pop3->bytecountp, -1, NULL); /* no upload here */
if(pp->cache) {
/* At this point there is a bunch of data in the header "cache" that is
actually body content, send it as body and then skip it. Do note
that there may even be additional "headers" after the body. */
/* we may get the EOB already here! */
result = Curl_pop3_write(conn, pp->cache, pp->cache_size);
if(result)
return result;
/* cache is drained */
free(pp->cache);
pp->cache = NULL;
pp->cache_size = 0;
}
state(conn, POP3_STOP);
return result;
}
/* for the list response */
static CURLcode pop3_state_list_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
(void)instate; /* no use for this yet */
if('O' != pop3code) {
state(conn, POP3_STOP);
return CURLE_RECV_ERROR;
}
/* This 'OK' line ends with a CR LF pair which is the two first bytes of the
EOB string so count this is two matching bytes. This is necessary to make
the code detect the EOB if the only data than comes now is %2e CR LF like
when there is no body to return. */
pop3c->eob = 2;
/* But since this initial CR LF pair is not part of the actual body, we set
the strip counter here so that these bytes won't be delivered. */
pop3c->strip = 2;
/* POP3 download */
Curl_setup_transfer(conn, FIRSTSOCKET, -1, FALSE, pop3->bytecountp,
-1, NULL); /* no upload here */
if(pp->cache) {
/* cache holds the email ID listing */
/* we may get the EOB already here! */
result = Curl_pop3_write(conn, pp->cache, pp->cache_size);
if(result)
return result;
/* cache is drained */
free(pp->cache);
pp->cache = NULL;
pp->cache_size = 0;
}
state(conn, POP3_STOP);
return result;
}
/* for LIST response with a given message */
static CURLcode pop3_state_list_single_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(pop3code != 'O') {
failf(data, "Invalid message. %c", pop3code);
result = CURLE_REMOTE_FILE_NOT_FOUND;
}
state(conn, POP3_STOP);
return result;
}
/* start the DO phase for RETR */
static CURLcode pop3_retr(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct pop3_conn *pop3c = &conn->proto.pop3c;
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "RETR %s", pop3c->mailbox);
if(result)
return result;
state(conn, POP3_RETR);
return result;
}
/* start the DO phase for LIST */
static CURLcode pop3_list(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct pop3_conn *pop3c = &conn->proto.pop3c;
if(pop3c->mailbox[0] != '\0')
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "LIST %s", pop3c->mailbox);
else
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "LIST");
if(result)
return result;
if(pop3c->mailbox[0] != '\0')
state(conn, POP3_LIST_SINGLE);
else
state(conn, POP3_LIST);
return result;
}
static CURLcode pop3_statemach_act(struct connectdata *conn)
{
CURLcode result;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct SessionHandle *data=conn->data;
int pop3code;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
size_t nread = 0;
if(pp->sendleft)
return Curl_pp_flushsend(pp);
/* we read a piece of response */
result = Curl_pp_readresp(sock, pp, &pop3code, &nread);
if(result)
return result;
if(pop3code) {
/* we have now received a full POP3 server response */
switch(pop3c->state) {
case POP3_SERVERGREET:
if(pop3code != 'O') {
failf(data, "Got unexpected pop3-server response");
return CURLE_FTP_WEIRD_SERVER_REPLY;
}
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested. Switch
to TLS connection now */
result = Curl_pp_sendf(&pop3c->pp, "STLS");
state(conn, POP3_STARTTLS);
}
else
result = pop3_state_user(conn);
if(result)
return result;
break;
case POP3_USER:
result = pop3_state_user_resp(conn, pop3code, pop3c->state);
break;
case POP3_PASS:
result = pop3_state_pass_resp(conn, pop3code, pop3c->state);
break;
case POP3_STARTTLS:
result = pop3_state_starttls_resp(conn, pop3code, pop3c->state);
break;
case POP3_RETR:
result = pop3_state_retr_resp(conn, pop3code, pop3c->state);
break;
case POP3_LIST:
result = pop3_state_list_resp(conn, pop3code, pop3c->state);
break;
case POP3_LIST_SINGLE:
result = pop3_state_list_single_resp(conn, pop3code, pop3c->state);
break;
case POP3_QUIT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, POP3_STOP);
break;
}
}
return result;
}
/* called repeatedly until done from multi.c */
static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done)
{
struct pop3_conn *pop3c = &conn->proto.pop3c;
CURLcode result = Curl_pp_multi_statemach(&pop3c->pp);
*done = (pop3c->state == POP3_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode pop3_easy_statemach(struct connectdata *conn)
{
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct pingpong *pp = &pop3c->pp;
CURLcode result = CURLE_OK;
while(pop3c->state != POP3_STOP) {
result = Curl_pp_easy_statemach(pp);
if(result)
break;
}
return result;
}
/*
* Allocate and initialize the struct POP3 for the current SessionHandle. If
* need be.
*/
static CURLcode pop3_init(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
if(!pop3) {
pop3 = data->state.proto.pop3 = calloc(sizeof(struct FTP), 1);
if(!pop3)
return CURLE_OUT_OF_MEMORY;
}
/* get some initial data into the pop3 struct */
pop3->bytecountp = &data->req.bytecount;
/* No need to duplicate user+password, the connectdata struct won't change
during a session, but we re-init them here since on subsequent inits
since the conn struct may have changed or been replaced.
*/
pop3->user = conn->user;
pop3->passwd = conn->passwd;
return CURLE_OK;
}
/*
* pop3_connect() should do everything that is to be considered a part of
* the connection phase.
*
* The variable 'done' points to will be TRUE if the protocol-layer connect
* phase is done when this function returns, or FALSE is not. When called as
* a part of the easy interface, it will always be TRUE.
*/
static CURLcode pop3_connect(struct connectdata *conn,
bool *done) /* see description above */
{
CURLcode result;
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct SessionHandle *data=conn->data;
struct pingpong *pp = &pop3c->pp;
*done = FALSE; /* default to not done yet */
/* If there already is a protocol-specific struct allocated for this
sessionhandle, deal with it */
Curl_reset_reqproto(conn);
result = pop3_init(conn);
if(CURLE_OK != result)
return result;
/* We always support persistent connections on pop3 */
conn->bits.close = FALSE;
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = pop3_statemach_act;
pp->endofresp = pop3_endofresp;
pp->conn = conn;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
/* for POP3 over HTTP proxy */
struct HTTP http_proxy;
struct FTP *pop3_save;
/* BLOCKING */
/* We want "seamless" POP3 operations through HTTP proxy tunnel */
/* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the member
* conn->proto.http; we want POP3 through HTTP and we have to change the
* member temporarily for connecting to the HTTP proxy. After
* Curl_proxyCONNECT we have to set back the member to the original struct
* POP3 pointer
*/
pop3_save = data->state.proto.pop3;
memset(&http_proxy, 0, sizeof(http_proxy));
data->state.proto.http = &http_proxy;
result = Curl_proxyCONNECT(conn, FIRSTSOCKET,
conn->host.name, conn->remote_port);
data->state.proto.pop3 = pop3_save;
if(CURLE_OK != result)
return result;
}
if(conn->handler->flags & PROTOPT_SSL) {
/* BLOCKING */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(result)
return result;
}
Curl_pp_init(pp); /* init the response reader stuff */
/* When we connect, we start in the state where we await the server greet
response */
state(conn, POP3_SERVERGREET);
if(data->state.used_interface == Curl_if_multi)
result = pop3_multi_statemach(conn, done);
else {
result = pop3_easy_statemach(conn);
if(!result)
*done = TRUE;
}
return result;
}
/***********************************************************************
*
* pop3_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
bool premature)
{
struct SessionHandle *data = conn->data;
struct FTP *pop3 = data->state.proto.pop3;
struct pop3_conn *pop3c = &conn->proto.pop3c;
CURLcode result=CURLE_OK;
(void)premature;
if(!pop3)
/* When the easy handle is removed from the multi while libcurl is still
* trying to resolve the host name, it seems that the pop3 struct is not
* yet initialized, but the removal action calls Curl_done() which calls
* this function. So we simply return success if no pop3 pointer is set.
*/
return CURLE_OK;
if(status) {
conn->bits.close = TRUE; /* marked for closure */
result = status; /* use the already set error code */
}
Curl_safefree(pop3c->mailbox);
pop3c->mailbox = NULL;
/* clear these for next connection */
pop3->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* pop3_perform()
*
* This is the actual DO function for POP3. Get a file/directory according to
* the options previously setup.
*/
static
CURLcode pop3_perform(struct connectdata *conn,
bool *connected, /* connect status after PASV / PORT */
bool *dophase_done)
{
/* this is POP3 and no proxy */
CURLcode result=CURLE_OK;
struct pop3_conn *pop3c = &conn->proto.pop3c;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(conn->data->set.opt_no_body) {
/* requested no body means no transfer... */
struct FTP *pop3 = conn->data->state.proto.pop3;
pop3->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* start the first command in the DO phase */
/* If mailbox is empty, then assume user wants listing for mail IDs,
* otherwise, attempt to retrieve the mail-id stored in mailbox
*/
if(strlen(pop3c->mailbox) && !conn->data->set.ftp_list_only)
result = pop3_retr(conn);
else
result = pop3_list(conn);
if(result)
return result;
/* run the state-machine */
if(conn->data->state.used_interface == Curl_if_multi)
result = pop3_multi_statemach(conn, dophase_done);
else {
result = pop3_easy_statemach(conn);
*dophase_done = TRUE; /* with the easy interface we are done here */
}
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* pop3_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (pop3_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode pop3_do(struct connectdata *conn, bool *done)
{
CURLcode retcode = CURLE_OK;
*done = FALSE; /* default to false */
/*
Since connections can be re-used between SessionHandles, this might be a
connection already existing but on a fresh SessionHandle struct so we must
make sure we have a good 'struct POP3' to play with. For new connections,
the struct POP3 is allocated and setup in the pop3_connect() function.
*/
Curl_reset_reqproto(conn);
retcode = pop3_init(conn);
if(retcode)
return retcode;
retcode = pop3_parse_url_path(conn);
if(retcode)
return retcode;
retcode = pop3_regular_transfer(conn, done);
return retcode;
}
/***********************************************************************
*
* pop3_quit()
*
* This should be called before calling sclose(). We should then wait for the
* response from the server before returning. The calling code should then try
* to close the connection.
*
*/
static CURLcode pop3_quit(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "QUIT", NULL);
if(result)
return result;
state(conn, POP3_QUIT);
result = pop3_easy_statemach(conn);
return result;
}
/***********************************************************************
*
* pop3_disconnect()
*
* Disconnect from an POP3 server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode pop3_disconnect(struct connectdata *conn, bool dead_connection)
{
struct pop3_conn *pop3c= &conn->proto.pop3c;
/* We cannot send quit unconditionally. If this connection is stale or
bad in any way, sending quit and waiting around here will make the
disconnect wait in vain and cause more problems than we need to.
*/
/* The POP3 session may or may not have been allocated/setup at this
point! */
if(!dead_connection && pop3c->pp.conn)
(void)pop3_quit(conn); /* ignore errors on the LOGOUT */
Curl_pp_disconnect(&pop3c->pp);
return CURLE_OK;
}
/***********************************************************************
*
* pop3_parse_url_path()
*
* Parse the URL path into separate path components.
*
*/
static CURLcode pop3_parse_url_path(struct connectdata *conn)
{
/* the pop3 struct is already inited in pop3_connect() */
struct pop3_conn *pop3c = &conn->proto.pop3c;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
/* url decode the path and use this mailbox */
return Curl_urldecode(data, path, 0, &pop3c->mailbox, NULL, TRUE);
}
/* call this when the DO phase has completed */
static CURLcode pop3_dophase_done(struct connectdata *conn,
bool connected)
{
struct FTP *pop3 = conn->data->state.proto.pop3;
(void)connected;
if(pop3->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
return CURLE_OK;
}
/* called from multi.c while DOing */
static CURLcode pop3_doing(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result;
result = pop3_multi_statemach(conn, dophase_done);
if(*dophase_done) {
result = pop3_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* pop3_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*
*/
static
CURLcode pop3_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result=CURLE_OK;
bool connected=FALSE;
struct SessionHandle *data = conn->data;
data->req.size = -1; /* make sure this is unknown at this point */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, 0);
Curl_pgrsSetDownloadSize(data, 0);
result = pop3_perform(conn,
&connected, /* have we connected after PASV/PORT */
dophase_done); /* all commands in the DO-phase done? */
if(CURLE_OK == result) {
if(!*dophase_done)
/* the DO phase has not completed yet */
return CURLE_OK;
result = pop3_dophase_done(conn, connected);
if(result)
return result;
}
return result;
}
static CURLcode pop3_setup_connection(struct connectdata * conn)
{
struct SessionHandle *data = conn->data;
if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
/* Unless we have asked to tunnel pop3 operations through the proxy, we
switch and use HTTP operations only */
#ifndef CURL_DISABLE_HTTP
if(conn->handler == &Curl_handler_pop3)
conn->handler = &Curl_handler_pop3_proxy;
else {
#ifdef USE_SSL
conn->handler = &Curl_handler_pop3s_proxy;
#else
failf(data, "POP3S not supported!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
/*
* We explicitly mark this connection as persistent here as we're doing
* POP3 over HTTP and thus we accidentally avoid setting this value
* otherwise.
*/
conn->bits.close = FALSE;
#else
failf(data, "POP3 over http proxy requires HTTP support built-in!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
/* this is the 5-bytes End-Of-Body marker for POP3 */
#define POP3_EOB "\x0d\x0a\x2e\x0d\x0a"
#define POP3_EOB_LEN 5
/*
* This function scans the body after the end-of-body and writes everything
* until the end is found.
*/
CURLcode Curl_pop3_write(struct connectdata *conn,
char *str,
size_t nread)
{
/* This code could be made into a special function in the handler struct. */
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct SingleRequest *k = &data->req;
struct pop3_conn *pop3c = &conn->proto.pop3c;
bool strip_dot = FALSE;
size_t last = 0;
size_t i;
/* Search through the buffer looking for the end-of-body marker which is
5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches
the eob so the server will have prefixed it with an extra dot which we
need to strip out. Additionally the marker could of course be spread out
over 5 different data chunks */
for(i = 0; i < nread; i++) {
size_t prev = pop3c->eob;
switch(str[i]) {
case 0x0d:
if(pop3c->eob == 0) {
pop3c->eob++;
if(i) {
/* Write out the body part that didn't match */
result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
i - last);
if(result)
return result;
last = i;
}
}
else if(pop3c->eob == 3)
pop3c->eob++;
else
/* If the character match wasn't at position 0 or 3 then restart the
pattern matching */
pop3c->eob = 1;
break;
case 0x0a:
if(pop3c->eob == 1 || pop3c->eob == 4)
pop3c->eob++;
else
/* If the character match wasn't at position 1 or 4 then start the
search again */
pop3c->eob = 0;
break;
case 0x2e:
if(pop3c->eob == 2)
pop3c->eob++;
else if(pop3c->eob == 3) {
/* We have an extra dot after the CRLF which we need to strip off */
strip_dot = TRUE;
pop3c->eob = 0;
}
else
/* If the character match wasn't at position 2 then start the search
again */
pop3c->eob = 0;
break;
default:
pop3c->eob = 0;
break;
}
/* Did we have a partial match which has subsequently failed? */
if(prev && prev >= pop3c->eob) {
/* Strip can only be non-zero for the very first mismatch after CRLF
and then both prev and strip are equal and nothing will be output
below */
while(prev && pop3c->strip) {
prev--;
pop3c->strip--;
}
if(prev) {
/* If the partial match was the CRLF and dot then only write the CRLF
as the server would have inserted the dot */
result = Curl_client_write(conn, CLIENTWRITE_BODY, (char*)POP3_EOB,
strip_dot ? prev - 1 : prev);
if(result)
return result;
last = i;
strip_dot = FALSE;
}
}
}
if(pop3c->eob == POP3_EOB_LEN) {
/* We have a full match so the transfer is done! */
k->keepon &= ~KEEP_RECV;
pop3c->eob = 0;
return CURLE_OK;
}
if(pop3c->eob)
/* While EOB is matching nothing should be output */
return CURLE_OK;
if(nread - last) {
result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
nread - last);
}
return result;
}
#endif /* CURL_DISABLE_POP3 */
| ./CrossVul/dataset_final_sorted/CWE-89/c/good_3567_3 |
crossvul-cpp_data_bad_5843_0 | /******************************************************************************
* $Id$
*
* Project: MapServer
* Purpose: PostGIS CONNECTIONTYPE support.
* Author: Paul Ramsey <pramsey@cleverelephant.ca>
* Dave Blasby <dblasby@gmail.com>
*
******************************************************************************
* Copyright (c) 2010 Paul Ramsey
* Copyright (c) 2002 Refractions Research
*
* 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 of this Software or works derived from this 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.
****************************************************************************/
/*
** Some theory of operation:
**
** Build SQL from DATA statement and LAYER state. SQL is always of the form:
**
** SELECT [this, that, other], geometry, uid
** FROM [table|(subquery) as sub]
** WHERE [box] AND [filter]
**
** So the geometry always resides at layer->numitems and the uid always
** resides at layer->numitems + 1
**
** Geometry is requested as Hex encoded WKB. The endian is always requested
** as the client endianness.
**
** msPostGISLayerWhichShapes creates SQL based on DATA and LAYER state,
** executes it, and places the un-read PGresult handle in the layerinfo->pgresult,
** setting the layerinfo->rownum to 0.
**
** msPostGISNextShape reads a row, increments layerinfo->rownum, and returns
** MS_SUCCESS, until rownum reaches ntuples, and it returns MS_DONE instead.
**
*/
/* GNU needs this for strcasestr */
#define _GNU_SOURCE
/* required for MSVC */
#define _USE_MATH_DEFINES
#include <assert.h>
#include <string.h>
#include <math.h>
#include "mapserver.h"
#include "maptime.h"
#include "mappostgis.h"
#define FP_EPSILON 1e-12
#define FP_EQ(a, b) (fabs((a)-(b)) < FP_EPSILON)
#define FP_LEFT -1
#define FP_RIGHT 1
#define FP_COLINEAR 0
#define SEGMENT_ANGLE 10.0
#define SEGMENT_MINPOINTS 10
#ifdef USE_POSTGIS
/*
** msPostGISCloseConnection()
**
** Handler registered witih msConnPoolRegister so that Mapserver
** can clean up open connections during a shutdown.
*/
void msPostGISCloseConnection(void *pgconn)
{
PQfinish((PGconn*)pgconn);
}
/*
** msPostGISCreateLayerInfo()
*/
msPostGISLayerInfo *msPostGISCreateLayerInfo(void)
{
msPostGISLayerInfo *layerinfo = msSmallMalloc(sizeof(msPostGISLayerInfo));
layerinfo->sql = NULL;
layerinfo->srid = NULL;
layerinfo->uid = NULL;
layerinfo->pgconn = NULL;
layerinfo->pgresult = NULL;
layerinfo->geomcolumn = NULL;
layerinfo->fromsource = NULL;
layerinfo->endian = 0;
layerinfo->rownum = 0;
layerinfo->version = 0;
layerinfo->paging = MS_TRUE;
return layerinfo;
}
/*
** msPostGISFreeLayerInfo()
*/
void msPostGISFreeLayerInfo(layerObj *layer)
{
msPostGISLayerInfo *layerinfo = NULL;
layerinfo = (msPostGISLayerInfo*)layer->layerinfo;
if ( layerinfo->sql ) free(layerinfo->sql);
if ( layerinfo->uid ) free(layerinfo->uid);
if ( layerinfo->srid ) free(layerinfo->srid);
if ( layerinfo->geomcolumn ) free(layerinfo->geomcolumn);
if ( layerinfo->fromsource ) free(layerinfo->fromsource);
if ( layerinfo->pgresult ) PQclear(layerinfo->pgresult);
if ( layerinfo->pgconn ) msConnPoolRelease(layer, layerinfo->pgconn);
free(layerinfo);
layer->layerinfo = NULL;
}
/*
** postgresqlNoticeHandler()
**
** Propagate messages from the database to the Mapserver log,
** set in PQsetNoticeProcessor during layer open.
*/
void postresqlNoticeHandler(void *arg, const char *message)
{
layerObj *lp;
lp = (layerObj*)arg;
if (lp->debug) {
msDebug("%s\n", message);
}
}
/*
** Expandable pointObj array. The lineObj unfortunately
** is not useful for this purpose, so we have this one.
*/
pointArrayObj*
pointArrayNew(int maxpoints)
{
pointArrayObj *d = msSmallMalloc(sizeof(pointArrayObj));
if ( maxpoints < 1 ) maxpoints = 1; /* Avoid a degenerate case */
d->maxpoints = maxpoints;
d->data = msSmallMalloc(maxpoints * sizeof(pointObj));
d->npoints = 0;
return d;
}
/*
** Utility function to creal up the pointArrayObj
*/
void
pointArrayFree(pointArrayObj *d)
{
if ( ! d ) return;
if ( d->data ) free(d->data);
free(d);
}
/*
** Add a pointObj to the pointObjArray, allocating
** extra storage space if we've used up our existing
** buffer.
*/
static int
pointArrayAddPoint(pointArrayObj *d, const pointObj *p)
{
if ( !p || !d ) return MS_FAILURE;
/* Avoid overwriting memory buffer */
if ( d->maxpoints - d->npoints == 0 ) {
d->maxpoints *= 2;
d->data = realloc(d->data, d->maxpoints * sizeof(pointObj));
}
d->data[d->npoints] = *p;
d->npoints++;
return MS_SUCCESS;
}
/*
** Pass an input type number through the PostGIS version
** type map array to handle the pre-2.0 incorrect WKB types
*/
static int
wkbTypeMap(wkbObj *w, int type)
{
if ( type < WKB_TYPE_COUNT )
return w->typemap[type];
else
return 0;
}
/*
** Read the WKB type number from a wkbObj without
** advancing the read pointer.
*/
static int
wkbType(wkbObj *w)
{
int t;
memcpy(&t, (w->ptr + 1), sizeof(int));
return wkbTypeMap(w,t);
}
/*
** Read the type number of the first element of a
** collection without advancing the read pointer.
*/
static int
wkbCollectionSubType(wkbObj *w)
{
int t;
memcpy(&t, (w->ptr + 1 + 4 + 4 + 1), sizeof(int));
return wkbTypeMap(w,t);
}
/*
** Read one byte from the WKB and advance the read pointer
*/
static char
wkbReadChar(wkbObj *w)
{
char c;
memcpy(&c, w->ptr, sizeof(char));
w->ptr += sizeof(char);
return c;
}
/*
** Read one integer from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline int
wkbReadInt(wkbObj *w)
{
int i;
memcpy(&i, w->ptr, sizeof(int));
w->ptr += sizeof(int);
return i;
}
/*
** Read one double from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline double
wkbReadDouble(wkbObj *w)
{
double d;
memcpy(&d, w->ptr, sizeof(double));
w->ptr += sizeof(double);
return d;
}
/*
** Read one pointObj (two doubles) from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline void
wkbReadPointP(wkbObj *w, pointObj *p)
{
memcpy(&(p->x), w->ptr, sizeof(double));
w->ptr += sizeof(double);
memcpy(&(p->y), w->ptr, sizeof(double));
w->ptr += sizeof(double);
}
/*
** Read one pointObj (two doubles) from the WKB and advance the read pointer.
** We assume the endianess of the WKB is the same as this machine.
*/
static inline pointObj
wkbReadPoint(wkbObj *w)
{
pointObj p;
wkbReadPointP(w, &p);
return p;
}
/*
** Read a "point array" and return an allocated lineObj.
** A point array is a WKB fragment that starts with a
** point count, which is followed by that number of doubles * 2.
** Linestrings, circular strings, polygon rings, all show this
** form.
*/
static void
wkbReadLine(wkbObj *w, lineObj *line)
{
int i;
pointObj p;
int npoints = wkbReadInt(w);
line->numpoints = npoints;
line->point = msSmallMalloc(npoints * sizeof(pointObj));
for ( i = 0; i < npoints; i++ ) {
wkbReadPointP(w, &p);
line->point[i] = p;
}
}
/*
** Advance the read pointer past a geometry without returning any
** values. Used for skipping un-drawable elements in a collection.
*/
static void
wkbSkipGeometry(wkbObj *w)
{
int type, npoints, nrings, ngeoms, i;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
switch(type) {
case WKB_POINT:
w->ptr += 2 * sizeof(double);
break;
case WKB_CIRCULARSTRING:
case WKB_LINESTRING:
npoints = wkbReadInt(w);
w->ptr += npoints * 2 * sizeof(double);
break;
case WKB_POLYGON:
nrings = wkbReadInt(w);
for ( i = 0; i < nrings; i++ ) {
npoints = wkbReadInt(w);
w->ptr += npoints * 2 * sizeof(double);
}
break;
case WKB_MULTIPOINT:
case WKB_MULTILINESTRING:
case WKB_MULTIPOLYGON:
case WKB_GEOMETRYCOLLECTION:
case WKB_COMPOUNDCURVE:
case WKB_CURVEPOLYGON:
case WKB_MULTICURVE:
case WKB_MULTISURFACE:
ngeoms = wkbReadInt(w);
for ( i = 0; i < ngeoms; i++ ) {
wkbSkipGeometry(w);
}
}
}
/*
** Convert a WKB point to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvPointToShape(wkbObj *w, shapeObj *shape)
{
int type;
lineObj line;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_POINT ) return MS_FAILURE;
if( ! (shape->type == MS_SHAPE_POINT) ) return MS_FAILURE;
line.numpoints = 1;
line.point = msSmallMalloc(sizeof(pointObj));
line.point[0] = wkbReadPoint(w);
msAddLineDirectly(shape, &line);
return MS_SUCCESS;
}
/*
** Convert a WKB line string to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvLineStringToShape(wkbObj *w, shapeObj *shape)
{
int type;
lineObj line;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_LINESTRING ) return MS_FAILURE;
wkbReadLine(w,&line);
msAddLineDirectly(shape, &line);
return MS_SUCCESS;
}
/*
** Convert a WKB polygon to a shapeObj, advancing the read pointer as we go.
*/
static int
wkbConvPolygonToShape(wkbObj *w, shapeObj *shape)
{
int type;
int i, nrings;
lineObj line;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_POLYGON ) return MS_FAILURE;
/* How many rings? */
nrings = wkbReadInt(w);
/* Add each ring to the shape */
for( i = 0; i < nrings; i++ ) {
wkbReadLine(w,&line);
msAddLineDirectly(shape, &line);
}
return MS_SUCCESS;
}
/*
** Convert a WKB curve polygon to a shapeObj, advancing the read pointer as we go.
** The arc portions of the rings will be stroked to linestrings as they
** are read by the underlying circular string handling.
*/
static int
wkbConvCurvePolygonToShape(wkbObj *w, shapeObj *shape)
{
int type, i, ncomponents;
int failures = 0;
int was_poly = ( shape->type == MS_SHAPE_POLYGON );
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
ncomponents = wkbReadInt(w);
if( type != WKB_CURVEPOLYGON ) return MS_FAILURE;
/* Lower the allowed dimensionality so we can
* catch the linear ring components */
shape->type = MS_SHAPE_LINE;
for ( i = 0; i < ncomponents; i++ ) {
if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
wkbSkipGeometry(w);
failures++;
}
}
/* Go back to expected dimensionality */
if ( was_poly) shape->type = MS_SHAPE_POLYGON;
if ( failures == ncomponents )
return MS_FAILURE;
else
return MS_SUCCESS;
}
/*
** Convert a WKB circular string to a shapeObj, advancing the read pointer as we go.
** Arcs will be stroked to linestrings.
*/
static int
wkbConvCircularStringToShape(wkbObj *w, shapeObj *shape)
{
int type;
lineObj line = {0, NULL};
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
if( type != WKB_CIRCULARSTRING ) return MS_FAILURE;
/* Stroke the string into a point array */
if ( arcStrokeCircularString(w, SEGMENT_ANGLE, &line) == MS_FAILURE ) {
if(line.point) free(line.point);
return MS_FAILURE;
}
/* Fill in the lineObj */
if ( line.numpoints > 0 ) {
msAddLine(shape, &line);
if(line.point) free(line.point);
}
return MS_SUCCESS;
}
/*
** Compound curves need special handling. First we load
** each component of the curve on the a lineObj in a shape.
** Then we merge those lineObjs into a single lineObj. This
** allows compound curves to serve as closed rings in
** curve polygons.
*/
static int
wkbConvCompoundCurveToShape(wkbObj *w, shapeObj *shape)
{
int npoints = 0;
int type, ncomponents, i, j;
lineObj *line;
shapeObj shapebuf;
/*endian = */wkbReadChar(w);
type = wkbTypeMap(w,wkbReadInt(w));
/* Init our shape buffer */
msInitShape(&shapebuf);
if( type != WKB_COMPOUNDCURVE ) return MS_FAILURE;
/* How many components in the compound curve? */
ncomponents = wkbReadInt(w);
/* We'll load each component onto a line in a shape */
for( i = 0; i < ncomponents; i++ )
wkbConvGeometryToShape(w, &shapebuf);
/* Do nothing on empty */
if ( shapebuf.numlines == 0 )
return MS_FAILURE;
/* Count the total number of points */
for( i = 0; i < shapebuf.numlines; i++ )
npoints += shapebuf.line[i].numpoints;
/* Do nothing on empty */
if ( npoints == 0 )
return MS_FAILURE;
/* Allocate space for the new line */
line = msSmallMalloc(sizeof(lineObj));
line->numpoints = npoints;
line->point = msSmallMalloc(sizeof(pointObj) * npoints);
/* Copy in the points */
npoints = 0;
for ( i = 0; i < shapebuf.numlines; i++ ) {
for ( j = 0; j < shapebuf.line[i].numpoints; j++ ) {
/* Don't add a start point that duplicates an endpoint */
if( j == 0 && i > 0 &&
memcmp(&(line->point[npoints - 1]),&(shapebuf.line[i].point[j]),sizeof(pointObj)) == 0 ) {
continue;
}
line->point[npoints++] = shapebuf.line[i].point[j];
}
}
line->numpoints = npoints;
/* Clean up */
msFreeShape(&shapebuf);
/* Fill in the lineObj */
msAddLineDirectly(shape, line);
return MS_SUCCESS;
}
/*
** Convert a WKB collection string to a shapeObj, advancing the read pointer as we go.
** Many WKB types (MultiPoint, MultiLineString, MultiPolygon, MultiSurface,
** MultiCurve, GeometryCollection) can be treated identically as collections
** (they start with endian, type number and count of sub-elements, then provide the
** subelements as WKB) so are handled with this one function.
*/
static int
wkbConvCollectionToShape(wkbObj *w, shapeObj *shape)
{
int i, ncomponents;
int failures = 0;
/*endian = */wkbReadChar(w);
/*type = */wkbTypeMap(w,wkbReadInt(w));
ncomponents = wkbReadInt(w);
/*
* If we can draw any portion of the collection, we will,
* but if all the components fail, we will draw nothing.
*/
for ( i = 0; i < ncomponents; i++ ) {
if ( wkbConvGeometryToShape(w, shape) == MS_FAILURE ) {
wkbSkipGeometry(w);
failures++;
}
}
if ( failures == ncomponents )
return MS_FAILURE;
else
return MS_SUCCESS;
}
/*
** Generic handler to switch to the appropriate function for the WKB type.
** Note that we also handle switching here to avoid processing shapes
** we will be unable to draw. Example: we can't draw point features as
** a MS_SHAPE_LINE layer, so if the type is WKB_POINT and the layer is
** MS_SHAPE_LINE, we exit before converting.
*/
int
wkbConvGeometryToShape(wkbObj *w, shapeObj *shape)
{
int wkbtype = wkbType(w); /* Peak at the type number */
switch(wkbtype) {
/* Recurse into anonymous collections */
case WKB_GEOMETRYCOLLECTION:
return wkbConvCollectionToShape(w, shape);
/* Handle area types */
case WKB_POLYGON:
return wkbConvPolygonToShape(w, shape);
case WKB_MULTIPOLYGON:
return wkbConvCollectionToShape(w, shape);
case WKB_CURVEPOLYGON:
return wkbConvCurvePolygonToShape(w, shape);
case WKB_MULTISURFACE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into polygons */
if ( shape->type == MS_SHAPE_POLYGON ) return MS_FAILURE;
/* Handle linear types */
switch(wkbtype) {
case WKB_LINESTRING:
return wkbConvLineStringToShape(w, shape);
case WKB_CIRCULARSTRING:
return wkbConvCircularStringToShape(w, shape);
case WKB_COMPOUNDCURVE:
return wkbConvCompoundCurveToShape(w, shape);
case WKB_MULTILINESTRING:
return wkbConvCollectionToShape(w, shape);
case WKB_MULTICURVE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into lines */
if ( shape->type == MS_SHAPE_LINE ) return MS_FAILURE;
/* Handle point types */
switch(wkbtype) {
case WKB_POINT:
return wkbConvPointToShape(w, shape);
case WKB_MULTIPOINT:
return wkbConvCollectionToShape(w, shape);
}
/* This is a WKB type we don't know about! */
return MS_FAILURE;
}
/*
** Calculate determinant of a 3x3 matrix. Handy for
** the circle center calculation.
*/
static inline double
arcDeterminant3x3(double *m)
{
/* This had better be a 3x3 matrix or we'll fall to bits */
return m[0] * ( m[4] * m[8] - m[7] * m[5] ) -
m[3] * ( m[1] * m[8] - m[7] * m[2] ) +
m[6] * ( m[1] * m[5] - m[4] * m[2] );
}
/*
** What side of p1->p2 is q on?
*/
static inline int
arcSegmentSide(const pointObj *p1, const pointObj *p2, const pointObj *q)
{
double side = ( (q->x - p1->x) * (p2->y - p1->y) - (p2->x - p1->x) * (q->y - p1->y) );
if ( FP_EQ(side,0.0) ) {
return FP_COLINEAR;
} else {
if ( side < 0.0 )
return FP_LEFT;
else
return FP_RIGHT;
}
}
/*
** Calculate the center of the circle defined by three points.
** Using matrix approach from http://mathforum.org/library/drmath/view/55239.html
*/
int
arcCircleCenter(const pointObj *p1, const pointObj *p2, const pointObj *p3, pointObj *center, double *radius)
{
pointObj c;
double r;
/* Components of the matrices. */
double x1sq = p1->x * p1->x;
double x2sq = p2->x * p2->x;
double x3sq = p3->x * p3->x;
double y1sq = p1->y * p1->y;
double y2sq = p2->y * p2->y;
double y3sq = p3->y * p3->y;
double matrix_num_x[9];
double matrix_num_y[9];
double matrix_denom[9];
/* Intialize matrix_num_x */
matrix_num_x[0] = x1sq+y1sq;
matrix_num_x[1] = p1->y;
matrix_num_x[2] = 1.0;
matrix_num_x[3] = x2sq+y2sq;
matrix_num_x[4] = p2->y;
matrix_num_x[5] = 1.0;
matrix_num_x[6] = x3sq+y3sq;
matrix_num_x[7] = p3->y;
matrix_num_x[8] = 1.0;
/* Intialize matrix_num_y */
matrix_num_y[0] = p1->x;
matrix_num_y[1] = x1sq+y1sq;
matrix_num_y[2] = 1.0;
matrix_num_y[3] = p2->x;
matrix_num_y[4] = x2sq+y2sq;
matrix_num_y[5] = 1.0;
matrix_num_y[6] = p3->x;
matrix_num_y[7] = x3sq+y3sq;
matrix_num_y[8] = 1.0;
/* Intialize matrix_denom */
matrix_denom[0] = p1->x;
matrix_denom[1] = p1->y;
matrix_denom[2] = 1.0;
matrix_denom[3] = p2->x;
matrix_denom[4] = p2->y;
matrix_denom[5] = 1.0;
matrix_denom[6] = p3->x;
matrix_denom[7] = p3->y;
matrix_denom[8] = 1.0;
/* Circle is closed, so p2 must be opposite p1 & p3. */
if ( FP_EQ(p1->x,p3->x) && FP_EQ(p1->y,p3->y) ) {
c.x = (p1->x + p2->x) / 2.0;
c.y = (p1->y + p2->y) / 2.0;
r = sqrt( (p1->x - p2->x) * (p1->x - p2->x) + (p1->y - p2->y) * (p1->y - p2->y) ) / 2.0;
}
/* There is no circle here, the points are actually co-linear */
else if ( arcSegmentSide(p1, p3, p2) == FP_COLINEAR ) {
return MS_FAILURE;
}
/* Calculate the center and radius. */
else {
double denom = 2.0 * arcDeterminant3x3(matrix_denom);
/* Center components */
c.x = arcDeterminant3x3(matrix_num_x) / denom;
c.y = arcDeterminant3x3(matrix_num_y) / denom;
/* Radius */
r = sqrt((p1->x-c.x) * (p1->x-c.x) + (p1->y-c.y) * (p1->y-c.y));
}
if ( radius ) *radius = r;
if ( center ) *center = c;
return MS_SUCCESS;
}
/*
** Write a stroked version of the circle defined by three points into a
** point buffer. The segment_angle (degrees) is the coverage of each stroke segment,
** and depending on whether this is the first arc in a circularstring,
** you might want to include_first
*/
int
arcStrokeCircle(const pointObj *p1, const pointObj *p2, const pointObj *p3,
double segment_angle, int include_first, pointArrayObj *pa)
{
pointObj center; /* Center of our circular arc */
double radius; /* Radius of our circular arc */
double sweep_angle_r; /* Total angular size of our circular arc in radians */
double segment_angle_r; /* Segment angle in radians */
double a1, /*a2,*/ a3; /* Angles represented by p1, p2, p3 relative to center */
int side = arcSegmentSide(p1, p3, p2); /* What side of p1,p3 is the middle point? */
int num_edges; /* How many edges we will be generating */
double current_angle_r; /* What angle are we generating now (radians)? */
int i; /* Counter */
pointObj p; /* Temporary point */
int is_closed = MS_FALSE;
/* We need to know if we're dealing with a circle early */
if ( FP_EQ(p1->x, p3->x) && FP_EQ(p1->y, p3->y) )
is_closed = MS_TRUE;
/* Check if the "arc" is actually straight */
if ( ! is_closed && side == FP_COLINEAR ) {
/* We just need to write in the end points */
if ( include_first )
pointArrayAddPoint(pa, p1);
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/* We should always be able to find the center of a non-linear arc */
if ( arcCircleCenter(p1, p2, p3, ¢er, &radius) == MS_FAILURE )
return MS_FAILURE;
/* Calculate the angles that our three points represent */
a1 = atan2(p1->y - center.y, p1->x - center.x);
/* UNUSED
a2 = atan2(p2->y - center.y, p2->x - center.x);
*/
a3 = atan2(p3->y - center.y, p3->x - center.x);
segment_angle_r = M_PI * segment_angle / 180.0;
/* Closed-circle case, we sweep the whole circle! */
if ( is_closed ) {
sweep_angle_r = 2.0 * M_PI;
}
/* Clockwise sweep direction */
else if ( side == FP_LEFT ) {
if ( a3 > a1 ) /* Wrapping past 180? */
sweep_angle_r = a1 + (2.0 * M_PI - a3);
else
sweep_angle_r = a1 - a3;
}
/* Counter-clockwise sweep direction */
else if ( side == FP_RIGHT ) {
if ( a3 > a1 ) /* Wrapping past 180? */
sweep_angle_r = a3 - a1;
else
sweep_angle_r = a3 + (2.0 * M_PI - a1);
} else
sweep_angle_r = 0.0;
/* We don't have enough resolution, let's invert our strategy. */
if ( (sweep_angle_r / segment_angle_r) < SEGMENT_MINPOINTS ) {
segment_angle_r = sweep_angle_r / (SEGMENT_MINPOINTS + 1);
}
/* We don't have enough resolution to stroke this arc,
* so just join the start to the end. */
if ( sweep_angle_r < segment_angle_r ) {
if ( include_first )
pointArrayAddPoint(pa, p1);
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/* How many edges to generate (we add the final edge
* by sticking on the last point */
num_edges = floor(sweep_angle_r / fabs(segment_angle_r));
/* Go backwards (negative angular steps) if we are stroking clockwise */
if ( side == FP_LEFT )
segment_angle_r *= -1;
/* What point should we start with? */
if( include_first ) {
current_angle_r = a1;
} else {
current_angle_r = a1 + segment_angle_r;
num_edges--;
}
/* For each edge, increment or decrement by our segment angle */
for( i = 0; i < num_edges; i++ ) {
if (segment_angle_r > 0.0 && current_angle_r > M_PI)
current_angle_r -= 2*M_PI;
if (segment_angle_r < 0.0 && current_angle_r < -1*M_PI)
current_angle_r -= 2*M_PI;
p.x = center.x + radius*cos(current_angle_r);
p.y = center.y + radius*sin(current_angle_r);
pointArrayAddPoint(pa, &p);
current_angle_r += segment_angle_r;
}
/* Add the last point */
pointArrayAddPoint(pa, p3);
return MS_SUCCESS;
}
/*
** This function does not actually take WKB as input, it takes the
** WKB starting from the numpoints integer. Each three-point edge
** is stroked into a linestring and appended into the lineObj
** argument.
*/
int
arcStrokeCircularString(wkbObj *w, double segment_angle, lineObj *line)
{
pointObj p1, p2, p3;
int npoints, nedges;
int edge = 0;
pointArrayObj *pa;
if ( ! w || ! line ) return MS_FAILURE;
npoints = wkbReadInt(w);
nedges = npoints / 2;
/* All CircularStrings have an odd number of points */
if ( npoints < 3 || npoints % 2 != 1 )
return MS_FAILURE;
/* Make a large guess at how much space we'll need */
pa = pointArrayNew(nedges * 180 / segment_angle);
wkbReadPointP(w,&p3);
/* Fill out the point array with stroked arcs */
while( edge < nedges ) {
p1 = p3;
wkbReadPointP(w,&p2);
wkbReadPointP(w,&p3);
if ( arcStrokeCircle(&p1, &p2, &p3, segment_angle, edge ? 0 : 1, pa) == MS_FAILURE ) {
pointArrayFree(pa);
return MS_FAILURE;
}
edge++;
}
/* Copy the point array into the line */
line->numpoints = pa->npoints;
line->point = msSmallMalloc(line->numpoints * sizeof(pointObj));
memcpy(line->point, pa->data, line->numpoints * sizeof(pointObj));
/* Clean up */
pointArrayFree(pa);
return MS_SUCCESS;
}
/*
** For LAYER types that are not the usual ones (charts,
** annotations, etc) we will convert to a shape type
** that "makes sense" given the WKB input. We do this
** by peaking at the type number of the first collection
** sub-element.
*/
static int
msPostGISFindBestType(wkbObj *w, shapeObj *shape)
{
int wkbtype;
/* What kind of geometry is this? */
wkbtype = wkbType(w);
/* Generic collection, we need to look a little deeper. */
if ( wkbtype == WKB_GEOMETRYCOLLECTION )
wkbtype = wkbCollectionSubType(w);
switch ( wkbtype ) {
case WKB_POLYGON:
case WKB_CURVEPOLYGON:
case WKB_MULTIPOLYGON:
shape->type = MS_SHAPE_POLYGON;
break;
case WKB_LINESTRING:
case WKB_CIRCULARSTRING:
case WKB_COMPOUNDCURVE:
case WKB_MULTICURVE:
case WKB_MULTILINESTRING:
shape->type = MS_SHAPE_LINE;
break;
case WKB_POINT:
case WKB_MULTIPOINT:
shape->type = MS_SHAPE_POINT;
break;
default:
return MS_FAILURE;
}
return wkbConvGeometryToShape(w, shape);
}
/*
** Recent versions of PgSQL provide the version as an int in a
** simple call to the connection handle. For earlier ones we have
** to parse the version string into a usable number.
*/
static int
msPostGISRetrievePgVersion(PGconn *pgconn)
{
#ifndef POSTGIS_HAS_SERVER_VERSION
int pgVersion = 0;
char *strVersion = NULL;
char *strParts[3] = { NULL, NULL, NULL };
int i = 0, j = 0, len = 0;
int factor = 10000;
if (pgconn == NULL) {
msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePgVersion()");
return MS_FAILURE;
}
if (! PQparameterStatus(pgconn, "server_version") )
return MS_FAILURE;
strVersion = msStrdup(PQparameterStatus(pgconn, "server_version"));
if( ! strVersion )
return MS_FAILURE;
strParts[j] = strVersion;
j++;
len = strlen(strVersion);
for( i = 0; i < len; i++ ) {
if( strVersion[i] == '.' ) {
strVersion[i] = '\0';
if( j < 3 ) {
strParts[j] = strVersion + i + 1;
j++;
} else {
free(strVersion);
msSetError(MS_QUERYERR, "Too many parts in version string.", "msPostGISRetrievePgVersion()");
return MS_FAILURE;
}
}
}
for( j = 0; j < 3 && strParts[j]; j++ ) {
pgVersion += factor * atoi(strParts[j]);
factor = factor / 100;
}
free(strVersion);
return pgVersion;
#else
return PQserverVersion(pgconn);
#endif
}
/*
** Get the PostGIS version number from the database as integer.
** Versions are multiplied out as with PgSQL: 1.5.2 -> 10502, 2.0.0 -> 20000.
*/
static int
msPostGISRetrieveVersion(PGconn *pgconn)
{
static char* sql = "SELECT postgis_version()";
int version = 0;
size_t strSize;
char *strVersion = NULL;
char *ptr;
char *strParts[3] = { NULL, NULL, NULL };
int i = 0, j = 0;
int factor = 10000;
PGresult *pgresult = NULL;
if ( ! pgconn ) {
msSetError(MS_QUERYERR, "No open connection.", "msPostGISRetrieveVersion()");
return MS_FAILURE;
}
pgresult = PQexecParams(pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISRetrieveVersion()", sql);
return MS_FAILURE;
}
if (PQgetisnull(pgresult, 0, 0)) {
PQclear(pgresult);
msSetError(MS_QUERYERR,"Null result returned.","msPostGISRetrieveVersion()");
return MS_FAILURE;
}
strSize = PQgetlength(pgresult, 0, 0) + 1;
strVersion = (char*)msSmallMalloc(strSize);
strlcpy(strVersion, PQgetvalue(pgresult, 0, 0), strSize);
PQclear(pgresult);
ptr = strVersion;
strParts[j++] = strVersion;
while( ptr != '\0' && j < 3 ) {
if ( *ptr == '.' ) {
*ptr = '\0';
strParts[j++] = ptr + 1;
}
if ( *ptr == ' ' ) {
*ptr = '\0';
break;
}
ptr++;
}
for( i = 0; i < j; i++ ) {
version += factor * atoi(strParts[i]);
factor = factor / 100;
}
free(strVersion);
return version;
}
/*
** msPostGISRetrievePK()
**
** Find out that the primary key is for this layer.
** The layerinfo->fromsource must already be populated and
** must not be a subquery.
*/
static int
msPostGISRetrievePK(layerObj *layer)
{
PGresult *pgresult = NULL;
char *sql = 0;
size_t size;
msPostGISLayerInfo *layerinfo = 0;
int length;
int pgVersion;
char *pos_sep;
char *schema = NULL;
char *table = NULL;
if (layer->debug) {
msDebug("msPostGISRetrievePK called.\n");
}
layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
/* Attempt to separate fromsource into schema.table */
pos_sep = strstr(layerinfo->fromsource, ".");
if (pos_sep) {
length = strlen(layerinfo->fromsource) - strlen(pos_sep) + 1;
schema = (char*)msSmallMalloc(length);
strlcpy(schema, layerinfo->fromsource, length);
length = strlen(pos_sep);
table = (char*)msSmallMalloc(length);
strlcpy(table, pos_sep + 1, length);
if (layer->debug) {
msDebug("msPostGISRetrievePK(): Found schema %s, table %s.\n", schema, table);
}
}
if (layerinfo->pgconn == NULL) {
msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
return MS_FAILURE;
}
pgVersion = msPostGISRetrievePgVersion(layerinfo->pgconn);
if (pgVersion < 70000) {
if (layer->debug) {
msDebug("msPostGISRetrievePK(): Major version below 7.\n");
}
return MS_FAILURE;
}
if (pgVersion < 70200) {
if (layer->debug) {
msDebug("msPostGISRetrievePK(): Version below 7.2.\n");
}
return MS_FAILURE;
}
if (pgVersion < 70300) {
/*
** PostgreSQL v7.2 has a different representation of primary keys that
** later versions. This currently does not explicitly exclude
** multicolumn primary keys.
*/
static char *v72sql = "select b.attname from pg_class as a, pg_attribute as b, (select oid from pg_class where relname = '%s') as c, pg_index as d where d.indexrelid = a.oid and d.indrelid = c.oid and d.indisprimary and b.attrelid = a.oid and a.relnatts = 1";
sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v72sql));
sprintf(sql, v72sql, layerinfo->fromsource);
} else {
/*
** PostgreSQL v7.3 and later treat primary keys as constraints.
** We only support single column primary keys, so multicolumn
** pks are explicitly excluded from the query.
*/
if (schema && table) {
static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class, pg_namespace where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_class.relnamespace = pg_namespace.oid and pg_namespace.nspname = '%s' and pg_constraint.conkey[2] is null";
sql = msSmallMalloc(strlen(schema) + strlen(table) + strlen(v73sql));
sprintf(sql, v73sql, table, schema);
free(table);
free(schema);
} else {
static char *v73sql = "select attname from pg_attribute, pg_constraint, pg_class where pg_constraint.conrelid = pg_class.oid and pg_class.oid = pg_attribute.attrelid and pg_constraint.contype = 'p' and pg_constraint.conkey[1] = pg_attribute.attnum and pg_class.relname = '%s' and pg_table_is_visible(pg_class.oid) and pg_constraint.conkey[2] is null";
sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v73sql));
sprintf(sql, v73sql, layerinfo->fromsource);
}
}
if (layer->debug > 1) {
msDebug("msPostGISRetrievePK: %s\n", sql);
}
layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
if (layerinfo->pgconn == NULL) {
msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
free(sql);
return MS_FAILURE;
}
pgresult = PQexecParams(layerinfo->pgconn, sql, 0, NULL, NULL, NULL, NULL, 0);
if ( !pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
static char *tmp1 = "Error executing SQL: ";
char *tmp2 = NULL;
size_t size2;
size2 = sizeof(char)*(strlen(tmp1) + strlen(sql) + 1);
tmp2 = (char*)msSmallMalloc(size2);
strlcpy(tmp2, tmp1, size2);
strlcat(tmp2, sql, size2);
msSetError(MS_QUERYERR, tmp2, "msPostGISRetrievePK()");
free(tmp2);
free(sql);
return MS_FAILURE;
}
if (PQntuples(pgresult) < 1) {
if (layer->debug) {
msDebug("msPostGISRetrievePK: No results found.\n");
}
PQclear(pgresult);
free(sql);
return MS_FAILURE;
}
if (PQntuples(pgresult) > 1) {
if (layer->debug) {
msDebug("msPostGISRetrievePK: Multiple results found.\n");
}
PQclear(pgresult);
free(sql);
return MS_FAILURE;
}
if (PQgetisnull(pgresult, 0, 0)) {
if (layer->debug) {
msDebug("msPostGISRetrievePK: Null result returned.\n");
}
PQclear(pgresult);
free(sql);
return MS_FAILURE;
}
size = PQgetlength(pgresult, 0, 0) + 1;
layerinfo->uid = (char*)msSmallMalloc(size);
strlcpy(layerinfo->uid, PQgetvalue(pgresult, 0, 0), size);
PQclear(pgresult);
free(sql);
return MS_SUCCESS;
}
/*
** msPostGISParseData()
**
** Parse the DATA string for geometry column name, table name,
** unique id column, srid, and SQL string.
*/
int msPostGISParseData(layerObj *layer)
{
char *pos_opt, *pos_scn, *tmp, *pos_srid, *pos_uid, *pos_geom, *data;
int slength;
msPostGISLayerInfo *layerinfo;
assert(layer != NULL);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*)(layer->layerinfo);
if (layer->debug) {
msDebug("msPostGISParseData called.\n");
}
if (!layer->data) {
msSetError(MS_QUERYERR, "Missing DATA clause. DATA statement must contain 'geometry_column from table_name' or 'geometry_column from (sub-query) as sub'.", "msPostGISParseData()");
return MS_FAILURE;
}
data = layer->data;
/*
** Clean up any existing strings first, as we will be populating these fields.
*/
if( layerinfo->srid ) {
free(layerinfo->srid);
layerinfo->srid = NULL;
}
if( layerinfo->uid ) {
free(layerinfo->uid);
layerinfo->uid = NULL;
}
if( layerinfo->geomcolumn ) {
free(layerinfo->geomcolumn);
layerinfo->geomcolumn = NULL;
}
if( layerinfo->fromsource ) {
free(layerinfo->fromsource);
layerinfo->fromsource = NULL;
}
/*
** Look for the optional ' using unique ID' string first.
*/
pos_uid = strcasestr(data, " using unique ");
if (pos_uid) {
/* Find the end of this case 'using unique ftab_id using srid=33' */
tmp = strstr(pos_uid + 14, " ");
/* Find the end of this case 'using srid=33 using unique ftab_id' */
if (!tmp) {
tmp = pos_uid + strlen(pos_uid);
}
layerinfo->uid = (char*) msSmallMalloc((tmp - (pos_uid + 14)) + 1);
strlcpy(layerinfo->uid, pos_uid + 14, tmp - (pos_uid + 14)+1);
msStringTrim(layerinfo->uid);
}
/*
** Look for the optional ' using srid=333 ' string next.
*/
pos_srid = strcasestr(data, " using srid=");
if (!pos_srid) {
layerinfo->srid = (char*) msSmallMalloc(1);
(layerinfo->srid)[0] = '\0'; /* no SRID, so return just null terminator*/
} else {
slength = strspn(pos_srid + 12, "-0123456789");
if (!slength) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. You specified 'USING SRID' but didnt have any numbers! %s", "msPostGISParseData()", data);
return MS_FAILURE;
} else {
layerinfo->srid = (char*) msSmallMalloc(slength + 1);
strlcpy(layerinfo->srid, pos_srid + 12, slength+1);
msStringTrim(layerinfo->srid);
}
}
/*
** This is a little hack so the rest of the code works.
** pos_opt should point to the start of the optional blocks.
**
** If they are both set, return the smaller one.
*/
if (pos_srid && pos_uid) {
pos_opt = (pos_srid > pos_uid) ? pos_uid : pos_srid;
}
/* If one or none is set, return the larger one. */
else {
pos_opt = (pos_srid > pos_uid) ? pos_srid : pos_uid;
}
/* No pos_opt? Move it to the end of the string. */
if (!pos_opt) {
pos_opt = data + strlen(data);
}
/*
** Scan for the 'geometry from table' or 'geometry from () as foo' clause.
*/
/* Find the first non-white character to start from */
pos_geom = data;
while( *pos_geom == ' ' || *pos_geom == '\t' || *pos_geom == '\n' || *pos_geom == '\r' )
pos_geom++;
/* Find the end of the geom column name */
pos_scn = strcasestr(data, " from ");
if (!pos_scn) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
return MS_FAILURE;
}
/* Copy the geometry column name */
layerinfo->geomcolumn = (char*) msSmallMalloc((pos_scn - pos_geom) + 1);
strlcpy(layerinfo->geomcolumn, pos_geom, pos_scn - pos_geom+1);
msStringTrim(layerinfo->geomcolumn);
/* Copy the table name or sub-select clause */
layerinfo->fromsource = (char*) msSmallMalloc((pos_opt - (pos_scn + 6)) + 1);
strlcpy(layerinfo->fromsource, pos_scn + 6, pos_opt - (pos_scn + 6)+1);
msStringTrim(layerinfo->fromsource);
/* Something is wrong, our goemetry column and table references are not there. */
if (strlen(layerinfo->fromsource) < 1 || strlen(layerinfo->geomcolumn) < 1) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. Must contain 'geometry from table' or 'geometry from (subselect) as foo'. %s", "msPostGISParseData()", data);
return MS_FAILURE;
}
/*
** We didn't find a ' using unique ' in the DATA string so try and find a
** primary key on the table.
*/
if ( ! (layerinfo->uid) ) {
if ( strstr(layerinfo->fromsource, " ") ) {
msSetError(MS_QUERYERR, "Error parsing PostGIS DATA variable. You must specify 'using unique' when supplying a subselect in the data definition.", "msPostGISParseData()");
return MS_FAILURE;
}
if ( msPostGISRetrievePK(layer) != MS_SUCCESS ) {
/* No user specified unique id so we will use the PostgreSQL oid */
/* TODO: Deprecate this, oids are deprecated in PostgreSQL */
layerinfo->uid = msStrdup("oid");
}
}
if (layer->debug) {
msDebug("msPostGISParseData: unique_column=%s, srid=%s, geom_column_name=%s, table_name=%s\n", layerinfo->uid, layerinfo->srid, layerinfo->geomcolumn, layerinfo->fromsource);
}
return MS_SUCCESS;
}
/*
** Decode a hex character.
*/
static unsigned char msPostGISHexDecodeChar[256] = {
/* not Hex characters */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
/* 0-9 */
0,1,2,3,4,5,6,7,8,9,
/* not Hex characters */
64,64,64,64,64,64,64,
/* A-F */
10,11,12,13,14,15,
/* not Hex characters */
64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,
/* a-f */
10,11,12,13,14,15,
64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
/* not Hex characters (upper 128 characters) */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
};
/*
** Decode hex string "src" (null terminated)
** into "dest" (not null terminated).
** Returns length of decoded array or 0 on failure.
*/
int msPostGISHexDecode(unsigned char *dest, const char *src, int srclen)
{
if (src && *src && (srclen % 2 == 0) ) {
unsigned char *p = dest;
int i;
for ( i=0; i<srclen; i+=2 ) {
register unsigned char b1=0, b2=0;
register unsigned char c1 = src[i];
register unsigned char c2 = src[i + 1];
b1 = msPostGISHexDecodeChar[c1];
b2 = msPostGISHexDecodeChar[c2];
*p++ = (b1 << 4) | b2;
}
return(p-dest);
}
return 0;
}
/*
** Decode a base64 character.
*/
static unsigned char msPostGISBase64DecodeChar[256] = {
/* not Base64 characters */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,
/* + */
62,
/* not Base64 characters */
64,64,64,
/* / */
63,
/* 0-9 */
52,53,54,55,56,57,58,59,60,61,
/* not Base64 characters */
64,64,64,64,64,64,64,
/* A-Z */
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,
/* not Base64 characters */
64,64,64,64,64,64,
/* a-z */
26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,
/* not Base64 characters */
64,64,64,64,64,
/* not Base64 characters (upper 128 characters) */
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,
64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64
};
/*
** Decode base64 string "src" (null terminated)
** into "dest" (not null terminated).
** Returns length of decoded array or 0 on failure.
*/
int msPostGISBase64Decode(unsigned char *dest, const char *src, int srclen)
{
if (src && *src) {
unsigned char *p = dest;
int i, j, k;
unsigned char *buf = calloc(srclen + 1, sizeof(unsigned char));
/* Drop illegal chars first */
for (i=0, j=0; src[i]; i++) {
unsigned char c = src[i];
if ( (msPostGISBase64DecodeChar[c] != 64) || (c == '=') ) {
buf[j++] = c;
}
}
for (k=0; k<j; k+=4) {
register unsigned char c1='A', c2='A', c3='A', c4='A';
register unsigned char b1=0, b2=0, b3=0, b4=0;
c1 = buf[k];
if (k+1<j) {
c2 = buf[k+1];
}
if (k+2<j) {
c3 = buf[k+2];
}
if (k+3<j) {
c4 = buf[k+3];
}
b1 = msPostGISBase64DecodeChar[c1];
b2 = msPostGISBase64DecodeChar[c2];
b3 = msPostGISBase64DecodeChar[c3];
b4 = msPostGISBase64DecodeChar[c4];
*p++=((b1<<2)|(b2>>4) );
if (c3 != '=') {
*p++=(((b2&0xf)<<4)|(b3>>2) );
}
if (c4 != '=') {
*p++=(((b3&0x3)<<6)|b4 );
}
}
free(buf);
return(p-dest);
}
return 0;
}
/*
** msPostGISBuildSQLBox()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLBox(layerObj *layer, rectObj *rect, char *strSRID)
{
char *strBox = NULL;
size_t sz;
if (layer->debug) {
msDebug("msPostGISBuildSQLBox called.\n");
}
if ( strSRID ) {
static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%s)";
/* 10 doubles + 1 integer + template characters */
sz = 10 * 22 + strlen(strSRID) + strlen(strBoxTemplate);
strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
if ( sz <= snprintf(strBox, sz, strBoxTemplate,
rect->minx, rect->miny,
rect->minx, rect->maxy,
rect->maxx, rect->maxy,
rect->maxx, rect->miny,
rect->minx, rect->miny,
strSRID)) {
msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
return NULL;
}
} else {
static char *strBoxTemplate = "ST_GeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))')";
/* 10 doubles + template characters */
sz = 10 * 22 + strlen(strBoxTemplate);
strBox = (char*)msSmallMalloc(sz+1); /* add space for terminating NULL */
if ( sz <= snprintf(strBox, sz, strBoxTemplate,
rect->minx, rect->miny,
rect->minx, rect->maxy,
rect->maxx, rect->maxy,
rect->maxx, rect->miny,
rect->minx, rect->miny) ) {
msSetError(MS_MISCERR,"Bounding box digits truncated.","msPostGISBuildSQLBox");
return NULL;
}
}
return strBox;
}
/*
** msPostGISBuildSQLItems()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLItems(layerObj *layer)
{
char *strEndian = NULL;
char *strGeom = NULL;
char *strItems = NULL;
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISBuildSQLItems called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
if ( ! layerinfo->geomcolumn ) {
msSetError(MS_MISCERR, "layerinfo->geomcolumn is not initialized.", "msPostGISBuildSQLItems()");
return NULL;
}
/*
** Get the server to transform the geometry into our
** native endian before transmitting it to us..
*/
if (layerinfo->endian == LITTLE_ENDIAN) {
strEndian = "NDR";
} else {
strEndian = "XDR";
}
{
/*
** We transfer the geometry from server to client as a
** hex or base64 encoded WKB byte-array. We will have to decode this
** data once we get it. Forcing to 2D (via the AsBinary function
** which includes a 2D force in it) removes ordinates we don't
** need, saving transfer and encode/decode time.
*/
#if TRANSFER_ENCODING == 64
static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'base64') as geom,\"%s\"";
#else
static char *strGeomTemplate = "encode(ST_AsBinary(ST_Force_2D(\"%s\"),'%s'),'hex') as geom,\"%s\"";
#endif
strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid));
sprintf(strGeom, strGeomTemplate, layerinfo->geomcolumn, strEndian, layerinfo->uid);
}
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLItems: %d items requested.\n",layer->numitems);
}
/*
** Not requesting items? We just need geometry and unique id.
*/
if (layer->numitems == 0) {
strItems = msStrdup(strGeom);
}
/*
** Build SQL to pull all the items.
*/
else {
int length = strlen(strGeom) + 2;
int t;
for ( t = 0; t < layer->numitems; t++ ) {
length += strlen(layer->items[t]) + 3; /* itemname + "", */
}
strItems = (char*)msSmallMalloc(length);
strItems[0] = '\0';
for ( t = 0; t < layer->numitems; t++ ) {
strlcat(strItems, "\"", length);
strlcat(strItems, layer->items[t], length);
strlcat(strItems, "\",", length);
}
strlcat(strItems, strGeom, length);
}
free(strGeom);
return strItems;
}
/*
** msPostGISBuildSQLSRID()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLSRID(layerObj *layer)
{
char *strSRID = NULL;
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISBuildSQLSRID called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
/* An SRID was already provided in the DATA line. */
if ( layerinfo->srid && (strlen(layerinfo->srid) > 0) ) {
strSRID = msStrdup(layerinfo->srid);
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLSRID: SRID provided (%s)\n", strSRID);
}
}
/*
** No SRID in data line, so extract target table from the 'fromsource'.
** Either of form "thetable" (one word) or "(select ... from thetable)"
** or "(select ... from thetable where ...)".
*/
else {
char *f_table_name;
char *strSRIDTemplate = "find_srid('','%s','%s')";
char *pos = strstr(layerinfo->fromsource, " ");
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLSRID: Building find_srid line.\n", strSRID);
}
if ( ! pos ) {
/* target table is one word */
f_table_name = msStrdup(layerinfo->fromsource);
if( layer->debug > 1 ) {
msDebug("msPostGISBuildSQLSRID: Found table (%s)\n", f_table_name);
}
} else {
/* target table is hiding in sub-select clause */
pos = strcasestr(layerinfo->fromsource, " from ");
if ( pos ) {
char *pos_paren;
char *pos_space;
pos += 6; /* should be start of table name */
pos_paren = strstr(pos, ")"); /* first ) after table name */
pos_space = strstr(pos, " "); /* first space after table name */
if ( pos_space < pos_paren ) {
/* found space first */
f_table_name = (char*)msSmallMalloc(pos_space - pos + 1);
strlcpy(f_table_name, pos, pos_space - pos+1);
} else {
/* found ) first */
f_table_name = (char*)msSmallMalloc(pos_paren - pos + 1);
strlcpy(f_table_name, pos, pos_paren - pos+1);
}
} else {
/* should not happen */
return NULL;
}
}
strSRID = msSmallMalloc(strlen(strSRIDTemplate) + strlen(f_table_name) + strlen(layerinfo->geomcolumn));
sprintf(strSRID, strSRIDTemplate, f_table_name, layerinfo->geomcolumn);
if ( f_table_name ) free(f_table_name);
}
return strSRID;
}
/*
** msPostGISReplaceBoxToken()
**
** Convert a fromsource data statement into something usable by replacing the !BOX! token.
**
** Returns malloc'ed char* that must be freed by caller.
*/
static char *msPostGISReplaceBoxToken(layerObj *layer, rectObj *rect, const char *fromsource)
{
char *result = NULL;
if ( strstr(fromsource, BOXTOKEN) && rect ) {
char *strBox = NULL;
char *strSRID = NULL;
/* We see to set the SRID on the box, but to what SRID? */
strSRID = msPostGISBuildSQLSRID(layer);
if ( ! strSRID ) {
return NULL;
}
/* Create a suitable SQL string from the rectangle and SRID. */
strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
if ( ! strBox ) {
msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISReplaceBoxToken()");
if (strSRID) free(strSRID);
return NULL;
}
/* Do the substitution. */
while ( strstr(fromsource, BOXTOKEN) ) {
char *start, *end;
char *oldresult = result;
size_t buffer_size = 0;
start = strstr(fromsource, BOXTOKEN);
end = start + BOXTOKENLENGTH;
buffer_size = (start - fromsource) + strlen(strBox) + strlen(end) +1;
result = (char*)msSmallMalloc(buffer_size);
strlcpy(result, fromsource, start - fromsource +1);
strlcpy(result + (start - fromsource), strBox, buffer_size-(start - fromsource));
strlcat(result, end, buffer_size);
fromsource = result;
if (oldresult != NULL)
free(oldresult);
}
if (strSRID) free(strSRID);
if (strBox) free(strBox);
} else {
result = msStrdup(fromsource);
}
return result;
}
/*
** msPostGISBuildSQLFrom()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLFrom(layerObj *layer, rectObj *rect)
{
char *strFrom = 0;
msPostGISLayerInfo *layerinfo;
if (layer->debug) {
msDebug("msPostGISBuildSQLFrom called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
if ( ! layerinfo->fromsource ) {
msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLFrom()");
return NULL;
}
/*
** If there's a '!BOX!' in our source we need to substitute the
** current rectangle for it...
*/
strFrom = msPostGISReplaceBoxToken(layer, rect, layerinfo->fromsource);
return strFrom;
}
/*
** msPostGISBuildSQLWhere()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid)
{
char *strRect = 0;
char *strFilter = 0;
char *strUid = 0;
char *strWhere = 0;
char *strLimit = 0;
char *strOffset = 0;
size_t strRectLength = 0;
size_t strFilterLength = 0;
size_t strUidLength = 0;
size_t strLimitLength = 0;
size_t strOffsetLength = 0;
size_t bufferSize = 0;
int insert_and = 0;
msPostGISLayerInfo *layerinfo;
if (layer->debug) {
msDebug("msPostGISBuildSQLWhere called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
if ( ! layerinfo->fromsource ) {
msSetError(MS_MISCERR, "Layerinfo->fromsource is not initialized.", "msPostGISBuildSQLWhere()");
return NULL;
}
/* Populate strLimit, if necessary. */
if ( layerinfo->paging && layer->maxfeatures >= 0 ) {
static char *strLimitTemplate = " limit %d";
strLimit = msSmallMalloc(strlen(strLimitTemplate) + 12);
sprintf(strLimit, strLimitTemplate, layer->maxfeatures);
strLimitLength = strlen(strLimit);
}
/* Populate strOffset, if necessary. */
if ( layerinfo->paging && layer->startindex > 0 ) {
static char *strOffsetTemplate = " offset %d";
strOffset = msSmallMalloc(strlen(strOffsetTemplate) + 12);
sprintf(strOffset, strOffsetTemplate, layer->startindex-1);
strOffsetLength = strlen(strOffset);
}
/* Populate strRect, if necessary. */
if ( rect && layerinfo->geomcolumn ) {
char *strBox = 0;
char *strSRID = 0;
size_t strBoxLength = 0;
static char *strRectTemplate = "%s && %s";
/* We see to set the SRID on the box, but to what SRID? */
strSRID = msPostGISBuildSQLSRID(layer);
if ( ! strSRID ) {
return NULL;
}
strBox = msPostGISBuildSQLBox(layer, rect, strSRID);
if ( strBox ) {
strBoxLength = strlen(strBox);
} else {
msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISBuildSQLWhere()");
return NULL;
}
strRect = (char*)msSmallMalloc(strlen(strRectTemplate) + strBoxLength + strlen(layerinfo->geomcolumn));
sprintf(strRect, strRectTemplate, layerinfo->geomcolumn, strBox);
strRectLength = strlen(strRect);
if (strBox) free(strBox);
if (strSRID) free(strSRID);
}
/* Populate strFilter, if necessary. */
if ( layer->filter.string ) {
static char *strFilterTemplate = "(%s)";
strFilter = (char*)msSmallMalloc(strlen(strFilterTemplate) + strlen(layer->filter.string));
sprintf(strFilter, strFilterTemplate, layer->filter.string);
strFilterLength = strlen(strFilter);
}
/* Populate strUid, if necessary. */
if ( uid ) {
static char *strUidTemplate = "\"%s\" = %ld";
strUid = (char*)msSmallMalloc(strlen(strUidTemplate) + strlen(layerinfo->uid) + 64);
sprintf(strUid, strUidTemplate, layerinfo->uid, *uid);
strUidLength = strlen(strUid);
}
bufferSize = strRectLength + 5 + strFilterLength + 5 + strUidLength
+ strLimitLength + strOffsetLength;
strWhere = (char*)msSmallMalloc(bufferSize);
*strWhere = '\0';
if ( strRect ) {
strlcat(strWhere, strRect, bufferSize);
insert_and++;
free(strRect);
}
if ( strFilter ) {
if ( insert_and ) {
strlcat(strWhere, " and ", bufferSize);
}
strlcat(strWhere, strFilter, bufferSize);
free(strFilter);
insert_and++;
}
if ( strUid ) {
if ( insert_and ) {
strlcat(strWhere, " and ", bufferSize);
}
strlcat(strWhere, strUid, bufferSize);
free(strUid);
insert_and++;
}
if ( strLimit ) {
strlcat(strWhere, strLimit, bufferSize);
free(strLimit);
}
if ( strOffset ) {
strlcat(strWhere, strOffset, bufferSize);
free(strOffset);
}
return strWhere;
}
/*
** msPostGISBuildSQL()
**
** Returns malloc'ed char* that must be freed by caller.
*/
char *msPostGISBuildSQL(layerObj *layer, rectObj *rect, long *uid)
{
msPostGISLayerInfo *layerinfo = 0;
char *strFrom = 0;
char *strItems = 0;
char *strWhere = 0;
char *strSQL = 0;
static char *strSQLTemplate0 = "select %s from %s where %s";
static char *strSQLTemplate1 = "select %s from %s%s";
char *strSQLTemplate = 0;
if (layer->debug) {
msDebug("msPostGISBuildSQL called.\n");
}
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
strItems = msPostGISBuildSQLItems(layer);
if ( ! strItems ) {
msSetError(MS_MISCERR, "Failed to build SQL items.", "msPostGISBuildSQL()");
return NULL;
}
strFrom = msPostGISBuildSQLFrom(layer, rect);
if ( ! strFrom ) {
msSetError(MS_MISCERR, "Failed to build SQL 'from'.", "msPostGISBuildSQL()");
return NULL;
}
/* If there's BOX hackery going on, we don't want to append a box index test at
the end of the query, the user is going to be responsible for making things
work with their hackery. */
if ( strstr(layerinfo->fromsource, BOXTOKEN) )
strWhere = msPostGISBuildSQLWhere(layer, NULL, uid);
else
strWhere = msPostGISBuildSQLWhere(layer, rect, uid);
if ( ! strWhere ) {
msSetError(MS_MISCERR, "Failed to build SQL 'where'.", "msPostGISBuildSQL()");
return NULL;
}
strSQLTemplate = strlen(strWhere) ? strSQLTemplate0 : strSQLTemplate1;
strSQL = msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom) + strlen(strItems) + strlen(strWhere));
sprintf(strSQL, strSQLTemplate, strItems, strFrom, strWhere);
if (strItems) free(strItems);
if (strFrom) free(strFrom);
if (strWhere) free(strWhere);
return strSQL;
}
#define wkbstaticsize 4096
int msPostGISReadShape(layerObj *layer, shapeObj *shape)
{
char *wkbstr = NULL;
unsigned char wkbstatic[wkbstaticsize];
unsigned char *wkb = NULL;
wkbObj w;
msPostGISLayerInfo *layerinfo = NULL;
int result = 0;
int wkbstrlen = 0;
if (layer->debug) {
msDebug("msPostGISReadShape called.\n");
}
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Retrieve the geometry. */
wkbstr = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, layer->numitems );
wkbstrlen = PQgetlength(layerinfo->pgresult, layerinfo->rownum, layer->numitems);
if ( ! wkbstr ) {
msSetError(MS_QUERYERR, "Base64 WKB returned is null!", "msPostGISReadShape()");
return MS_FAILURE;
}
if(wkbstrlen > wkbstaticsize) {
wkb = calloc(wkbstrlen, sizeof(char));
} else {
wkb = wkbstatic;
}
#if TRANSFER_ENCODING == 64
result = msPostGISBase64Decode(wkb, wkbstr, wkbstrlen - 1);
#else
result = msPostGISHexDecode(wkb, wkbstr, wkbstrlen);
#endif
if( ! result ) {
if(wkb!=wkbstatic) free(wkb);
return MS_FAILURE;
}
/* Initialize our wkbObj */
w.wkb = (char*)wkb;
w.ptr = w.wkb;
w.size = (wkbstrlen - 1)/2;
/* Set the type map according to what version of PostGIS we are dealing with */
if( layerinfo->version >= 20000 ) /* PostGIS 2.0+ */
w.typemap = wkb_postgis20;
else
w.typemap = wkb_postgis15;
switch (layer->type) {
case MS_LAYER_POINT:
shape->type = MS_SHAPE_POINT;
result = wkbConvGeometryToShape(&w, shape);
break;
case MS_LAYER_LINE:
shape->type = MS_SHAPE_LINE;
result = wkbConvGeometryToShape(&w, shape);
break;
case MS_LAYER_POLYGON:
shape->type = MS_SHAPE_POLYGON;
result = wkbConvGeometryToShape(&w, shape);
break;
case MS_LAYER_ANNOTATION:
case MS_LAYER_QUERY:
case MS_LAYER_CHART:
result = msPostGISFindBestType(&w, shape);
break;
case MS_LAYER_RASTER:
msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
break;
case MS_LAYER_CIRCLE:
msDebug("Ignoring MS_LAYER_RASTER in msPostGISReadShape.\n");
break;
default:
msDebug("Unsupported layer type in msPostGISReadShape()!\n");
break;
}
/* All done with WKB geometry, free it! */
if(wkb!=wkbstatic) free(wkb);
if (result != MS_FAILURE) {
int t;
long uid;
char *tmp;
/* Found a drawable shape, so now retreive the attributes. */
shape->values = (char**) msSmallMalloc(sizeof(char*) * layer->numitems);
for ( t = 0; t < layer->numitems; t++) {
int size = PQgetlength(layerinfo->pgresult, layerinfo->rownum, t);
char *val = (char*)PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t);
int isnull = PQgetisnull(layerinfo->pgresult, layerinfo->rownum, t);
if ( isnull ) {
shape->values[t] = msStrdup("");
} else {
shape->values[t] = (char*) msSmallMalloc(size + 1);
memcpy(shape->values[t], val, size);
shape->values[t][size] = '\0'; /* null terminate it */
msStringTrimBlanks(shape->values[t]);
}
if( layer->debug > 4 ) {
msDebug("msPostGISReadShape: PQgetlength = %d\n", size);
}
if( layer->debug > 1 ) {
msDebug("msPostGISReadShape: [%s] \"%s\"\n", layer->items[t], shape->values[t]);
}
}
/* t is the geometry, t+1 is the uid */
tmp = PQgetvalue(layerinfo->pgresult, layerinfo->rownum, t + 1);
if( tmp ) {
uid = strtol( tmp, NULL, 10 );
} else {
uid = 0;
}
if( layer->debug > 4 ) {
msDebug("msPostGISReadShape: Setting shape->index = %d\n", uid);
msDebug("msPostGISReadShape: Setting shape->resultindex = %d\n", layerinfo->rownum);
}
shape->index = uid;
shape->resultindex = layerinfo->rownum;
if( layer->debug > 2 ) {
msDebug("msPostGISReadShape: [index] %d\n", shape->index);
}
shape->numvalues = layer->numitems;
msComputeBounds(shape);
}
if( layer->debug > 2 ) {
char *tmp = msShapeToWKT(shape);
msDebug("msPostGISReadShape: [shape] %s\n", tmp);
free(tmp);
}
return MS_SUCCESS;
}
#endif /* USE_POSTGIS */
/*
** msPostGISLayerOpen()
**
** Registered vtable->LayerOpen function.
*/
int msPostGISLayerOpen(layerObj *layer)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo;
int order_test = 1;
assert(layer != NULL);
if (layer->debug) {
msDebug("msPostGISLayerOpen called: %s\n", layer->data);
}
if (layer->layerinfo) {
if (layer->debug) {
msDebug("msPostGISLayerOpen: Layer is already open!\n");
}
return MS_SUCCESS; /* already open */
}
if (!layer->data) {
msSetError(MS_QUERYERR, "Nothing specified in DATA statement.", "msPostGISLayerOpen()");
return MS_FAILURE;
}
/*
** Initialize the layerinfo
**/
layerinfo = msPostGISCreateLayerInfo();
if (((char*) &order_test)[0] == 1) {
layerinfo->endian = LITTLE_ENDIAN;
} else {
layerinfo->endian = BIG_ENDIAN;
}
/*
** Get a database connection from the pool.
*/
layerinfo->pgconn = (PGconn *) msConnPoolRequest(layer);
/* No connection in the pool, so set one up. */
if (!layerinfo->pgconn) {
char *conn_decrypted;
if (layer->debug) {
msDebug("msPostGISLayerOpen: No connection in pool, creating a fresh one.\n");
}
if (!layer->connection) {
msSetError(MS_MISCERR, "Missing CONNECTION keyword.", "msPostGISLayerOpen()");
return MS_FAILURE;
}
/*
** Decrypt any encrypted token in connection string and attempt to connect.
*/
conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
if (conn_decrypted == NULL) {
return MS_FAILURE; /* An error should already have been produced */
}
layerinfo->pgconn = PQconnectdb(conn_decrypted);
msFree(conn_decrypted);
conn_decrypted = NULL;
/*
** Connection failed, return error message with passwords ***ed out.
*/
if (!layerinfo->pgconn || PQstatus(layerinfo->pgconn) == CONNECTION_BAD) {
char *index, *maskeddata;
if (layer->debug)
msDebug("msPostGISLayerOpen: Connection failure.\n");
maskeddata = msStrdup(layer->connection);
index = strstr(maskeddata, "password=");
if (index != NULL) {
index = (char*)(index + 9);
while (*index != '\0' && *index != ' ') {
*index = '*';
index++;
}
}
msSetError(MS_QUERYERR, "Database connection failed (%s) with connect string '%s'\nIs the database running? Is it allowing connections? Does the specified user exist? Is the password valid? Is the database on the standard port?", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn), maskeddata);
free(maskeddata);
free(layerinfo);
return MS_FAILURE;
}
/* Register to receive notifications from the database. */
PQsetNoticeProcessor(layerinfo->pgconn, postresqlNoticeHandler, (void *) layer);
/* Save this connection in the pool for later. */
msConnPoolRegister(layer, layerinfo->pgconn, msPostGISCloseConnection);
} else {
/* Connection in the pool should be tested to see if backend is alive. */
if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
/* Uh oh, bad connection. Can we reset it? */
PQreset(layerinfo->pgconn);
if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
/* Nope, time to bail out. */
msSetError(MS_QUERYERR, "PostgreSQL database connection gone bad (%s)", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn));
return MS_FAILURE;
}
}
}
/* Get the PostGIS version number from the database */
layerinfo->version = msPostGISRetrieveVersion(layerinfo->pgconn);
if( layerinfo->version == MS_FAILURE ) return MS_FAILURE;
if (layer->debug)
msDebug("msPostGISLayerOpen: Got PostGIS version %d.\n", layerinfo->version);
/* Save the layerinfo in the layerObj. */
layer->layerinfo = (void*)layerinfo;
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerOpen()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerClose()
**
** Registered vtable->LayerClose function.
*/
int msPostGISLayerClose(layerObj *layer)
{
#ifdef USE_POSTGIS
if (layer->debug) {
msDebug("msPostGISLayerClose called: %s\n", layer->data);
}
if( layer->layerinfo ) {
msPostGISFreeLayerInfo(layer);
}
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerClose()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerIsOpen()
**
** Registered vtable->LayerIsOpen function.
*/
int msPostGISLayerIsOpen(layerObj *layer)
{
#ifdef USE_POSTGIS
if (layer->debug) {
msDebug("msPostGISLayerIsOpen called.\n");
}
if (layer->layerinfo)
return MS_TRUE;
else
return MS_FALSE;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerIsOpen()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerFreeItemInfo()
**
** Registered vtable->LayerFreeItemInfo function.
*/
void msPostGISLayerFreeItemInfo(layerObj *layer)
{
#ifdef USE_POSTGIS
if (layer->debug) {
msDebug("msPostGISLayerFreeItemInfo called.\n");
}
if (layer->iteminfo) {
free(layer->iteminfo);
}
layer->iteminfo = NULL;
#endif
}
/*
** msPostGISLayerInitItemInfo()
**
** Registered vtable->LayerInitItemInfo function.
** Our iteminfo is list of indexes from 1..numitems.
*/
int msPostGISLayerInitItemInfo(layerObj *layer)
{
#ifdef USE_POSTGIS
int i;
int *itemindexes ;
if (layer->debug) {
msDebug("msPostGISLayerInitItemInfo called.\n");
}
if (layer->numitems == 0) {
return MS_SUCCESS;
}
if (layer->iteminfo) {
free(layer->iteminfo);
}
layer->iteminfo = msSmallMalloc(sizeof(int) * layer->numitems);
if (!layer->iteminfo) {
msSetError(MS_MEMERR, "Out of memory.", "msPostGISLayerInitItemInfo()");
return MS_FAILURE;
}
itemindexes = (int*)layer->iteminfo;
for (i = 0; i < layer->numitems; i++) {
itemindexes[i] = i; /* Last item is always the geometry. The rest are non-geometry. */
}
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerInitItemInfo()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerWhichShapes()
**
** Registered vtable->LayerWhichShapes function.
*/
int msPostGISLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
char *strSQL = NULL;
PGresult *pgresult = NULL;
char** layer_bind_values = (char**)msSmallMalloc(sizeof(char*) * 1000);
char* bind_value;
char* bind_key = (char*)msSmallMalloc(3);
int num_bind_values = 0;
/* try to get the first bind value */
bind_value = msLookupHashTable(&layer->bindvals, "1");
while(bind_value != NULL) {
/* put the bind value on the stack */
layer_bind_values[num_bind_values] = bind_value;
/* increment the counter */
num_bind_values++;
/* create a new lookup key */
sprintf(bind_key, "%d", num_bind_values+1);
/* get the bind_value */
bind_value = msLookupHashTable(&layer->bindvals, bind_key);
}
assert(layer != NULL);
assert(layer->layerinfo != NULL);
if (layer->debug) {
msDebug("msPostGISLayerWhichShapes called.\n");
}
/* Fill out layerinfo with our current DATA state. */
if ( msPostGISParseData(layer) != MS_SUCCESS) {
return MS_FAILURE;
}
/*
** This comes *after* parsedata, because parsedata fills in
** layer->layerinfo.
*/
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Build a SQL query based on our current state. */
strSQL = msPostGISBuildSQL(layer, &rect, NULL);
if ( ! strSQL ) {
msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerWhichShapes()");
return MS_FAILURE;
}
if (layer->debug) {
msDebug("msPostGISLayerWhichShapes query: %s\n", strSQL);
}
if(num_bind_values > 0) {
pgresult = PQexecParams(layerinfo->pgconn, strSQL, num_bind_values, NULL, (const char**)layer_bind_values, NULL, NULL, 1);
} else {
pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
}
/* free bind values */
free(bind_key);
free(layer_bind_values);
if ( layer->debug > 1 ) {
msDebug("msPostGISLayerWhichShapes query status: %s (%d)\n", PQresStatus(PQresultStatus(pgresult)), PQresultStatus(pgresult));
}
/* Something went wrong. */
if (!pgresult || PQresultStatus(pgresult) != PGRES_TUPLES_OK) {
if ( layer->debug ) {
msDebug("Error (%s) executing query: %s", "msPostGISLayerWhichShapes()\n", PQerrorMessage(layerinfo->pgconn), strSQL);
}
msSetError(MS_QUERYERR, "Error executing query: %s ", "msPostGISLayerWhichShapes()", PQerrorMessage(layerinfo->pgconn));
free(strSQL);
if (pgresult) {
PQclear(pgresult);
}
return MS_FAILURE;
}
if ( layer->debug ) {
msDebug("msPostGISLayerWhichShapes got %d records in result.\n", PQntuples(pgresult));
}
/* Clean any existing pgresult before storing current one. */
if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
layerinfo->pgresult = pgresult;
/* Clean any existing SQL before storing current. */
if(layerinfo->sql) free(layerinfo->sql);
layerinfo->sql = strSQL;
layerinfo->rownum = 0;
return MS_SUCCESS;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerWhichShapes()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerNextShape()
**
** Registered vtable->LayerNextShape function.
*/
int msPostGISLayerNextShape(layerObj *layer, shapeObj *shape)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo;
if (layer->debug) {
msDebug("msPostGISLayerNextShape called.\n");
}
assert(layer != NULL);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
shape->type = MS_SHAPE_NULL;
/*
** Roll through pgresult until we hit non-null shape (usually right away).
*/
while (shape->type == MS_SHAPE_NULL) {
if (layerinfo->rownum < PQntuples(layerinfo->pgresult)) {
/* Retrieve this shape, cursor access mode. */
msPostGISReadShape(layer, shape);
if( shape->type != MS_SHAPE_NULL ) {
(layerinfo->rownum)++; /* move to next shape */
return MS_SUCCESS;
} else {
(layerinfo->rownum)++; /* move to next shape */
}
} else {
return MS_DONE;
}
}
/* Found nothing, clean up and exit. */
msFreeShape(shape);
return MS_FAILURE;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerNextShape()");
return MS_FAILURE;
#endif
}
/*
** msPostGISLayerGetShape()
**
** Registered vtable->LayerGetShape function. For pulling from a prepared and
** undisposed result set.
*/
int msPostGISLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
{
#ifdef USE_POSTGIS
PGresult *pgresult = NULL;
msPostGISLayerInfo *layerinfo = NULL;
long shapeindex = record->shapeindex;
int resultindex = record->resultindex;
assert(layer != NULL);
assert(layer->layerinfo != NULL);
if (layer->debug) {
msDebug("msPostGISLayerGetShape called for record = %i\n", resultindex);
}
/* If resultindex is set, fetch the shape from the resultcache, otherwise fetch it from the DB */
if (resultindex >= 0) {
int status;
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Check the validity of the open result. */
pgresult = layerinfo->pgresult;
if ( ! pgresult ) {
msSetError( MS_MISCERR,
"PostgreSQL result set is null.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
}
status = PQresultStatus(pgresult);
if ( layer->debug > 1 ) {
msDebug("msPostGISLayerGetShape query status: %s (%d)\n", PQresStatus(status), status);
}
if( ! ( status == PGRES_COMMAND_OK || status == PGRES_TUPLES_OK) ) {
msSetError( MS_MISCERR,
"PostgreSQL result set is not ready.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
}
/* Check the validity of the requested record number. */
if( resultindex >= PQntuples(pgresult) ) {
msDebug("msPostGISLayerGetShape got request for (%d) but only has %d tuples.\n", resultindex, PQntuples(pgresult));
msSetError( MS_MISCERR,
"Got request larger than result set.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
}
layerinfo->rownum = resultindex; /* Only return one result. */
/* We don't know the shape type until we read the geometry. */
shape->type = MS_SHAPE_NULL;
/* Return the shape, cursor access mode. */
msPostGISReadShape(layer, shape);
return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : MS_SUCCESS;
} else { /* no resultindex, fetch the shape from the DB */
int num_tuples;
char *strSQL = 0;
/* Fill out layerinfo with our current DATA state. */
if ( msPostGISParseData(layer) != MS_SUCCESS) {
return MS_FAILURE;
}
/*
** This comes *after* parsedata, because parsedata fills in
** layer->layerinfo.
*/
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* Build a SQL query based on our current state. */
strSQL = msPostGISBuildSQL(layer, 0, &shapeindex);
if ( ! strSQL ) {
msSetError(MS_QUERYERR, "Failed to build query SQL.", "msPostGISLayerGetShape()");
return MS_FAILURE;
}
if (layer->debug) {
msDebug("msPostGISLayerGetShape query: %s\n", strSQL);
}
pgresult = PQexecParams(layerinfo->pgconn, strSQL,0, NULL, NULL, NULL, NULL, 0);
/* Something went wrong. */
if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
if ( layer->debug ) {
msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetShape()\n", PQerrorMessage(layerinfo->pgconn), strSQL );
}
msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetShape()", PQerrorMessage(layerinfo->pgconn));
if (pgresult) {
PQclear(pgresult);
}
free(strSQL);
return MS_FAILURE;
}
/* Clean any existing pgresult before storing current one. */
if(layerinfo->pgresult) PQclear(layerinfo->pgresult);
layerinfo->pgresult = pgresult;
/* Clean any existing SQL before storing current. */
if(layerinfo->sql) free(layerinfo->sql);
layerinfo->sql = strSQL;
layerinfo->rownum = 0; /* Only return one result. */
/* We don't know the shape type until we read the geometry. */
shape->type = MS_SHAPE_NULL;
num_tuples = PQntuples(pgresult);
if (layer->debug) {
msDebug("msPostGISLayerGetShape number of records: %d\n", num_tuples);
}
if (num_tuples > 0) {
/* Get shape in random access mode. */
msPostGISReadShape(layer, shape);
}
return (shape->type == MS_SHAPE_NULL) ? MS_FAILURE : ( (num_tuples > 0) ? MS_SUCCESS : MS_DONE );
}
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerGetShape()");
return MS_FAILURE;
#endif
}
/**********************************************************************
* msPostGISPassThroughFieldDefinitions()
*
* Pass the field definitions through to the layer metadata in the
* "gml_[item]_{type,width,precision}" set of metadata items for
* defining fields.
**********************************************************************/
/* These are the OIDs for some builtin types, as returned by PQftype(). */
/* They were copied from pg_type.h in src/include/catalog/pg_type.h */
#ifndef BOOLOID
#define BOOLOID 16
#define BYTEAOID 17
#define CHAROID 18
#define NAMEOID 19
#define INT8OID 20
#define INT2OID 21
#define INT2VECTOROID 22
#define INT4OID 23
#define REGPROCOID 24
#define TEXTOID 25
#define OIDOID 26
#define TIDOID 27
#define XIDOID 28
#define CIDOID 29
#define OIDVECTOROID 30
#define FLOAT4OID 700
#define FLOAT8OID 701
#define INT4ARRAYOID 1007
#define TEXTARRAYOID 1009
#define BPCHARARRAYOID 1014
#define VARCHARARRAYOID 1015
#define FLOAT4ARRAYOID 1021
#define FLOAT8ARRAYOID 1022
#define BPCHAROID 1042
#define VARCHAROID 1043
#define DATEOID 1082
#define TIMEOID 1083
#define TIMESTAMPOID 1114
#define TIMESTAMPTZOID 1184
#define NUMERICOID 1700
#endif
#ifdef USE_POSTGIS
static void
msPostGISPassThroughFieldDefinitions( layerObj *layer,
PGresult *pgresult )
{
int i, numitems = PQnfields(pgresult);
msPostGISLayerInfo *layerinfo = layer->layerinfo;
for(i=0; i<numitems; i++) {
int oid, fmod;
const char *gml_type = "Character";
const char *item = PQfname(pgresult,i);
char md_item_name[256];
char gml_width[32], gml_precision[32];
gml_width[0] = '\0';
gml_precision[0] = '\0';
/* skip geometry column */
if( strcmp(item, layerinfo->geomcolumn) == 0 )
continue;
oid = PQftype(pgresult,i);
fmod = PQfmod(pgresult,i);
if( (oid == BPCHAROID || oid == VARCHAROID) && fmod >= 4 ) {
sprintf( gml_width, "%d", fmod-4 );
} else if( oid == BOOLOID ) {
gml_type = "Integer";
sprintf( gml_width, "%d", 1 );
} else if( oid == INT2OID ) {
gml_type = "Integer";
sprintf( gml_width, "%d", 5 );
} else if( oid == INT4OID || oid == INT8OID ) {
gml_type = "Integer";
} else if( oid == FLOAT4OID || oid == FLOAT8OID ) {
gml_type = "Real";
} else if( oid == NUMERICOID ) {
gml_type = "Real";
if( fmod >= 4 && ((fmod - 4) & 0xFFFF) == 0 ) {
gml_type = "Integer";
sprintf( gml_width, "%d", (fmod - 4) >> 16 );
} else if( fmod >= 4 ) {
sprintf( gml_width, "%d", (fmod - 4) >> 16 );
sprintf( gml_precision, "%d", ((fmod-4) & 0xFFFF) );
}
} else if( oid == DATEOID
|| oid == TIMESTAMPOID || oid == TIMESTAMPTZOID ) {
gml_type = "Date";
}
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_type", item );
if( msOWSLookupMetadata(&(layer->metadata), "G", "type") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_type );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_width", item );
if( strlen(gml_width) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "width") == NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_width );
snprintf( md_item_name, sizeof(md_item_name), "gml_%s_precision",item );
if( strlen(gml_precision) > 0
&& msOWSLookupMetadata(&(layer->metadata), "G", "precision")==NULL )
msInsertHashTable(&(layer->metadata), md_item_name, gml_precision );
}
}
#endif /* defined(USE_POSTGIS) */
/*
** msPostGISLayerGetItems()
**
** Registered vtable->LayerGetItems function. Query the database for
** column information about the requested layer. Rather than look in
** system tables, we just run a zero-cost query and read out of the
** result header.
*/
int msPostGISLayerGetItems(layerObj *layer)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
static char *strSQLTemplate = "select * from %s where false limit 0";
PGresult *pgresult = NULL;
char *col = NULL;
char *sql = NULL;
char *strFrom = NULL;
char found_geom = 0;
const char *value;
int t, item_num;
rectObj rect;
/* A useless rectangle for our useless query */
rect.minx = rect.miny = rect.maxx = rect.maxy = 0.0;
assert(layer != NULL);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
assert(layerinfo->pgconn);
if (layer->debug) {
msDebug("msPostGISLayerGetItems called.\n");
}
/* Fill out layerinfo with our current DATA state. */
if ( msPostGISParseData(layer) != MS_SUCCESS) {
return MS_FAILURE;
}
layerinfo = (msPostGISLayerInfo*) layer->layerinfo;
/* This allocates a fresh string, so remember to free it... */
strFrom = msPostGISReplaceBoxToken(layer, &rect, layerinfo->fromsource);
/*
** Both the "table" and "(select ...) as sub" cases can be handled with the
** same SQL.
*/
sql = (char*) msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom));
sprintf(sql, strSQLTemplate, strFrom);
free(strFrom);
if (layer->debug) {
msDebug("msPostGISLayerGetItems executing SQL: %s\n", sql);
}
pgresult = PQexecParams(layerinfo->pgconn, sql,0, NULL, NULL, NULL, NULL, 0);
if ( (!pgresult) || (PQresultStatus(pgresult) != PGRES_TUPLES_OK) ) {
if ( layer->debug ) {
msDebug("Error (%s) executing SQL: %s", "msPostGISLayerGetItems()\n", PQerrorMessage(layerinfo->pgconn), sql);
}
msSetError(MS_QUERYERR, "Error executing SQL: %s", "msPostGISLayerGetItems()", PQerrorMessage(layerinfo->pgconn));
if (pgresult) {
PQclear(pgresult);
}
free(sql);
return MS_FAILURE;
}
free(sql);
layer->numitems = PQnfields(pgresult) - 1; /* dont include the geometry column (last entry)*/
layer->items = msSmallMalloc(sizeof(char*) * (layer->numitems + 1)); /* +1 in case there is a problem finding geometry column */
found_geom = 0; /* havent found the geom field */
item_num = 0;
for (t = 0; t < PQnfields(pgresult); t++) {
col = PQfname(pgresult, t);
if ( strcmp(col, layerinfo->geomcolumn) != 0 ) {
/* this isnt the geometry column */
layer->items[item_num] = msStrdup(col);
item_num++;
} else {
found_geom = 1;
}
}
/*
** consider populating the field definitions in metadata.
*/
if((value = msOWSLookupMetadata(&(layer->metadata), "G", "types")) != NULL
&& strcasecmp(value,"auto") == 0 )
msPostGISPassThroughFieldDefinitions( layer, pgresult );
/*
** Cleanup
*/
PQclear(pgresult);
if (!found_geom) {
msSetError(MS_QUERYERR, "Tried to find the geometry column in the database, but couldn't find it. Is it mis-capitalized? '%s'", "msPostGISLayerGetItems()", layerinfo->geomcolumn);
return MS_FAILURE;
}
return msPostGISLayerInitItemInfo(layer);
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerGetItems()");
return MS_FAILURE;
#endif
}
/*
* make sure that the timestring is complete and acceptable
* to the date_trunc function :
* - if the resolution is year (2004) or month (2004-01),
* a complete string for time would be 2004-01-01
* - if the resolluion is hour or minute (2004-01-01 15), a
* complete time is 2004-01-01 15:00:00
*/
int postgresTimeStampForTimeString(const char *timestring, char *dest, size_t destsize)
{
int nlength = strlen(timestring);
int timeresolution = msTimeGetResolution(timestring);
int bNoDate = (*timestring == 'T');
if (timeresolution < 0)
return MS_FALSE;
switch(timeresolution) {
case TIME_RESOLUTION_YEAR:
if (timestring[nlength-1] != '-') {
snprintf(dest, destsize,"date '%s-01-01'",timestring);
} else {
snprintf(dest, destsize,"date '%s01-01'",timestring);
}
break;
case TIME_RESOLUTION_MONTH:
if (timestring[nlength-1] != '-') {
snprintf(dest, destsize,"date '%s-01'",timestring);
} else {
snprintf(dest, destsize,"date '%s01'",timestring);
}
break;
case TIME_RESOLUTION_DAY:
snprintf(dest, destsize,"date '%s'",timestring);
break;
case TIME_RESOLUTION_HOUR:
if (timestring[nlength-1] != ':') {
if(bNoDate)
snprintf(dest, destsize,"time '%s:00:00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s:00:00'", timestring);
} else {
if(bNoDate)
snprintf(dest, destsize,"time '%s00:00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s00:00'", timestring);
}
break;
case TIME_RESOLUTION_MINUTE:
if (timestring[nlength-1] != ':') {
if(bNoDate)
snprintf(dest, destsize,"time '%s:00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s:00'", timestring);
} else {
if(bNoDate)
snprintf(dest, destsize,"time '%s00'", timestring);
else
snprintf(dest, destsize,"timestamp '%s00'", timestring);
}
break;
case TIME_RESOLUTION_SECOND:
if(bNoDate)
snprintf(dest, destsize,"time '%s'", timestring);
else
snprintf(dest, destsize,"timestamp '%s'", timestring);
break;
default:
return MS_FAILURE;
}
return MS_SUCCESS;
}
/*
* create a postgresql where clause for the given timestring, taking into account
* the resolution (e.g. second, day, month...) of the given timestring
* we apply the date_trunc function on the given timestring and not on the time
* column in order for postgres to take advantage of an eventual index on the
* time column
*
* the generated sql is
*
* (
* timecol >= date_trunc(timestring,resolution)
* and
* timecol < date_trunc(timestring,resolution) + interval '1 resolution'
* )
*/
int createPostgresTimeCompareSimple(const char *timecol, const char *timestring, char *dest, size_t destsize)
{
int timeresolution = msTimeGetResolution(timestring);
char timeStamp[100];
char *interval;
if (timeresolution < 0)
return MS_FALSE;
postgresTimeStampForTimeString(timestring,timeStamp,100);
switch(timeresolution) {
case TIME_RESOLUTION_YEAR:
interval = "year";
break;
case TIME_RESOLUTION_MONTH:
interval = "month";
break;
case TIME_RESOLUTION_DAY:
interval = "day";
break;
case TIME_RESOLUTION_HOUR:
interval = "hour";
break;
case TIME_RESOLUTION_MINUTE:
interval = "minute";
break;
case TIME_RESOLUTION_SECOND:
interval = "second";
break;
default:
return MS_FAILURE;
}
snprintf(dest, destsize,"(%s >= date_trunc('%s',%s) and %s < date_trunc('%s',%s) + interval '1 %s')",
timecol, interval, timeStamp, timecol, interval, timeStamp, interval);
return MS_SUCCESS;
}
/*
* create a postgresql where clause for the range given by the two input timestring,
* taking into account the resolution (e.g. second, day, month...) of each of the
* given timestrings (both timestrings can have different resolutions, although I don't
* know if that's a valid TIME range
* we apply the date_trunc function on the given timestrings and not on the time
* column in order for postgres to take advantage of an eventual index on the
* time column
*
* the generated sql is
*
* (
* timecol >= date_trunc(mintimestring,minresolution)
* and
* timecol < date_trunc(maxtimestring,maxresolution) + interval '1 maxresolution'
* )
*/
int createPostgresTimeCompareRange(const char *timecol, const char *mintime, const char *maxtime,
char *dest, size_t destsize)
{
int mintimeresolution = msTimeGetResolution(mintime);
int maxtimeresolution = msTimeGetResolution(maxtime);
char minTimeStamp[100];
char maxTimeStamp[100];
char *minTimeInterval,*maxTimeInterval;
if (mintimeresolution < 0 || maxtimeresolution < 0)
return MS_FALSE;
postgresTimeStampForTimeString(mintime,minTimeStamp,100);
postgresTimeStampForTimeString(maxtime,maxTimeStamp,100);
switch(maxtimeresolution) {
case TIME_RESOLUTION_YEAR:
maxTimeInterval = "year";
break;
case TIME_RESOLUTION_MONTH:
maxTimeInterval = "month";
break;
case TIME_RESOLUTION_DAY:
maxTimeInterval = "day";
break;
case TIME_RESOLUTION_HOUR:
maxTimeInterval = "hour";
break;
case TIME_RESOLUTION_MINUTE:
maxTimeInterval = "minute";
break;
case TIME_RESOLUTION_SECOND:
maxTimeInterval = "second";
break;
default:
return MS_FAILURE;
}
switch(mintimeresolution) {
case TIME_RESOLUTION_YEAR:
minTimeInterval = "year";
break;
case TIME_RESOLUTION_MONTH:
minTimeInterval = "month";
break;
case TIME_RESOLUTION_DAY:
minTimeInterval = "day";
break;
case TIME_RESOLUTION_HOUR:
minTimeInterval = "hour";
break;
case TIME_RESOLUTION_MINUTE:
minTimeInterval = "minute";
break;
case TIME_RESOLUTION_SECOND:
minTimeInterval = "second";
break;
default:
return MS_FAILURE;
}
snprintf(dest, destsize,"(%s >= date_trunc('%s',%s) and %s < date_trunc('%s',%s) + interval '1 %s')",
timecol, minTimeInterval, minTimeStamp,
timecol, maxTimeInterval, maxTimeStamp, maxTimeInterval);
return MS_SUCCESS;
}
int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
char *msPostGISEscapeSQLParam(layerObj *layer, const char *pszString)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
int nError;
size_t nSrcLen;
char* pszEscapedStr =NULL;
if (layer && pszString && strlen(pszString) > 0) {
if(!msPostGISLayerIsOpen(layer))
msPostGISLayerOpen(layer);
assert(layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *) layer->layerinfo;
nSrcLen = strlen(pszString);
pszEscapedStr = (char*) msSmallMalloc( 2 * nSrcLen + 1);
PQescapeStringConn (layerinfo->pgconn, pszEscapedStr, pszString, nSrcLen, &nError);
if (nError != 0) {
free(pszEscapedStr);
pszEscapedStr = NULL;
}
}
return pszEscapedStr;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISEscapeSQLParam()");
return NULL;
#endif
}
void msPostGISEnablePaging(layerObj *layer, int value)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISEnablePaging called.\n");
}
if(!msPostGISLayerIsOpen(layer))
msPostGISLayerOpen(layer);
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
layerinfo->paging = value;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISEnablePaging()");
#endif
return;
}
int msPostGISGetPaging(layerObj *layer)
{
#ifdef USE_POSTGIS
msPostGISLayerInfo *layerinfo = NULL;
if (layer->debug) {
msDebug("msPostGISGetPaging called.\n");
}
if(!msPostGISLayerIsOpen(layer))
return MS_TRUE;
assert( layer->layerinfo != NULL);
layerinfo = (msPostGISLayerInfo *)layer->layerinfo;
return layerinfo->paging;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISEnablePaging()");
return MS_FAILURE;
#endif
}
int msPostGISLayerInitializeVirtualTable(layerObj *layer)
{
assert(layer != NULL);
assert(layer->vtable != NULL);
layer->vtable->LayerInitItemInfo = msPostGISLayerInitItemInfo;
layer->vtable->LayerFreeItemInfo = msPostGISLayerFreeItemInfo;
layer->vtable->LayerOpen = msPostGISLayerOpen;
layer->vtable->LayerIsOpen = msPostGISLayerIsOpen;
layer->vtable->LayerWhichShapes = msPostGISLayerWhichShapes;
layer->vtable->LayerNextShape = msPostGISLayerNextShape;
layer->vtable->LayerGetShape = msPostGISLayerGetShape;
layer->vtable->LayerClose = msPostGISLayerClose;
layer->vtable->LayerGetItems = msPostGISLayerGetItems;
/* layer->vtable->LayerGetExtent = msPostGISLayerGetExtent; */
layer->vtable->LayerApplyFilterToLayer = msLayerApplyCondSQLFilterToLayer;
/* layer->vtable->LayerGetAutoStyle, not supported for this layer */
/* layer->vtable->LayerCloseConnection = msPostGISLayerClose; */
layer->vtable->LayerSetTimeFilter = msPostGISLayerSetTimeFilter;
/* layer->vtable->LayerCreateItems, use default */
/* layer->vtable->LayerGetNumFeatures, use default */
/* layer->vtable->LayerGetAutoProjection, use defaut*/
layer->vtable->LayerEscapeSQLParam = msPostGISEscapeSQLParam;
layer->vtable->LayerEnablePaging = msPostGISEnablePaging;
layer->vtable->LayerGetPaging = msPostGISGetPaging;
return MS_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-89/c/bad_5843_0 |
crossvul-cpp_data_good_3567_2 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC3501 IMAPv4 protocol
* RFC5092 IMAP URL Scheme
*
***************************************************************************/
#include "setup.h"
#ifndef CURL_DISABLE_IMAP
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "if2ip.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "imap.h"
#include "strtoofft.h"
#include "strequal.h"
#include "sslgen.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "rawstr.h"
#include "strtoofft.h"
#include "http_proxy.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/* Local API functions */
static CURLcode imap_parse_url_path(struct connectdata *conn);
static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode imap_do(struct connectdata *conn, bool *done);
static CURLcode imap_done(struct connectdata *conn,
CURLcode, bool premature);
static CURLcode imap_connect(struct connectdata *conn, bool *done);
static CURLcode imap_disconnect(struct connectdata *conn, bool dead);
static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done);
static int imap_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks);
static CURLcode imap_doing(struct connectdata *conn,
bool *dophase_done);
static CURLcode imap_setup_connection(struct connectdata * conn);
static CURLcode imap_state_upgrade_tls(struct connectdata *conn);
/*
* IMAP protocol handler.
*/
const struct Curl_handler Curl_handler_imap = {
"IMAP", /* scheme */
imap_setup_connection, /* setup_connection */
imap_do, /* do_it */
imap_done, /* done */
ZERO_NULL, /* do_more */
imap_connect, /* connect_it */
imap_multi_statemach, /* connecting */
imap_doing, /* doing */
imap_getsock, /* proto_getsock */
imap_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAP, /* defport */
CURLPROTO_IMAP, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD
| PROTOPT_NOURLQUERY /* flags */
};
#ifdef USE_SSL
/*
* IMAPS protocol handler.
*/
const struct Curl_handler Curl_handler_imaps = {
"IMAPS", /* scheme */
imap_setup_connection, /* setup_connection */
imap_do, /* do_it */
imap_done, /* done */
ZERO_NULL, /* do_more */
imap_connect, /* connect_it */
imap_multi_statemach, /* connecting */
imap_doing, /* doing */
imap_getsock, /* proto_getsock */
imap_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAPS, /* defport */
CURLPROTO_IMAP | CURLPROTO_IMAPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL | PROTOPT_NEEDSPWD
| PROTOPT_NOURLQUERY /* flags */
};
#endif
#ifndef CURL_DISABLE_HTTP
/*
* HTTP-proxyed IMAP protocol handler.
*/
static const struct Curl_handler Curl_handler_imap_proxy = {
"IMAP", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAP, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* HTTP-proxyed IMAPS protocol handler.
*/
static const struct Curl_handler Curl_handler_imaps_proxy = {
"IMAPS", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAPS, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#endif
#endif
/***********************************************************************
*
* imapsendf()
*
* Sends the formated string as an IMAP command to a server
*
* Designed to never block.
*/
static CURLcode imapsendf(struct connectdata *conn,
const char *idstr, /* id to wait for at the
completion of this command */
const char *fmt, ...)
{
CURLcode res;
struct imap_conn *imapc = &conn->proto.imapc;
va_list ap;
va_start(ap, fmt);
imapc->idstr = idstr; /* this is the thing */
res = Curl_pp_vsendf(&imapc->pp, fmt, ap);
va_end(ap);
return res;
}
static const char *getcmdid(struct connectdata *conn)
{
static const char * const ids[]= {
"A",
"B",
"C",
"D"
};
struct imap_conn *imapc = &conn->proto.imapc;
/* get the next id, but wrap at end of table */
imapc->cmdid = (int)((imapc->cmdid+1) % (sizeof(ids)/sizeof(ids[0])));
return ids[imapc->cmdid];
}
/* For the IMAP "protocol connect" and "doing" phases only */
static int imap_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.imapc.pp, socks, numsocks);
}
/* function that checks for an imap status code at the start of the
given string */
static int imap_endofresp(struct pingpong *pp, int *resp)
{
char *line = pp->linestart_resp;
size_t len = pp->nread_resp;
struct imap_conn *imapc = &pp->conn->proto.imapc;
const char *id = imapc->idstr;
size_t id_len = strlen(id);
if(len >= id_len + 3) {
if(!memcmp(id, line, id_len) && (line[id_len] == ' ') ) {
/* end of response */
*resp = line[id_len+1]; /* O, N or B */
return TRUE;
}
else if((imapc->state == IMAP_FETCH) &&
!memcmp("* ", line, 2) ) {
/* FETCH response we're interested in */
*resp = '*';
return TRUE;
}
}
return FALSE; /* nothing for us */
}
/* This is the ONLY way to change IMAP state! */
static void state(struct connectdata *conn,
imapstate newstate)
{
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[]={
"STOP",
"SERVERGREET",
"LOGIN",
"STARTTLS",
"UPGRADETLS",
"SELECT",
"FETCH",
"LOGOUT",
/* LAST */
};
#endif
struct imap_conn *imapc = &conn->proto.imapc;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
if(imapc->state != newstate)
infof(conn->data, "IMAP %p state change from %s to %s\n",
imapc, names[imapc->state], names[newstate]);
#endif
imapc->state = newstate;
}
static CURLcode imap_state_login(struct connectdata *conn)
{
CURLcode result;
struct FTP *imap = conn->data->state.proto.imap;
const char *str;
str = getcmdid(conn);
/* send USER and password */
result = imapsendf(conn, str, "%s LOGIN %s %s", str,
imap->user?imap->user:"",
imap->passwd?imap->passwd:"");
if(result)
return result;
state(conn, IMAP_LOGIN);
return CURLE_OK;
}
#ifdef USE_SSL
static void imap_to_imaps(struct connectdata *conn)
{
conn->handler = &Curl_handler_imaps;
}
#else
#define imap_to_imaps(x) Curl_nop_stmt
#endif
/* for STARTTLS responses */
static CURLcode imap_state_starttls_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied. %c", imapcode);
result = CURLE_USE_SSL_FAILED;
}
else
result = imap_state_login(conn);
}
else {
if(data->state.used_interface == Curl_if_multi) {
state(conn, IMAP_UPGRADETLS);
return imap_state_upgrade_tls(conn);
}
else {
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(CURLE_OK == result) {
imap_to_imaps(conn);
result = imap_state_login(conn);
}
}
}
state(conn, IMAP_STOP);
return result;
}
static CURLcode imap_state_upgrade_tls(struct connectdata *conn)
{
struct imap_conn *imapc = &conn->proto.imapc;
CURLcode result;
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
if(imapc->ssldone) {
imap_to_imaps(conn);
result = imap_state_login(conn);
state(conn, IMAP_STOP);
}
return result;
}
/* for LOGIN responses */
static CURLcode imap_state_login_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
failf(data, "Access denied. %c", imapcode);
result = CURLE_LOGIN_DENIED;
}
state(conn, IMAP_STOP);
return result;
}
/* for the (first line of) FETCH BODY[TEXT] response */
static CURLcode imap_state_fetch_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
struct imap_conn *imapc = &conn->proto.imapc;
struct FTP *imap = data->state.proto.imap;
struct pingpong *pp = &imapc->pp;
const char *ptr = data->state.buffer;
(void)instate; /* no use for this yet */
if('*' != imapcode) {
Curl_pgrsSetDownloadSize(data, 0);
state(conn, IMAP_STOP);
return CURLE_OK;
}
/* Something like this comes "* 1 FETCH (BODY[TEXT] {2021}\r" */
while(*ptr && (*ptr != '{'))
ptr++;
if(*ptr == '{') {
curl_off_t filesize = curlx_strtoofft(ptr+1, NULL, 10);
if(filesize)
Curl_pgrsSetDownloadSize(data, filesize);
infof(data, "Found %" FORMAT_OFF_TU " bytes to download\n", filesize);
if(pp->cache) {
/* At this point there is a bunch of data in the header "cache" that is
actually body content, send it as body and then skip it. Do note
that there may even be additional "headers" after the body. */
size_t chunk = pp->cache_size;
if(chunk > (size_t)filesize)
/* the conversion from curl_off_t to size_t is always fine here */
chunk = (size_t)filesize;
result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
if(result)
return result;
filesize -= chunk;
/* we've now used parts of or the entire cache */
if(pp->cache_size > chunk) {
/* part of, move the trailing data to the start and reduce the size */
memmove(pp->cache, pp->cache+chunk,
pp->cache_size - chunk);
pp->cache_size -= chunk;
}
else {
/* cache is drained */
free(pp->cache);
pp->cache = NULL;
pp->cache_size = 0;
}
}
infof(data, "Filesize left: %" FORMAT_OFF_T "\n", filesize);
if(!filesize)
/* the entire data is already transferred! */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
else
/* IMAP download */
Curl_setup_transfer(conn, FIRSTSOCKET, filesize, FALSE,
imap->bytecountp, -1, NULL); /* no upload here */
data->req.maxdownload = filesize;
}
else
/* We don't know how to parse this line */
result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: fix this code */
state(conn, IMAP_STOP);
return result;
}
/* start the DO phase */
static CURLcode imap_select(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
const char *str;
str = getcmdid(conn);
result = imapsendf(conn, str, "%s SELECT %s", str,
imapc->mailbox?imapc->mailbox:"");
if(result)
return result;
state(conn, IMAP_SELECT);
return result;
}
static CURLcode imap_fetch(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
const char *str;
str = getcmdid(conn);
/* TODO: make this select the correct mail
* Use "1 body[text]" to get the full mail body of mail 1
*/
result = imapsendf(conn, str, "%s FETCH 1 BODY[TEXT]", str);
if(result)
return result;
/*
* When issued, the server will respond with a single line similar to
* '* 1 FETCH (BODY[TEXT] {2021}'
*
* Identifying the fetch and how many bytes of contents we can expect. We
* must extract that number before continuing to "download as usual".
*/
state(conn, IMAP_FETCH);
return result;
}
/* for SELECT responses */
static CURLcode imap_state_select_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
failf(data, "Select failed");
result = CURLE_LOGIN_DENIED;
}
else
result = imap_fetch(conn);
return result;
}
static CURLcode imap_statemach_act(struct connectdata *conn)
{
CURLcode result;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct SessionHandle *data=conn->data;
int imapcode;
struct imap_conn *imapc = &conn->proto.imapc;
struct pingpong *pp = &imapc->pp;
size_t nread = 0;
/* busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
if(imapc->state == IMAP_UPGRADETLS)
return imap_state_upgrade_tls(conn);
if(pp->sendleft)
return Curl_pp_flushsend(pp);
/* we read a piece of response */
result = Curl_pp_readresp(sock, pp, &imapcode, &nread);
if(result)
return result;
if(imapcode)
/* we have now received a full IMAP server response */
switch(imapc->state) {
case IMAP_SERVERGREET:
if(imapcode != 'O') {
failf(data, "Got unexpected imap-server response");
return CURLE_FTP_WEIRD_SERVER_REPLY;
}
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested. Switch
to TLS connection now */
const char *str;
str = getcmdid(conn);
result = imapsendf(conn, str, "%s STARTTLS", str);
state(conn, IMAP_STARTTLS);
}
else
result = imap_state_login(conn);
if(result)
return result;
break;
case IMAP_LOGIN:
result = imap_state_login_resp(conn, imapcode, imapc->state);
break;
case IMAP_STARTTLS:
result = imap_state_starttls_resp(conn, imapcode, imapc->state);
break;
case IMAP_FETCH:
result = imap_state_fetch_resp(conn, imapcode, imapc->state);
break;
case IMAP_SELECT:
result = imap_state_select_resp(conn, imapcode, imapc->state);
break;
case IMAP_LOGOUT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, IMAP_STOP);
break;
}
return result;
}
/* called repeatedly until done from multi.c */
static CURLcode imap_multi_statemach(struct connectdata *conn,
bool *done)
{
struct imap_conn *imapc = &conn->proto.imapc;
CURLcode result;
if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone)
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
else
result = Curl_pp_multi_statemach(&imapc->pp);
*done = (imapc->state == IMAP_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode imap_easy_statemach(struct connectdata *conn)
{
struct imap_conn *imapc = &conn->proto.imapc;
struct pingpong *pp = &imapc->pp;
CURLcode result = CURLE_OK;
while(imapc->state != IMAP_STOP) {
result = Curl_pp_easy_statemach(pp);
if(result)
break;
}
return result;
}
/*
* Allocate and initialize the struct IMAP for the current SessionHandle. If
* need be.
*/
static CURLcode imap_init(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
struct FTP *imap = data->state.proto.imap;
if(!imap) {
imap = data->state.proto.imap = calloc(sizeof(struct FTP), 1);
if(!imap)
return CURLE_OUT_OF_MEMORY;
}
/* get some initial data into the imap struct */
imap->bytecountp = &data->req.bytecount;
/* No need to duplicate user+password, the connectdata struct won't change
during a session, but we re-init them here since on subsequent inits
since the conn struct may have changed or been replaced.
*/
imap->user = conn->user;
imap->passwd = conn->passwd;
return CURLE_OK;
}
/*
* imap_connect() should do everything that is to be considered a part of
* the connection phase.
*
* The variable 'done' points to will be TRUE if the protocol-layer connect
* phase is done when this function returns, or FALSE is not. When called as
* a part of the easy interface, it will always be TRUE.
*/
static CURLcode imap_connect(struct connectdata *conn,
bool *done) /* see description above */
{
CURLcode result;
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data=conn->data;
struct pingpong *pp = &imapc->pp;
*done = FALSE; /* default to not done yet */
/* If there already is a protocol-specific struct allocated for this
sessionhandle, deal with it */
Curl_reset_reqproto(conn);
result = imap_init(conn);
if(CURLE_OK != result)
return result;
/* We always support persistent connections on imap */
conn->bits.close = FALSE;
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = imap_statemach_act;
pp->endofresp = imap_endofresp;
pp->conn = conn;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
/* for IMAP over HTTP proxy */
struct HTTP http_proxy;
struct FTP *imap_save;
/* BLOCKING */
/* We want "seamless" IMAP operations through HTTP proxy tunnel */
/* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the member
* conn->proto.http; we want IMAP through HTTP and we have to change the
* member temporarily for connecting to the HTTP proxy. After
* Curl_proxyCONNECT we have to set back the member to the original struct
* IMAP pointer
*/
imap_save = data->state.proto.imap;
memset(&http_proxy, 0, sizeof(http_proxy));
data->state.proto.http = &http_proxy;
result = Curl_proxyCONNECT(conn, FIRSTSOCKET,
conn->host.name, conn->remote_port);
data->state.proto.imap = imap_save;
if(CURLE_OK != result)
return result;
}
if((conn->handler->flags & PROTOPT_SSL) &&
data->state.used_interface != Curl_if_multi) {
/* BLOCKING */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(result)
return result;
}
Curl_pp_init(pp); /* init generic pingpong data */
/* When we connect, we start in the state where we await the server greeting
response */
state(conn, IMAP_SERVERGREET);
imapc->idstr = "*"; /* we start off waiting for a '*' response */
if(data->state.used_interface == Curl_if_multi)
result = imap_multi_statemach(conn, done);
else {
result = imap_easy_statemach(conn);
if(!result)
*done = TRUE;
}
return result;
}
/***********************************************************************
*
* imap_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode imap_done(struct connectdata *conn, CURLcode status,
bool premature)
{
struct SessionHandle *data = conn->data;
struct FTP *imap = data->state.proto.imap;
CURLcode result=CURLE_OK;
(void)premature;
if(!imap)
/* When the easy handle is removed from the multi while libcurl is still
* trying to resolve the host name, it seems that the imap struct is not
* yet initialized, but the removal action calls Curl_done() which calls
* this function. So we simply return success if no imap pointer is set.
*/
return CURLE_OK;
if(status) {
conn->bits.close = TRUE; /* marked for closure */
result = status; /* use the already set error code */
}
/* clear these for next connection */
imap->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* imap_perform()
*
* This is the actual DO function for IMAP. Get a file/directory according to
* the options previously setup.
*/
static
CURLcode imap_perform(struct connectdata *conn,
bool *connected, /* connect status after PASV / PORT */
bool *dophase_done)
{
/* this is IMAP and no proxy */
CURLcode result=CURLE_OK;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(conn->data->set.opt_no_body) {
/* requested no body means no transfer... */
struct FTP *imap = conn->data->state.proto.imap;
imap->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* start the first command in the DO phase */
result = imap_select(conn);
if(result)
return result;
/* run the state-machine */
if(conn->data->state.used_interface == Curl_if_multi)
result = imap_multi_statemach(conn, dophase_done);
else {
result = imap_easy_statemach(conn);
*dophase_done = TRUE; /* with the easy interface we are done here */
}
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* imap_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (imap_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode imap_do(struct connectdata *conn, bool *done)
{
CURLcode retcode = CURLE_OK;
*done = FALSE; /* default to false */
/*
Since connections can be re-used between SessionHandles, this might be a
connection already existing but on a fresh SessionHandle struct so we must
make sure we have a good 'struct IMAP' to play with. For new connections,
the struct IMAP is allocated and setup in the imap_connect() function.
*/
Curl_reset_reqproto(conn);
retcode = imap_init(conn);
if(retcode)
return retcode;
retcode = imap_parse_url_path(conn);
if(retcode)
return retcode;
retcode = imap_regular_transfer(conn, done);
return retcode;
}
/***********************************************************************
*
* imap_logout()
*
* This should be called before calling sclose(). We should then wait for the
* response from the server before returning. The calling code should then try
* to close the connection.
*
*/
static CURLcode imap_logout(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
const char *str;
str = getcmdid(conn);
result = imapsendf(conn, str, "%s LOGOUT", str, NULL);
if(result)
return result;
state(conn, IMAP_LOGOUT);
result = imap_easy_statemach(conn);
return result;
}
/***********************************************************************
*
* imap_disconnect()
*
* Disconnect from an IMAP server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection)
{
struct imap_conn *imapc= &conn->proto.imapc;
/* The IMAP session may or may not have been allocated/setup at this
point! */
if(!dead_connection && imapc->pp.conn)
(void)imap_logout(conn); /* ignore errors on the LOGOUT */
Curl_pp_disconnect(&imapc->pp);
Curl_safefree(imapc->mailbox);
return CURLE_OK;
}
/***********************************************************************
*
* imap_parse_url_path()
*
* Parse the URL path into separate path components.
*
*/
static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
return Curl_urldecode(data, path, 0, &imapc->mailbox, NULL, TRUE);
}
/* call this when the DO phase has completed */
static CURLcode imap_dophase_done(struct connectdata *conn,
bool connected)
{
struct FTP *imap = conn->data->state.proto.imap;
(void)connected;
if(imap->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
return CURLE_OK;
}
/* called from multi.c while DOing */
static CURLcode imap_doing(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result;
result = imap_multi_statemach(conn, dophase_done);
if(*dophase_done) {
result = imap_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* imap_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*
*/
static
CURLcode imap_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result=CURLE_OK;
bool connected=FALSE;
struct SessionHandle *data = conn->data;
data->req.size = -1; /* make sure this is unknown at this point */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, 0);
Curl_pgrsSetDownloadSize(data, 0);
result = imap_perform(conn,
&connected, /* have we connected after PASV/PORT */
dophase_done); /* all commands in the DO-phase done? */
if(CURLE_OK == result) {
if(!*dophase_done)
/* the DO phase has not completed yet */
return CURLE_OK;
result = imap_dophase_done(conn, connected);
if(result)
return result;
}
return result;
}
static CURLcode imap_setup_connection(struct connectdata * conn)
{
struct SessionHandle *data = conn->data;
if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
/* Unless we have asked to tunnel imap operations through the proxy, we
switch and use HTTP operations only */
#ifndef CURL_DISABLE_HTTP
if(conn->handler == &Curl_handler_imap)
conn->handler = &Curl_handler_imap_proxy;
else {
#ifdef USE_SSL
conn->handler = &Curl_handler_imaps_proxy;
#else
failf(data, "IMAPS not supported!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
/*
* We explicitly mark this connection as persistent here as we're doing
* IMAP over HTTP and thus we accidentally avoid setting this value
* otherwise.
*/
conn->bits.close = FALSE;
#else
failf(data, "IMAP over http proxy requires HTTP support built-in!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
#endif /* CURL_DISABLE_IMAP */
| ./CrossVul/dataset_final_sorted/CWE-89/c/good_3567_2 |
crossvul-cpp_data_good_3567_4 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC2821 SMTP protocol
* RFC3207 SMTP over TLS
* RFC4954 SMTP Authentication
* RFC2195 CRAM-MD5 authentication
* RFC4616 PLAIN authentication
*
***************************************************************************/
#include "setup.h"
#ifndef CURL_DISABLE_SMTP
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "if2ip.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "smtp.h"
#include "strtoofft.h"
#include "strequal.h"
#include "sslgen.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "rawstr.h"
#include "strtoofft.h"
#include "curl_base64.h"
#include "curl_md5.h"
#include "curl_hmac.h"
#include "curl_gethostname.h"
#include "curl_ntlm_msgs.h"
#include "warnless.h"
#include "http_proxy.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/* Local API functions */
static CURLcode smtp_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode smtp_do(struct connectdata *conn, bool *done);
static CURLcode smtp_done(struct connectdata *conn,
CURLcode, bool premature);
static CURLcode smtp_connect(struct connectdata *conn, bool *done);
static CURLcode smtp_disconnect(struct connectdata *conn, bool dead);
static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done);
static int smtp_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks);
static CURLcode smtp_doing(struct connectdata *conn,
bool *dophase_done);
static CURLcode smtp_setup_connection(struct connectdata * conn);
static CURLcode smtp_state_upgrade_tls(struct connectdata *conn);
/*
* SMTP protocol handler.
*/
const struct Curl_handler Curl_handler_smtp = {
"SMTP", /* scheme */
smtp_setup_connection, /* setup_connection */
smtp_do, /* do_it */
smtp_done, /* done */
ZERO_NULL, /* do_more */
smtp_connect, /* connect_it */
smtp_multi_statemach, /* connecting */
smtp_doing, /* doing */
smtp_getsock, /* proto_getsock */
smtp_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTP, /* defport */
CURLPROTO_SMTP, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */
};
#ifdef USE_SSL
/*
* SMTPS protocol handler.
*/
const struct Curl_handler Curl_handler_smtps = {
"SMTPS", /* scheme */
smtp_setup_connection, /* setup_connection */
smtp_do, /* do_it */
smtp_done, /* done */
ZERO_NULL, /* do_more */
smtp_connect, /* connect_it */
smtp_multi_statemach, /* connecting */
smtp_doing, /* doing */
smtp_getsock, /* proto_getsock */
smtp_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTPS, /* defport */
CURLPROTO_SMTP | CURLPROTO_SMTPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL
| PROTOPT_NOURLQUERY /* flags */
};
#endif
#ifndef CURL_DISABLE_HTTP
/*
* HTTP-proxyed SMTP protocol handler.
*/
static const struct Curl_handler Curl_handler_smtp_proxy = {
"SMTP", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTP, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* HTTP-proxyed SMTPS protocol handler.
*/
static const struct Curl_handler Curl_handler_smtps_proxy = {
"SMTPS", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTPS, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#endif
#endif
/* Function that checks for an ending smtp status code at the start of the
given string.
As a side effect, it also flags allowed authentication mechanisms according
to EHLO AUTH response. */
static int smtp_endofresp(struct pingpong *pp, int *resp)
{
char *line = pp->linestart_resp;
size_t len = pp->nread_resp;
struct connectdata *conn = pp->conn;
struct smtp_conn *smtpc = &conn->proto.smtpc;
int result;
size_t wordlen;
if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
return FALSE; /* Nothing for us. */
if((result = (line[3] == ' ')) != 0)
*resp = curlx_sltosi(strtol(line, NULL, 10));
line += 4;
len -= 4;
if(smtpc->state == SMTP_EHLO && len >= 5 && !memcmp(line, "AUTH ", 5)) {
line += 5;
len -= 5;
for(;;) {
while(len &&
(*line == ' ' || *line == '\t' ||
*line == '\r' || *line == '\n')) {
line++;
len--;
}
if(!len)
break;
for(wordlen = 0; wordlen < len && line[wordlen] != ' ' &&
line[wordlen] != '\t' && line[wordlen] != '\r' &&
line[wordlen] != '\n';)
wordlen++;
if(wordlen == 5 && !memcmp(line, "LOGIN", 5))
smtpc->authmechs |= SMTP_AUTH_LOGIN;
else if(wordlen == 5 && !memcmp(line, "PLAIN", 5))
smtpc->authmechs |= SMTP_AUTH_PLAIN;
else if(wordlen == 8 && !memcmp(line, "CRAM-MD5", 8))
smtpc->authmechs |= SMTP_AUTH_CRAM_MD5;
else if(wordlen == 10 && !memcmp(line, "DIGEST-MD5", 10))
smtpc->authmechs |= SMTP_AUTH_DIGEST_MD5;
else if(wordlen == 6 && !memcmp(line, "GSSAPI", 6))
smtpc->authmechs |= SMTP_AUTH_GSSAPI;
else if(wordlen == 8 && !memcmp(line, "EXTERNAL", 8))
smtpc->authmechs |= SMTP_AUTH_EXTERNAL;
else if(wordlen == 4 && !memcmp(line, "NTLM", 4))
smtpc->authmechs |= SMTP_AUTH_NTLM;
line += wordlen;
len -= wordlen;
}
}
return result;
}
/* This is the ONLY way to change SMTP state! */
static void state(struct connectdata *conn,
smtpstate newstate)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[] = {
"STOP",
"SERVERGREET",
"EHLO",
"HELO",
"STARTTLS",
"UPGRADETLS",
"AUTHPLAIN",
"AUTHLOGIN",
"AUTHPASSWD",
"AUTHCRAM",
"AUTHNTLM",
"AUTHNTLM_TYPE2MSG",
"AUTH",
"MAIL",
"RCPT",
"DATA",
"POSTDATA",
"QUIT",
/* LAST */
};
if(smtpc->state != newstate)
infof(conn->data, "SMTP %p state change from %s to %s\n",
smtpc, names[smtpc->state], names[newstate]);
#endif
smtpc->state = newstate;
}
static CURLcode smtp_state_ehlo(struct connectdata *conn)
{
CURLcode result;
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->authmechs = 0; /* No known authentication mechanisms yet. */
smtpc->authused = 0; /* Clear the authentication mechanism used
for esmtp connections */
/* send EHLO */
result = Curl_pp_sendf(&smtpc->pp, "EHLO %s", smtpc->domain);
if(result)
return result;
state(conn, SMTP_EHLO);
return CURLE_OK;
}
static CURLcode smtp_state_helo(struct connectdata *conn)
{
CURLcode result;
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->authused = 0; /* No authentication mechanism used in smtp
connections */
/* send HELO */
result = Curl_pp_sendf(&smtpc->pp, "HELO %s", smtpc->domain);
if(result)
return result;
state(conn, SMTP_HELO);
return CURLE_OK;
}
static CURLcode smtp_auth_plain_data(struct connectdata *conn,
char **outptr, size_t *outlen)
{
char plainauth[2 * MAX_CURL_USER_LENGTH + MAX_CURL_PASSWORD_LENGTH];
size_t ulen;
size_t plen;
ulen = strlen(conn->user);
plen = strlen(conn->passwd);
if(2 * ulen + plen + 2 > sizeof plainauth) {
*outlen = 0;
*outptr = NULL;
return CURLE_OUT_OF_MEMORY; /* plainauth too small */
}
memcpy(plainauth, conn->user, ulen);
plainauth[ulen] = '\0';
memcpy(plainauth + ulen + 1, conn->user, ulen);
plainauth[2 * ulen + 1] = '\0';
memcpy(plainauth + 2 * ulen + 2, conn->passwd, plen);
return Curl_base64_encode(conn->data, plainauth, 2 * ulen + plen + 2,
outptr, outlen);
}
static CURLcode smtp_auth_login_user(struct connectdata *conn,
char **outptr, size_t *outlen)
{
size_t ulen = strlen(conn->user);
if(!ulen) {
*outptr = strdup("=");
if(*outptr) {
*outlen = (size_t) 1;
return CURLE_OK;
}
*outlen = 0;
return CURLE_OUT_OF_MEMORY;
}
return Curl_base64_encode(conn->data, conn->user, ulen, outptr, outlen);
}
#ifdef USE_NTLM
static CURLcode smtp_auth_ntlm_type1_message(struct connectdata *conn,
char **outptr, size_t *outlen)
{
return Curl_ntlm_create_type1_message(conn->user, conn->passwd,
&conn->ntlm, outptr, outlen);
}
#endif
static CURLcode smtp_authenticate(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
char *initresp = NULL;
const char *mech = NULL;
size_t len = 0;
smtpstate state1 = SMTP_STOP;
smtpstate state2 = SMTP_STOP;
/* Check we have a username and password to authenticate with and end the
connect phase if we don't. */
if(!conn->bits.user_passwd) {
state(conn, SMTP_STOP);
return result;
}
/* Check supported authentication mechanisms by decreasing order of
security. */
#ifndef CURL_DISABLE_CRYPTO_AUTH
if(smtpc->authmechs & SMTP_AUTH_CRAM_MD5) {
mech = "CRAM-MD5";
state1 = SMTP_AUTHCRAM;
smtpc->authused = SMTP_AUTH_CRAM_MD5;
}
else
#endif
#ifdef USE_NTLM
if(smtpc->authmechs & SMTP_AUTH_NTLM) {
mech = "NTLM";
state1 = SMTP_AUTHNTLM;
state2 = SMTP_AUTHNTLM_TYPE2MSG;
smtpc->authused = SMTP_AUTH_NTLM;
result = smtp_auth_ntlm_type1_message(conn, &initresp, &len);
}
else
#endif
if(smtpc->authmechs & SMTP_AUTH_LOGIN) {
mech = "LOGIN";
state1 = SMTP_AUTHLOGIN;
state2 = SMTP_AUTHPASSWD;
smtpc->authused = SMTP_AUTH_LOGIN;
result = smtp_auth_login_user(conn, &initresp, &len);
}
else if(smtpc->authmechs & SMTP_AUTH_PLAIN) {
mech = "PLAIN";
state1 = SMTP_AUTHPLAIN;
state2 = SMTP_AUTH;
smtpc->authused = SMTP_AUTH_PLAIN;
result = smtp_auth_plain_data(conn, &initresp, &len);
}
else {
infof(conn->data, "No known auth mechanisms supported!\n");
result = CURLE_LOGIN_DENIED; /* Other mechanisms not supported. */
}
if(!result) {
if(initresp &&
strlen(mech) + len <= 512 - 8) { /* AUTH <mech> ...<crlf> */
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s %s", mech, initresp);
if(!result)
state(conn, state2);
}
else {
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s", mech);
if(!result)
state(conn, state1);
}
Curl_safefree(initresp);
}
return result;
}
/* For the SMTP "protocol connect" and "doing" phases only */
static int smtp_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.smtpc.pp, socks, numsocks);
}
#ifdef USE_SSL
static void smtp_to_smtps(struct connectdata *conn)
{
conn->handler = &Curl_handler_smtps;
}
#else
#define smtp_to_smtps(x) Curl_nop_stmt
#endif
/* for STARTTLS responses */
static CURLcode smtp_state_starttls_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode != 220) {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied. %c", smtpcode);
result = CURLE_USE_SSL_FAILED;
}
else
result = smtp_authenticate(conn);
}
else {
if(data->state.used_interface == Curl_if_multi) {
state(conn, SMTP_UPGRADETLS);
return smtp_state_upgrade_tls(conn);
}
else {
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(CURLE_OK == result) {
smtp_to_smtps(conn);
result = smtp_state_ehlo(conn);
}
}
}
return result;
}
static CURLcode smtp_state_upgrade_tls(struct connectdata *conn)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
CURLcode result;
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
if(smtpc->ssldone) {
smtp_to_smtps(conn);
result = smtp_state_ehlo(conn);
}
return result;
}
/* for EHLO responses */
static CURLcode smtp_state_ehlo_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
if((data->set.use_ssl <= CURLUSESSL_TRY || conn->ssl[FIRSTSOCKET].use) &&
!conn->bits.user_passwd)
result = smtp_state_helo(conn);
else {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
}
else if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested. Switch
to TLS connection now */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "STARTTLS");
state(conn, SMTP_STARTTLS);
}
else
result = smtp_authenticate(conn);
return result;
}
/* for HELO responses */
static CURLcode smtp_state_helo_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
/* end the connect phase */
state(conn, SMTP_STOP);
}
return result;
}
/* for AUTH PLAIN (without initial response) responses */
static CURLcode smtp_state_authplain_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
size_t len = 0;
char *plainauth = NULL;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = smtp_auth_plain_data(conn, &plainauth, &len);
if(!result) {
if(plainauth) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", plainauth);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(plainauth);
}
}
return result;
}
/* for AUTH LOGIN (without initial response) responses */
static CURLcode smtp_state_authlogin_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
size_t len = 0;
char *authuser = NULL;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = smtp_auth_login_user(conn, &authuser, &len);
if(!result) {
if(authuser) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", authuser);
if(!result)
state(conn, SMTP_AUTHPASSWD);
}
Curl_safefree(authuser);
}
}
return result;
}
/* for responses to user entry of AUTH LOGIN. */
static CURLcode smtp_state_authpasswd_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
size_t plen;
size_t len = 0;
char *authpasswd = NULL;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
plen = strlen(conn->passwd);
if(!plen)
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "=");
else {
result = Curl_base64_encode(data, conn->passwd, plen, &authpasswd, &len);
if(!result) {
if(authpasswd) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", authpasswd);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(authpasswd);
}
}
}
return result;
}
#ifndef CURL_DISABLE_CRYPTO_AUTH
/* for AUTH CRAM-MD5 responses. */
static CURLcode smtp_state_authcram_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
char * chlg64 = data->state.buffer;
unsigned char * chlg;
size_t chlglen;
size_t len = 0;
char *rplyb64 = NULL;
HMAC_context *ctxt;
unsigned char digest[16];
char reply[MAX_CURL_USER_LENGTH + 32 /* 2 * size of MD5 digest */ + 1];
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
return CURLE_LOGIN_DENIED;
}
/* Get the challenge. */
for(chlg64 += 4; *chlg64 == ' ' || *chlg64 == '\t'; chlg64++)
;
chlg = (unsigned char *) NULL;
chlglen = 0;
if(*chlg64 != '=') {
for(len = strlen(chlg64); len--;)
if(chlg64[len] != '\r' && chlg64[len] != '\n' && chlg64[len] != ' ' &&
chlg64[len] != '\t')
break;
if(++len) {
chlg64[len] = '\0';
result = Curl_base64_decode(chlg64, &chlg, &chlglen);
if(result)
return result;
}
}
/* Compute digest. */
ctxt = Curl_HMAC_init(Curl_HMAC_MD5,
(const unsigned char *) conn->passwd,
(unsigned int)(strlen(conn->passwd)));
if(!ctxt) {
Curl_safefree(chlg);
return CURLE_OUT_OF_MEMORY;
}
if(chlglen > 0)
Curl_HMAC_update(ctxt, chlg, (unsigned int)(chlglen));
Curl_safefree(chlg);
Curl_HMAC_final(ctxt, digest);
/* Prepare the reply. */
snprintf(reply, sizeof reply,
"%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
conn->user, digest[0], digest[1], digest[2], digest[3], digest[4],
digest[5],
digest[6], digest[7], digest[8], digest[9], digest[10], digest[11],
digest[12], digest[13], digest[14], digest[15]);
/* Encode it to base64 and send it. */
result = Curl_base64_encode(data, reply, 0, &rplyb64, &len);
if(!result) {
if(rplyb64) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", rplyb64);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(rplyb64);
}
return result;
}
#endif
#ifdef USE_NTLM
/* for the AUTH NTLM (without initial response) response. */
static CURLcode smtp_state_auth_ntlm_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
char *type1msg = NULL;
size_t len = 0;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = smtp_auth_ntlm_type1_message(conn, &type1msg, &len);
if(!result) {
if(type1msg) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", type1msg);
if(!result)
state(conn, SMTP_AUTHNTLM_TYPE2MSG);
}
Curl_safefree(type1msg);
}
}
return result;
}
/* for the NTLM type-2 response (sent in reponse to our type-1 message). */
static CURLcode smtp_state_auth_ntlm_type2msg_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
char *type3msg = NULL;
size_t len = 0;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = Curl_ntlm_decode_type2_message(data, data->state.buffer + 4,
&conn->ntlm);
if(!result) {
result = Curl_ntlm_create_type3_message(conn->data, conn->user,
conn->passwd, &conn->ntlm,
&type3msg, &len);
if(!result) {
if(type3msg) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", type3msg);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(type3msg);
}
}
}
return result;
}
#endif
/* for final responses to AUTH sequences. */
static CURLcode smtp_state_auth_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode != 235) {
failf(data, "Authentication failed: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else
state(conn, SMTP_STOP); /* End of connect phase. */
return result;
}
/* start the DO phase */
static CURLcode smtp_mail(struct connectdata *conn)
{
char *from = NULL;
char *size = NULL;
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
/* calculate the FROM parameter */
if(!data->set.str[STRING_MAIL_FROM])
/* null reverse-path, RFC-2821, sect. 3.7 */
from = strdup("<>");
else if(data->set.str[STRING_MAIL_FROM][0] == '<')
from = aprintf("%s", data->set.str[STRING_MAIL_FROM]);
else
from = aprintf("<%s>", data->set.str[STRING_MAIL_FROM]);
if(!from)
return CURLE_OUT_OF_MEMORY;
/* calculate the optional SIZE parameter */
if(conn->data->set.infilesize > 0) {
size = aprintf("%" FORMAT_OFF_T, data->set.infilesize);
if(!size) {
Curl_safefree(from);
return CURLE_OUT_OF_MEMORY;
}
}
/* send MAIL FROM */
if(!size)
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s", from);
else
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s SIZE=%s",
from, size);
Curl_safefree(size);
Curl_safefree(from);
if(result)
return result;
state(conn, SMTP_MAIL);
return result;
}
static CURLcode smtp_rcpt_to(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
/* send RCPT TO */
if(smtpc->rcpt) {
if(smtpc->rcpt->data[0] == '<')
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:%s",
smtpc->rcpt->data);
else
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:<%s>",
smtpc->rcpt->data);
if(!result)
state(conn, SMTP_RCPT);
}
return result;
}
/* for MAIL responses */
static CURLcode smtp_state_mail_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
state(conn, SMTP_STOP);
}
else {
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->rcpt = data->set.mail_rcpt;
result = smtp_rcpt_to(conn);
}
return result;
}
/* for RCPT responses */
static CURLcode smtp_state_rcpt_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
state(conn, SMTP_STOP);
}
else {
struct smtp_conn *smtpc = &conn->proto.smtpc;
if(smtpc->rcpt) {
smtpc->rcpt = smtpc->rcpt->next;
result = smtp_rcpt_to(conn);
/* if we failed or still is in RCPT sending, return */
if(result || smtpc->rcpt)
return result;
}
/* send DATA */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "DATA");
if(result)
return result;
state(conn, SMTP_DATA);
}
return result;
}
/* for the DATA response */
static CURLcode smtp_state_data_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
struct SessionHandle *data = conn->data;
struct FTP *smtp = data->state.proto.smtp;
(void)instate; /* no use for this yet */
if(smtpcode != 354) {
state(conn, SMTP_STOP);
return CURLE_RECV_ERROR;
}
/* SMTP upload */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
FIRSTSOCKET, smtp->bytecountp);
state(conn, SMTP_STOP);
return CURLE_OK;
}
/* for the POSTDATA response, which is received after the entire DATA
part has been sent off to the server */
static CURLcode smtp_state_postdata_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
(void)instate; /* no use for this yet */
if(smtpcode != 250)
result = CURLE_RECV_ERROR;
state(conn, SMTP_STOP);
return result;
}
static CURLcode smtp_statemach_act(struct connectdata *conn)
{
CURLcode result;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct SessionHandle *data = conn->data;
int smtpcode;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
size_t nread = 0;
if(smtpc->state == SMTP_UPGRADETLS)
return smtp_state_upgrade_tls(conn);
if(pp->sendleft)
/* we have a piece of a command still left to send */
return Curl_pp_flushsend(pp);
/* we read a piece of response */
result = Curl_pp_readresp(sock, pp, &smtpcode, &nread);
if(result)
return result;
if(smtpcode) {
/* we have now received a full SMTP server response */
switch(smtpc->state) {
case SMTP_SERVERGREET:
if(smtpcode/100 != 2) {
failf(data, "Got unexpected smtp-server response: %d", smtpcode);
return CURLE_FTP_WEIRD_SERVER_REPLY;
}
result = smtp_state_ehlo(conn);
if(result)
return result;
break;
case SMTP_EHLO:
result = smtp_state_ehlo_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_HELO:
result = smtp_state_helo_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_STARTTLS:
result = smtp_state_starttls_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHPLAIN:
result = smtp_state_authplain_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHLOGIN:
result = smtp_state_authlogin_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHPASSWD:
result = smtp_state_authpasswd_resp(conn, smtpcode, smtpc->state);
break;
#ifndef CURL_DISABLE_CRYPTO_AUTH
case SMTP_AUTHCRAM:
result = smtp_state_authcram_resp(conn, smtpcode, smtpc->state);
break;
#endif
#ifdef USE_NTLM
case SMTP_AUTHNTLM:
result = smtp_state_auth_ntlm_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHNTLM_TYPE2MSG:
result = smtp_state_auth_ntlm_type2msg_resp(conn, smtpcode,
smtpc->state);
break;
#endif
case SMTP_AUTH:
result = smtp_state_auth_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_MAIL:
result = smtp_state_mail_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_RCPT:
result = smtp_state_rcpt_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_DATA:
result = smtp_state_data_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_POSTDATA:
result = smtp_state_postdata_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_QUIT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, SMTP_STOP);
break;
}
}
return result;
}
/* called repeatedly until done from multi.c */
static CURLcode smtp_multi_statemach(struct connectdata *conn,
bool *done)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
CURLcode result;
if((conn->handler->flags & PROTOPT_SSL) && !smtpc->ssldone)
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
else
result = Curl_pp_multi_statemach(&smtpc->pp);
*done = (smtpc->state == SMTP_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode smtp_easy_statemach(struct connectdata *conn)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
CURLcode result = CURLE_OK;
while(smtpc->state != SMTP_STOP) {
result = Curl_pp_easy_statemach(pp);
if(result)
break;
}
return result;
}
/*
* Allocate and initialize the struct SMTP for the current SessionHandle. If
* need be.
*/
static CURLcode smtp_init(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
struct FTP *smtp = data->state.proto.smtp;
if(!smtp) {
smtp = data->state.proto.smtp = calloc(sizeof(struct FTP), 1);
if(!smtp)
return CURLE_OUT_OF_MEMORY;
}
/* get some initial data into the smtp struct */
smtp->bytecountp = &data->req.bytecount;
/* No need to duplicate user+password, the connectdata struct won't change
during a session, but we re-init them here since on subsequent inits
since the conn struct may have changed or been replaced.
*/
smtp->user = conn->user;
smtp->passwd = conn->passwd;
return CURLE_OK;
}
/*
* smtp_connect() should do everything that is to be considered a part of
* the connection phase.
*
* The variable pointed to by 'done' will be TRUE if the protocol-layer
* connect phase is done when this function returns, or FALSE if not. When
* called as a part of the easy interface, it will always be TRUE.
*/
static CURLcode smtp_connect(struct connectdata *conn,
bool *done) /* see description above */
{
CURLcode result;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct SessionHandle *data = conn->data;
struct pingpong *pp = &smtpc->pp;
const char *path = conn->data->state.path;
char localhost[HOSTNAME_MAX + 1];
*done = FALSE; /* default to not done yet */
/* If there already is a protocol-specific struct allocated for this
sessionhandle, deal with it */
Curl_reset_reqproto(conn);
result = smtp_init(conn);
if(CURLE_OK != result)
return result;
/* We always support persistent connections on smtp */
conn->bits.close = FALSE;
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = smtp_statemach_act;
pp->endofresp = smtp_endofresp;
pp->conn = conn;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
/* for SMTP over HTTP proxy */
struct HTTP http_proxy;
struct FTP *smtp_save;
/* BLOCKING */
/* We want "seamless" SMTP operations through HTTP proxy tunnel */
/* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the member
* conn->proto.http; we want SMTP through HTTP and we have to change the
* member temporarily for connecting to the HTTP proxy. After
* Curl_proxyCONNECT we have to set back the member to the original struct
* SMTP pointer
*/
smtp_save = data->state.proto.smtp;
memset(&http_proxy, 0, sizeof(http_proxy));
data->state.proto.http = &http_proxy;
result = Curl_proxyCONNECT(conn, FIRSTSOCKET,
conn->host.name, conn->remote_port);
data->state.proto.smtp = smtp_save;
if(CURLE_OK != result)
return result;
}
if((conn->handler->protocol & CURLPROTO_SMTPS) &&
data->state.used_interface != Curl_if_multi) {
/* SMTPS is simply smtp with SSL for the control channel */
/* now, perform the SSL initialization for this socket */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(result)
return result;
}
Curl_pp_init(pp); /* init the response reader stuff */
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = smtp_statemach_act;
pp->endofresp = smtp_endofresp;
pp->conn = conn;
if(!*path) {
if(!Curl_gethostname(localhost, sizeof localhost))
path = localhost;
else
path = "localhost";
}
/* url decode the path and use it as domain with EHLO */
result = Curl_urldecode(conn->data, path, 0, &smtpc->domain, NULL, TRUE);
if(result)
return result;
/* When we connect, we start in the state where we await the server greeting
*/
state(conn, SMTP_SERVERGREET);
if(data->state.used_interface == Curl_if_multi)
result = smtp_multi_statemach(conn, done);
else {
result = smtp_easy_statemach(conn);
if(!result)
*done = TRUE;
}
return result;
}
/***********************************************************************
*
* smtp_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
bool premature)
{
struct SessionHandle *data = conn->data;
struct FTP *smtp = data->state.proto.smtp;
CURLcode result = CURLE_OK;
ssize_t bytes_written;
(void)premature;
if(!smtp)
/* When the easy handle is removed from the multi while libcurl is still
* trying to resolve the host name, it seems that the smtp struct is not
* yet initialized, but the removal action calls Curl_done() which calls
* this function. So we simply return success if no smtp pointer is set.
*/
return CURLE_OK;
if(status) {
conn->bits.close = TRUE; /* marked for closure */
result = status; /* use the already set error code */
}
else
/* TODO: make this work even when the socket is EWOULDBLOCK in this
call! */
/* write to socket (send away data) */
result = Curl_write(conn,
conn->writesockfd, /* socket to send to */
SMTP_EOB, /* buffer pointer */
SMTP_EOB_LEN, /* buffer size */
&bytes_written); /* actually sent away */
if(status == CURLE_OK) {
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
pp->response = Curl_tvnow(); /* timeout relative now */
state(conn, SMTP_POSTDATA);
/* run the state-machine
TODO: when the multi interface is used, this _really_ should be using
the smtp_multi_statemach function but we have no general support for
non-blocking DONE operations, not in the multi state machine and with
Curl_done() invokes on several places in the code!
*/
result = smtp_easy_statemach(conn);
}
/* clear these for next connection */
smtp->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* smtp_perform()
*
* This is the actual DO function for SMTP. Get a file/directory according to
* the options previously setup.
*/
static
CURLcode smtp_perform(struct connectdata *conn,
bool *connected, /* connect status after PASV / PORT */
bool *dophase_done)
{
/* this is SMTP and no proxy */
CURLcode result = CURLE_OK;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(conn->data->set.opt_no_body) {
/* requested no body means no transfer... */
struct FTP *smtp = conn->data->state.proto.smtp;
smtp->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* start the first command in the DO phase */
result = smtp_mail(conn);
if(result)
return result;
/* run the state-machine */
if(conn->data->state.used_interface == Curl_if_multi)
result = smtp_multi_statemach(conn, dophase_done);
else {
result = smtp_easy_statemach(conn);
*dophase_done = TRUE; /* with the easy interface we are done here */
}
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* smtp_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (smtp_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode smtp_do(struct connectdata *conn, bool *done)
{
CURLcode retcode = CURLE_OK;
*done = FALSE; /* default to false */
/*
Since connections can be re-used between SessionHandles, this might be a
connection already existing but on a fresh SessionHandle struct so we must
make sure we have a good 'struct SMTP' to play with. For new connections,
the struct SMTP is allocated and setup in the smtp_connect() function.
*/
Curl_reset_reqproto(conn);
retcode = smtp_init(conn);
if(retcode)
return retcode;
retcode = smtp_regular_transfer(conn, done);
return retcode;
}
/***********************************************************************
*
* smtp_quit()
*
* This should be called before calling sclose(). We should then wait for the
* response from the server before returning. The calling code should then try
* to close the connection.
*
*/
static CURLcode smtp_quit(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "QUIT");
if(result)
return result;
state(conn, SMTP_QUIT);
result = smtp_easy_statemach(conn);
return result;
}
/***********************************************************************
*
* smtp_disconnect()
*
* Disconnect from an SMTP server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode smtp_disconnect(struct connectdata *conn,
bool dead_connection)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
/* We cannot send quit unconditionally. If this connection is stale or
bad in any way, sending quit and waiting around here will make the
disconnect wait in vain and cause more problems than we need to.
*/
/* The SMTP session may or may not have been allocated/setup at this
point! */
if(!dead_connection && smtpc->pp.conn)
(void)smtp_quit(conn); /* ignore errors on the LOGOUT */
Curl_pp_disconnect(&smtpc->pp);
#ifdef USE_NTLM
/* Cleanup the ntlm structure */
if(smtpc->authused == SMTP_AUTH_NTLM) {
Curl_ntlm_sspi_cleanup(&conn->ntlm);
}
#endif
/* This won't already be freed in some error cases */
Curl_safefree(smtpc->domain);
smtpc->domain = NULL;
return CURLE_OK;
}
/* call this when the DO phase has completed */
static CURLcode smtp_dophase_done(struct connectdata *conn,
bool connected)
{
struct FTP *smtp = conn->data->state.proto.smtp;
struct smtp_conn *smtpc = &conn->proto.smtpc;
(void)connected;
if(smtp->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
free(smtpc->domain);
smtpc->domain = NULL;
return CURLE_OK;
}
/* called from multi.c while DOing */
static CURLcode smtp_doing(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result;
result = smtp_multi_statemach(conn, dophase_done);
if(*dophase_done) {
result = smtp_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* smtp_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*/
static
CURLcode smtp_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result = CURLE_OK;
bool connected = FALSE;
struct SessionHandle *data = conn->data;
data->req.size = -1; /* make sure this is unknown at this point */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, 0);
Curl_pgrsSetDownloadSize(data, 0);
result = smtp_perform(conn,
&connected, /* have we connected after PASV/PORT */
dophase_done); /* all commands in the DO-phase done? */
if(CURLE_OK == result) {
if(!*dophase_done)
/* the DO phase has not completed yet */
return CURLE_OK;
result = smtp_dophase_done(conn, connected);
if(result)
return result;
}
return result;
}
static CURLcode smtp_setup_connection(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
/* Unless we have asked to tunnel smtp operations through the proxy, we
switch and use HTTP operations only */
#ifndef CURL_DISABLE_HTTP
if(conn->handler == &Curl_handler_smtp)
conn->handler = &Curl_handler_smtp_proxy;
else {
#ifdef USE_SSL
conn->handler = &Curl_handler_smtps_proxy;
#else
failf(data, "SMTPS not supported!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
/*
* We explicitly mark this connection as persistent here as we're doing
* SMTP over HTTP and thus we accidentally avoid setting this value
* otherwise.
*/
conn->bits.close = FALSE;
#else
failf(data, "SMTP over http proxy requires HTTP support built-in!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
CURLcode Curl_smtp_escape_eob(struct connectdata *conn, ssize_t nread)
{
/* When sending SMTP payload, we must detect CRLF.CRLF sequences in
* the data and make sure it is sent as CRLF..CRLF instead, as
* otherwise it will wrongly be detected as end of data by the server.
*/
ssize_t i;
ssize_t si;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct SessionHandle *data = conn->data;
if(data->state.scratch == NULL)
data->state.scratch = malloc(2 * BUFSIZE);
if(data->state.scratch == NULL) {
failf (data, "Failed to alloc scratch buffer!");
return CURLE_OUT_OF_MEMORY;
}
/* This loop can be improved by some kind of Boyer-Moore style of
approach but that is saved for later... */
for(i = 0, si = 0; i < nread; i++) {
if(SMTP_EOB[smtpc->eob] == data->req.upload_fromhere[i])
smtpc->eob++;
else if(smtpc->eob) {
/* previously a substring matched, output that first */
memcpy(&data->state.scratch[si], SMTP_EOB, smtpc->eob);
si += smtpc->eob;
/* then compare the first byte */
if(SMTP_EOB[0] == data->req.upload_fromhere[i])
smtpc->eob = 1;
else
smtpc->eob = 0;
}
if(SMTP_EOB_LEN == smtpc->eob) {
/* It matched, copy the replacement data to the target buffer
instead. Note that the replacement does not contain the
trailing CRLF but we instead continue to match on that one
to deal with repeated sequences. Like CRLF.CRLF.CRLF etc
*/
memcpy(&data->state.scratch[si], SMTP_EOB_REPL,
SMTP_EOB_REPL_LEN);
si += SMTP_EOB_REPL_LEN;
smtpc->eob = 2; /* start over at two bytes */
}
else if(!smtpc->eob)
data->state.scratch[si++] = data->req.upload_fromhere[i];
} /* for() */
if(si != nread) {
/* only use the new buffer if we replaced something */
nread = si;
/* upload from the new (replaced) buffer instead */
data->req.upload_fromhere = data->state.scratch;
/* set the new amount too */
data->req.upload_present = nread;
}
return CURLE_OK;
}
#endif /* CURL_DISABLE_SMTP */
| ./CrossVul/dataset_final_sorted/CWE-89/c/good_3567_4 |
crossvul-cpp_data_bad_3567_4 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC2821 SMTP protocol
* RFC3207 SMTP over TLS
* RFC4954 SMTP Authentication
* RFC2195 CRAM-MD5 authentication
* RFC4616 PLAIN authentication
*
***************************************************************************/
#include "setup.h"
#ifndef CURL_DISABLE_SMTP
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "if2ip.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "smtp.h"
#include "strtoofft.h"
#include "strequal.h"
#include "sslgen.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "rawstr.h"
#include "strtoofft.h"
#include "curl_base64.h"
#include "curl_md5.h"
#include "curl_hmac.h"
#include "curl_gethostname.h"
#include "curl_ntlm_msgs.h"
#include "warnless.h"
#include "http_proxy.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/* Local API functions */
static CURLcode smtp_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode smtp_do(struct connectdata *conn, bool *done);
static CURLcode smtp_done(struct connectdata *conn,
CURLcode, bool premature);
static CURLcode smtp_connect(struct connectdata *conn, bool *done);
static CURLcode smtp_disconnect(struct connectdata *conn, bool dead);
static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done);
static int smtp_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks);
static CURLcode smtp_doing(struct connectdata *conn,
bool *dophase_done);
static CURLcode smtp_setup_connection(struct connectdata * conn);
static CURLcode smtp_state_upgrade_tls(struct connectdata *conn);
/*
* SMTP protocol handler.
*/
const struct Curl_handler Curl_handler_smtp = {
"SMTP", /* scheme */
smtp_setup_connection, /* setup_connection */
smtp_do, /* do_it */
smtp_done, /* done */
ZERO_NULL, /* do_more */
smtp_connect, /* connect_it */
smtp_multi_statemach, /* connecting */
smtp_doing, /* doing */
smtp_getsock, /* proto_getsock */
smtp_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTP, /* defport */
CURLPROTO_SMTP, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */
};
#ifdef USE_SSL
/*
* SMTPS protocol handler.
*/
const struct Curl_handler Curl_handler_smtps = {
"SMTPS", /* scheme */
smtp_setup_connection, /* setup_connection */
smtp_do, /* do_it */
smtp_done, /* done */
ZERO_NULL, /* do_more */
smtp_connect, /* connect_it */
smtp_multi_statemach, /* connecting */
smtp_doing, /* doing */
smtp_getsock, /* proto_getsock */
smtp_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTPS, /* defport */
CURLPROTO_SMTP | CURLPROTO_SMTPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL
| PROTOPT_NOURLQUERY /* flags */
};
#endif
#ifndef CURL_DISABLE_HTTP
/*
* HTTP-proxyed SMTP protocol handler.
*/
static const struct Curl_handler Curl_handler_smtp_proxy = {
"SMTP", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTP, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* HTTP-proxyed SMTPS protocol handler.
*/
static const struct Curl_handler Curl_handler_smtps_proxy = {
"SMTPS", /* scheme */
ZERO_NULL, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_SMTPS, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#endif
#endif
/* Function that checks for an ending smtp status code at the start of the
given string.
As a side effect, it also flags allowed authentication mechanisms according
to EHLO AUTH response. */
static int smtp_endofresp(struct pingpong *pp, int *resp)
{
char *line = pp->linestart_resp;
size_t len = pp->nread_resp;
struct connectdata *conn = pp->conn;
struct smtp_conn *smtpc = &conn->proto.smtpc;
int result;
size_t wordlen;
if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
return FALSE; /* Nothing for us. */
if((result = (line[3] == ' ')) != 0)
*resp = curlx_sltosi(strtol(line, NULL, 10));
line += 4;
len -= 4;
if(smtpc->state == SMTP_EHLO && len >= 5 && !memcmp(line, "AUTH ", 5)) {
line += 5;
len -= 5;
for(;;) {
while(len &&
(*line == ' ' || *line == '\t' ||
*line == '\r' || *line == '\n')) {
line++;
len--;
}
if(!len)
break;
for(wordlen = 0; wordlen < len && line[wordlen] != ' ' &&
line[wordlen] != '\t' && line[wordlen] != '\r' &&
line[wordlen] != '\n';)
wordlen++;
if(wordlen == 5 && !memcmp(line, "LOGIN", 5))
smtpc->authmechs |= SMTP_AUTH_LOGIN;
else if(wordlen == 5 && !memcmp(line, "PLAIN", 5))
smtpc->authmechs |= SMTP_AUTH_PLAIN;
else if(wordlen == 8 && !memcmp(line, "CRAM-MD5", 8))
smtpc->authmechs |= SMTP_AUTH_CRAM_MD5;
else if(wordlen == 10 && !memcmp(line, "DIGEST-MD5", 10))
smtpc->authmechs |= SMTP_AUTH_DIGEST_MD5;
else if(wordlen == 6 && !memcmp(line, "GSSAPI", 6))
smtpc->authmechs |= SMTP_AUTH_GSSAPI;
else if(wordlen == 8 && !memcmp(line, "EXTERNAL", 8))
smtpc->authmechs |= SMTP_AUTH_EXTERNAL;
else if(wordlen == 4 && !memcmp(line, "NTLM", 4))
smtpc->authmechs |= SMTP_AUTH_NTLM;
line += wordlen;
len -= wordlen;
}
}
return result;
}
/* This is the ONLY way to change SMTP state! */
static void state(struct connectdata *conn,
smtpstate newstate)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[] = {
"STOP",
"SERVERGREET",
"EHLO",
"HELO",
"STARTTLS",
"UPGRADETLS",
"AUTHPLAIN",
"AUTHLOGIN",
"AUTHPASSWD",
"AUTHCRAM",
"AUTHNTLM",
"AUTHNTLM_TYPE2MSG",
"AUTH",
"MAIL",
"RCPT",
"DATA",
"POSTDATA",
"QUIT",
/* LAST */
};
if(smtpc->state != newstate)
infof(conn->data, "SMTP %p state change from %s to %s\n",
smtpc, names[smtpc->state], names[newstate]);
#endif
smtpc->state = newstate;
}
static CURLcode smtp_state_ehlo(struct connectdata *conn)
{
CURLcode result;
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->authmechs = 0; /* No known authentication mechanisms yet. */
smtpc->authused = 0; /* Clear the authentication mechanism used
for esmtp connections */
/* send EHLO */
result = Curl_pp_sendf(&smtpc->pp, "EHLO %s", smtpc->domain);
if(result)
return result;
state(conn, SMTP_EHLO);
return CURLE_OK;
}
static CURLcode smtp_state_helo(struct connectdata *conn)
{
CURLcode result;
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->authused = 0; /* No authentication mechanism used in smtp
connections */
/* send HELO */
result = Curl_pp_sendf(&smtpc->pp, "HELO %s", smtpc->domain);
if(result)
return result;
state(conn, SMTP_HELO);
return CURLE_OK;
}
static CURLcode smtp_auth_plain_data(struct connectdata *conn,
char **outptr, size_t *outlen)
{
char plainauth[2 * MAX_CURL_USER_LENGTH + MAX_CURL_PASSWORD_LENGTH];
size_t ulen;
size_t plen;
ulen = strlen(conn->user);
plen = strlen(conn->passwd);
if(2 * ulen + plen + 2 > sizeof plainauth) {
*outlen = 0;
*outptr = NULL;
return CURLE_OUT_OF_MEMORY; /* plainauth too small */
}
memcpy(plainauth, conn->user, ulen);
plainauth[ulen] = '\0';
memcpy(plainauth + ulen + 1, conn->user, ulen);
plainauth[2 * ulen + 1] = '\0';
memcpy(plainauth + 2 * ulen + 2, conn->passwd, plen);
return Curl_base64_encode(conn->data, plainauth, 2 * ulen + plen + 2,
outptr, outlen);
}
static CURLcode smtp_auth_login_user(struct connectdata *conn,
char **outptr, size_t *outlen)
{
size_t ulen = strlen(conn->user);
if(!ulen) {
*outptr = strdup("=");
if(*outptr) {
*outlen = (size_t) 1;
return CURLE_OK;
}
*outlen = 0;
return CURLE_OUT_OF_MEMORY;
}
return Curl_base64_encode(conn->data, conn->user, ulen, outptr, outlen);
}
#ifdef USE_NTLM
static CURLcode smtp_auth_ntlm_type1_message(struct connectdata *conn,
char **outptr, size_t *outlen)
{
return Curl_ntlm_create_type1_message(conn->user, conn->passwd,
&conn->ntlm, outptr, outlen);
}
#endif
static CURLcode smtp_authenticate(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
char *initresp = NULL;
const char *mech = NULL;
size_t len = 0;
smtpstate state1 = SMTP_STOP;
smtpstate state2 = SMTP_STOP;
/* Check we have a username and password to authenticate with and end the
connect phase if we don't. */
if(!conn->bits.user_passwd) {
state(conn, SMTP_STOP);
return result;
}
/* Check supported authentication mechanisms by decreasing order of
security. */
#ifndef CURL_DISABLE_CRYPTO_AUTH
if(smtpc->authmechs & SMTP_AUTH_CRAM_MD5) {
mech = "CRAM-MD5";
state1 = SMTP_AUTHCRAM;
smtpc->authused = SMTP_AUTH_CRAM_MD5;
}
else
#endif
#ifdef USE_NTLM
if(smtpc->authmechs & SMTP_AUTH_NTLM) {
mech = "NTLM";
state1 = SMTP_AUTHNTLM;
state2 = SMTP_AUTHNTLM_TYPE2MSG;
smtpc->authused = SMTP_AUTH_NTLM;
result = smtp_auth_ntlm_type1_message(conn, &initresp, &len);
}
else
#endif
if(smtpc->authmechs & SMTP_AUTH_LOGIN) {
mech = "LOGIN";
state1 = SMTP_AUTHLOGIN;
state2 = SMTP_AUTHPASSWD;
smtpc->authused = SMTP_AUTH_LOGIN;
result = smtp_auth_login_user(conn, &initresp, &len);
}
else if(smtpc->authmechs & SMTP_AUTH_PLAIN) {
mech = "PLAIN";
state1 = SMTP_AUTHPLAIN;
state2 = SMTP_AUTH;
smtpc->authused = SMTP_AUTH_PLAIN;
result = smtp_auth_plain_data(conn, &initresp, &len);
}
else {
infof(conn->data, "No known auth mechanisms supported!\n");
result = CURLE_LOGIN_DENIED; /* Other mechanisms not supported. */
}
if(!result) {
if(initresp &&
strlen(mech) + len <= 512 - 8) { /* AUTH <mech> ...<crlf> */
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s %s", mech, initresp);
if(!result)
state(conn, state2);
}
else {
result = Curl_pp_sendf(&smtpc->pp, "AUTH %s", mech);
if(!result)
state(conn, state1);
}
Curl_safefree(initresp);
}
return result;
}
/* For the SMTP "protocol connect" and "doing" phases only */
static int smtp_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.smtpc.pp, socks, numsocks);
}
#ifdef USE_SSL
static void smtp_to_smtps(struct connectdata *conn)
{
conn->handler = &Curl_handler_smtps;
}
#else
#define smtp_to_smtps(x) Curl_nop_stmt
#endif
/* for STARTTLS responses */
static CURLcode smtp_state_starttls_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode != 220) {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied. %c", smtpcode);
result = CURLE_USE_SSL_FAILED;
}
else
result = smtp_authenticate(conn);
}
else {
if(data->state.used_interface == Curl_if_multi) {
state(conn, SMTP_UPGRADETLS);
return smtp_state_upgrade_tls(conn);
}
else {
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(CURLE_OK == result) {
smtp_to_smtps(conn);
result = smtp_state_ehlo(conn);
}
}
}
return result;
}
static CURLcode smtp_state_upgrade_tls(struct connectdata *conn)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
CURLcode result;
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
if(smtpc->ssldone) {
smtp_to_smtps(conn);
result = smtp_state_ehlo(conn);
}
return result;
}
/* for EHLO responses */
static CURLcode smtp_state_ehlo_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
if((data->set.use_ssl <= CURLUSESSL_TRY || conn->ssl[FIRSTSOCKET].use) &&
!conn->bits.user_passwd)
result = smtp_state_helo(conn);
else {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
}
else if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested. Switch
to TLS connection now */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "STARTTLS");
state(conn, SMTP_STARTTLS);
}
else
result = smtp_authenticate(conn);
return result;
}
/* for HELO responses */
static CURLcode smtp_state_helo_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
/* end the connect phase */
state(conn, SMTP_STOP);
}
return result;
}
/* for AUTH PLAIN (without initial response) responses */
static CURLcode smtp_state_authplain_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
size_t len = 0;
char *plainauth = NULL;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = smtp_auth_plain_data(conn, &plainauth, &len);
if(!result) {
if(plainauth) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", plainauth);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(plainauth);
}
}
return result;
}
/* for AUTH LOGIN (without initial response) responses */
static CURLcode smtp_state_authlogin_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
size_t len = 0;
char *authuser = NULL;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = smtp_auth_login_user(conn, &authuser, &len);
if(!result) {
if(authuser) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", authuser);
if(!result)
state(conn, SMTP_AUTHPASSWD);
}
Curl_safefree(authuser);
}
}
return result;
}
/* for responses to user entry of AUTH LOGIN. */
static CURLcode smtp_state_authpasswd_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
size_t plen;
size_t len = 0;
char *authpasswd = NULL;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
plen = strlen(conn->passwd);
if(!plen)
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "=");
else {
result = Curl_base64_encode(data, conn->passwd, plen, &authpasswd, &len);
if(!result) {
if(authpasswd) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", authpasswd);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(authpasswd);
}
}
}
return result;
}
#ifndef CURL_DISABLE_CRYPTO_AUTH
/* for AUTH CRAM-MD5 responses. */
static CURLcode smtp_state_authcram_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
char * chlg64 = data->state.buffer;
unsigned char * chlg;
size_t chlglen;
size_t len = 0;
char *rplyb64 = NULL;
HMAC_context *ctxt;
unsigned char digest[16];
char reply[MAX_CURL_USER_LENGTH + 32 /* 2 * size of MD5 digest */ + 1];
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
return CURLE_LOGIN_DENIED;
}
/* Get the challenge. */
for(chlg64 += 4; *chlg64 == ' ' || *chlg64 == '\t'; chlg64++)
;
chlg = (unsigned char *) NULL;
chlglen = 0;
if(*chlg64 != '=') {
for(len = strlen(chlg64); len--;)
if(chlg64[len] != '\r' && chlg64[len] != '\n' && chlg64[len] != ' ' &&
chlg64[len] != '\t')
break;
if(++len) {
chlg64[len] = '\0';
result = Curl_base64_decode(chlg64, &chlg, &chlglen);
if(result)
return result;
}
}
/* Compute digest. */
ctxt = Curl_HMAC_init(Curl_HMAC_MD5,
(const unsigned char *) conn->passwd,
(unsigned int)(strlen(conn->passwd)));
if(!ctxt) {
Curl_safefree(chlg);
return CURLE_OUT_OF_MEMORY;
}
if(chlglen > 0)
Curl_HMAC_update(ctxt, chlg, (unsigned int)(chlglen));
Curl_safefree(chlg);
Curl_HMAC_final(ctxt, digest);
/* Prepare the reply. */
snprintf(reply, sizeof reply,
"%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
conn->user, digest[0], digest[1], digest[2], digest[3], digest[4],
digest[5],
digest[6], digest[7], digest[8], digest[9], digest[10], digest[11],
digest[12], digest[13], digest[14], digest[15]);
/* Encode it to base64 and send it. */
result = Curl_base64_encode(data, reply, 0, &rplyb64, &len);
if(!result) {
if(rplyb64) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", rplyb64);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(rplyb64);
}
return result;
}
#endif
#ifdef USE_NTLM
/* for the AUTH NTLM (without initial response) response. */
static CURLcode smtp_state_auth_ntlm_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
char *type1msg = NULL;
size_t len = 0;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = smtp_auth_ntlm_type1_message(conn, &type1msg, &len);
if(!result) {
if(type1msg) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", type1msg);
if(!result)
state(conn, SMTP_AUTHNTLM_TYPE2MSG);
}
Curl_safefree(type1msg);
}
}
return result;
}
/* for the NTLM type-2 response (sent in reponse to our type-1 message). */
static CURLcode smtp_state_auth_ntlm_type2msg_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
char *type3msg = NULL;
size_t len = 0;
(void)instate; /* no use for this yet */
if(smtpcode != 334) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else {
result = Curl_ntlm_decode_type2_message(data, data->state.buffer + 4,
&conn->ntlm);
if(!result) {
result = Curl_ntlm_create_type3_message(conn->data, conn->user,
conn->passwd, &conn->ntlm,
&type3msg, &len);
if(!result) {
if(type3msg) {
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", type3msg);
if(!result)
state(conn, SMTP_AUTH);
}
Curl_safefree(type3msg);
}
}
}
return result;
}
#endif
/* for final responses to AUTH sequences. */
static CURLcode smtp_state_auth_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode != 235) {
failf(data, "Authentication failed: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
}
else
state(conn, SMTP_STOP); /* End of connect phase. */
return result;
}
/* start the DO phase */
static CURLcode smtp_mail(struct connectdata *conn)
{
char *from = NULL;
char *size = NULL;
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
/* calculate the FROM parameter */
if(!data->set.str[STRING_MAIL_FROM])
/* null reverse-path, RFC-2821, sect. 3.7 */
from = strdup("<>");
else if(data->set.str[STRING_MAIL_FROM][0] == '<')
from = aprintf("%s", data->set.str[STRING_MAIL_FROM]);
else
from = aprintf("<%s>", data->set.str[STRING_MAIL_FROM]);
if(!from)
return CURLE_OUT_OF_MEMORY;
/* calculate the optional SIZE parameter */
if(conn->data->set.infilesize > 0) {
size = aprintf("%" FORMAT_OFF_T, data->set.infilesize);
if(!size) {
Curl_safefree(from);
return CURLE_OUT_OF_MEMORY;
}
}
/* send MAIL FROM */
if(!size)
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s", from);
else
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s SIZE=%s",
from, size);
Curl_safefree(size);
Curl_safefree(from);
if(result)
return result;
state(conn, SMTP_MAIL);
return result;
}
static CURLcode smtp_rcpt_to(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct smtp_conn *smtpc = &conn->proto.smtpc;
/* send RCPT TO */
if(smtpc->rcpt) {
if(smtpc->rcpt->data[0] == '<')
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:%s",
smtpc->rcpt->data);
else
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:<%s>",
smtpc->rcpt->data);
if(!result)
state(conn, SMTP_RCPT);
}
return result;
}
/* for MAIL responses */
static CURLcode smtp_state_mail_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
state(conn, SMTP_STOP);
}
else {
struct smtp_conn *smtpc = &conn->proto.smtpc;
smtpc->rcpt = data->set.mail_rcpt;
result = smtp_rcpt_to(conn);
}
return result;
}
/* for RCPT responses */
static CURLcode smtp_state_rcpt_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode/100 != 2) {
failf(data, "Access denied: %d", smtpcode);
result = CURLE_LOGIN_DENIED;
state(conn, SMTP_STOP);
}
else {
struct smtp_conn *smtpc = &conn->proto.smtpc;
if(smtpc->rcpt) {
smtpc->rcpt = smtpc->rcpt->next;
result = smtp_rcpt_to(conn);
/* if we failed or still is in RCPT sending, return */
if(result || smtpc->rcpt)
return result;
}
/* send DATA */
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "DATA");
if(result)
return result;
state(conn, SMTP_DATA);
}
return result;
}
/* for the DATA response */
static CURLcode smtp_state_data_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
struct SessionHandle *data = conn->data;
struct FTP *smtp = data->state.proto.smtp;
(void)instate; /* no use for this yet */
if(smtpcode != 354) {
state(conn, SMTP_STOP);
return CURLE_RECV_ERROR;
}
/* SMTP upload */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
FIRSTSOCKET, smtp->bytecountp);
state(conn, SMTP_STOP);
return CURLE_OK;
}
/* for the POSTDATA response, which is received after the entire DATA
part has been sent off to the server */
static CURLcode smtp_state_postdata_resp(struct connectdata *conn,
int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
(void)instate; /* no use for this yet */
if(smtpcode != 250)
result = CURLE_RECV_ERROR;
state(conn, SMTP_STOP);
return result;
}
static CURLcode smtp_statemach_act(struct connectdata *conn)
{
CURLcode result;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
struct SessionHandle *data = conn->data;
int smtpcode;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
size_t nread = 0;
if(smtpc->state == SMTP_UPGRADETLS)
return smtp_state_upgrade_tls(conn);
if(pp->sendleft)
/* we have a piece of a command still left to send */
return Curl_pp_flushsend(pp);
/* we read a piece of response */
result = Curl_pp_readresp(sock, pp, &smtpcode, &nread);
if(result)
return result;
if(smtpcode) {
/* we have now received a full SMTP server response */
switch(smtpc->state) {
case SMTP_SERVERGREET:
if(smtpcode/100 != 2) {
failf(data, "Got unexpected smtp-server response: %d", smtpcode);
return CURLE_FTP_WEIRD_SERVER_REPLY;
}
result = smtp_state_ehlo(conn);
if(result)
return result;
break;
case SMTP_EHLO:
result = smtp_state_ehlo_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_HELO:
result = smtp_state_helo_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_STARTTLS:
result = smtp_state_starttls_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHPLAIN:
result = smtp_state_authplain_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHLOGIN:
result = smtp_state_authlogin_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHPASSWD:
result = smtp_state_authpasswd_resp(conn, smtpcode, smtpc->state);
break;
#ifndef CURL_DISABLE_CRYPTO_AUTH
case SMTP_AUTHCRAM:
result = smtp_state_authcram_resp(conn, smtpcode, smtpc->state);
break;
#endif
#ifdef USE_NTLM
case SMTP_AUTHNTLM:
result = smtp_state_auth_ntlm_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_AUTHNTLM_TYPE2MSG:
result = smtp_state_auth_ntlm_type2msg_resp(conn, smtpcode,
smtpc->state);
break;
#endif
case SMTP_AUTH:
result = smtp_state_auth_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_MAIL:
result = smtp_state_mail_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_RCPT:
result = smtp_state_rcpt_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_DATA:
result = smtp_state_data_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_POSTDATA:
result = smtp_state_postdata_resp(conn, smtpcode, smtpc->state);
break;
case SMTP_QUIT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, SMTP_STOP);
break;
}
}
return result;
}
/* called repeatedly until done from multi.c */
static CURLcode smtp_multi_statemach(struct connectdata *conn,
bool *done)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
CURLcode result;
if((conn->handler->flags & PROTOPT_SSL) && !smtpc->ssldone)
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone);
else
result = Curl_pp_multi_statemach(&smtpc->pp);
*done = (smtpc->state == SMTP_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode smtp_easy_statemach(struct connectdata *conn)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
CURLcode result = CURLE_OK;
while(smtpc->state != SMTP_STOP) {
result = Curl_pp_easy_statemach(pp);
if(result)
break;
}
return result;
}
/*
* Allocate and initialize the struct SMTP for the current SessionHandle. If
* need be.
*/
static CURLcode smtp_init(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
struct FTP *smtp = data->state.proto.smtp;
if(!smtp) {
smtp = data->state.proto.smtp = calloc(sizeof(struct FTP), 1);
if(!smtp)
return CURLE_OUT_OF_MEMORY;
}
/* get some initial data into the smtp struct */
smtp->bytecountp = &data->req.bytecount;
/* No need to duplicate user+password, the connectdata struct won't change
during a session, but we re-init them here since on subsequent inits
since the conn struct may have changed or been replaced.
*/
smtp->user = conn->user;
smtp->passwd = conn->passwd;
return CURLE_OK;
}
/*
* smtp_connect() should do everything that is to be considered a part of
* the connection phase.
*
* The variable pointed to by 'done' will be TRUE if the protocol-layer
* connect phase is done when this function returns, or FALSE if not. When
* called as a part of the easy interface, it will always be TRUE.
*/
static CURLcode smtp_connect(struct connectdata *conn,
bool *done) /* see description above */
{
CURLcode result;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct SessionHandle *data = conn->data;
struct pingpong *pp = &smtpc->pp;
const char *path = conn->data->state.path;
int len;
char localhost[HOSTNAME_MAX + 1];
*done = FALSE; /* default to not done yet */
/* If there already is a protocol-specific struct allocated for this
sessionhandle, deal with it */
Curl_reset_reqproto(conn);
result = smtp_init(conn);
if(CURLE_OK != result)
return result;
/* We always support persistent connections on smtp */
conn->bits.close = FALSE;
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = smtp_statemach_act;
pp->endofresp = smtp_endofresp;
pp->conn = conn;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
/* for SMTP over HTTP proxy */
struct HTTP http_proxy;
struct FTP *smtp_save;
/* BLOCKING */
/* We want "seamless" SMTP operations through HTTP proxy tunnel */
/* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the member
* conn->proto.http; we want SMTP through HTTP and we have to change the
* member temporarily for connecting to the HTTP proxy. After
* Curl_proxyCONNECT we have to set back the member to the original struct
* SMTP pointer
*/
smtp_save = data->state.proto.smtp;
memset(&http_proxy, 0, sizeof(http_proxy));
data->state.proto.http = &http_proxy;
result = Curl_proxyCONNECT(conn, FIRSTSOCKET,
conn->host.name, conn->remote_port);
data->state.proto.smtp = smtp_save;
if(CURLE_OK != result)
return result;
}
if((conn->handler->protocol & CURLPROTO_SMTPS) &&
data->state.used_interface != Curl_if_multi) {
/* SMTPS is simply smtp with SSL for the control channel */
/* now, perform the SSL initialization for this socket */
result = Curl_ssl_connect(conn, FIRSTSOCKET);
if(result)
return result;
}
Curl_pp_init(pp); /* init the response reader stuff */
pp->response_time = RESP_TIMEOUT; /* set default response time-out */
pp->statemach_act = smtp_statemach_act;
pp->endofresp = smtp_endofresp;
pp->conn = conn;
if(!*path) {
if(!Curl_gethostname(localhost, sizeof localhost))
path = localhost;
else
path = "localhost";
}
/* url decode the path and use it as domain with EHLO */
smtpc->domain = curl_easy_unescape(conn->data, path, 0, &len);
if(!smtpc->domain)
return CURLE_OUT_OF_MEMORY;
/* When we connect, we start in the state where we await the server greeting
*/
state(conn, SMTP_SERVERGREET);
if(data->state.used_interface == Curl_if_multi)
result = smtp_multi_statemach(conn, done);
else {
result = smtp_easy_statemach(conn);
if(!result)
*done = TRUE;
}
return result;
}
/***********************************************************************
*
* smtp_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
bool premature)
{
struct SessionHandle *data = conn->data;
struct FTP *smtp = data->state.proto.smtp;
CURLcode result = CURLE_OK;
ssize_t bytes_written;
(void)premature;
if(!smtp)
/* When the easy handle is removed from the multi while libcurl is still
* trying to resolve the host name, it seems that the smtp struct is not
* yet initialized, but the removal action calls Curl_done() which calls
* this function. So we simply return success if no smtp pointer is set.
*/
return CURLE_OK;
if(status) {
conn->bits.close = TRUE; /* marked for closure */
result = status; /* use the already set error code */
}
else
/* TODO: make this work even when the socket is EWOULDBLOCK in this
call! */
/* write to socket (send away data) */
result = Curl_write(conn,
conn->writesockfd, /* socket to send to */
SMTP_EOB, /* buffer pointer */
SMTP_EOB_LEN, /* buffer size */
&bytes_written); /* actually sent away */
if(status == CURLE_OK) {
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct pingpong *pp = &smtpc->pp;
pp->response = Curl_tvnow(); /* timeout relative now */
state(conn, SMTP_POSTDATA);
/* run the state-machine
TODO: when the multi interface is used, this _really_ should be using
the smtp_multi_statemach function but we have no general support for
non-blocking DONE operations, not in the multi state machine and with
Curl_done() invokes on several places in the code!
*/
result = smtp_easy_statemach(conn);
}
/* clear these for next connection */
smtp->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* smtp_perform()
*
* This is the actual DO function for SMTP. Get a file/directory according to
* the options previously setup.
*/
static
CURLcode smtp_perform(struct connectdata *conn,
bool *connected, /* connect status after PASV / PORT */
bool *dophase_done)
{
/* this is SMTP and no proxy */
CURLcode result = CURLE_OK;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(conn->data->set.opt_no_body) {
/* requested no body means no transfer... */
struct FTP *smtp = conn->data->state.proto.smtp;
smtp->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* start the first command in the DO phase */
result = smtp_mail(conn);
if(result)
return result;
/* run the state-machine */
if(conn->data->state.used_interface == Curl_if_multi)
result = smtp_multi_statemach(conn, dophase_done);
else {
result = smtp_easy_statemach(conn);
*dophase_done = TRUE; /* with the easy interface we are done here */
}
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* smtp_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (smtp_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode smtp_do(struct connectdata *conn, bool *done)
{
CURLcode retcode = CURLE_OK;
*done = FALSE; /* default to false */
/*
Since connections can be re-used between SessionHandles, this might be a
connection already existing but on a fresh SessionHandle struct so we must
make sure we have a good 'struct SMTP' to play with. For new connections,
the struct SMTP is allocated and setup in the smtp_connect() function.
*/
Curl_reset_reqproto(conn);
retcode = smtp_init(conn);
if(retcode)
return retcode;
retcode = smtp_regular_transfer(conn, done);
return retcode;
}
/***********************************************************************
*
* smtp_quit()
*
* This should be called before calling sclose(). We should then wait for the
* response from the server before returning. The calling code should then try
* to close the connection.
*
*/
static CURLcode smtp_quit(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
result = Curl_pp_sendf(&conn->proto.smtpc.pp, "QUIT");
if(result)
return result;
state(conn, SMTP_QUIT);
result = smtp_easy_statemach(conn);
return result;
}
/***********************************************************************
*
* smtp_disconnect()
*
* Disconnect from an SMTP server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode smtp_disconnect(struct connectdata *conn,
bool dead_connection)
{
struct smtp_conn *smtpc = &conn->proto.smtpc;
/* We cannot send quit unconditionally. If this connection is stale or
bad in any way, sending quit and waiting around here will make the
disconnect wait in vain and cause more problems than we need to.
*/
/* The SMTP session may or may not have been allocated/setup at this
point! */
if(!dead_connection && smtpc->pp.conn)
(void)smtp_quit(conn); /* ignore errors on the LOGOUT */
Curl_pp_disconnect(&smtpc->pp);
#ifdef USE_NTLM
/* Cleanup the ntlm structure */
if(smtpc->authused == SMTP_AUTH_NTLM) {
Curl_ntlm_sspi_cleanup(&conn->ntlm);
}
#endif
/* This won't already be freed in some error cases */
Curl_safefree(smtpc->domain);
smtpc->domain = NULL;
return CURLE_OK;
}
/* call this when the DO phase has completed */
static CURLcode smtp_dophase_done(struct connectdata *conn,
bool connected)
{
struct FTP *smtp = conn->data->state.proto.smtp;
struct smtp_conn *smtpc = &conn->proto.smtpc;
(void)connected;
if(smtp->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
free(smtpc->domain);
smtpc->domain = NULL;
return CURLE_OK;
}
/* called from multi.c while DOing */
static CURLcode smtp_doing(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result;
result = smtp_multi_statemach(conn, dophase_done);
if(*dophase_done) {
result = smtp_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* smtp_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*/
static
CURLcode smtp_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result = CURLE_OK;
bool connected = FALSE;
struct SessionHandle *data = conn->data;
data->req.size = -1; /* make sure this is unknown at this point */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, 0);
Curl_pgrsSetDownloadSize(data, 0);
result = smtp_perform(conn,
&connected, /* have we connected after PASV/PORT */
dophase_done); /* all commands in the DO-phase done? */
if(CURLE_OK == result) {
if(!*dophase_done)
/* the DO phase has not completed yet */
return CURLE_OK;
result = smtp_dophase_done(conn, connected);
if(result)
return result;
}
return result;
}
static CURLcode smtp_setup_connection(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
/* Unless we have asked to tunnel smtp operations through the proxy, we
switch and use HTTP operations only */
#ifndef CURL_DISABLE_HTTP
if(conn->handler == &Curl_handler_smtp)
conn->handler = &Curl_handler_smtp_proxy;
else {
#ifdef USE_SSL
conn->handler = &Curl_handler_smtps_proxy;
#else
failf(data, "SMTPS not supported!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
/*
* We explicitly mark this connection as persistent here as we're doing
* SMTP over HTTP and thus we accidentally avoid setting this value
* otherwise.
*/
conn->bits.close = FALSE;
#else
failf(data, "SMTP over http proxy requires HTTP support built-in!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
CURLcode Curl_smtp_escape_eob(struct connectdata *conn, ssize_t nread)
{
/* When sending SMTP payload, we must detect CRLF.CRLF sequences in
* the data and make sure it is sent as CRLF..CRLF instead, as
* otherwise it will wrongly be detected as end of data by the server.
*/
ssize_t i;
ssize_t si;
struct smtp_conn *smtpc = &conn->proto.smtpc;
struct SessionHandle *data = conn->data;
if(data->state.scratch == NULL)
data->state.scratch = malloc(2 * BUFSIZE);
if(data->state.scratch == NULL) {
failf (data, "Failed to alloc scratch buffer!");
return CURLE_OUT_OF_MEMORY;
}
/* This loop can be improved by some kind of Boyer-Moore style of
approach but that is saved for later... */
for(i = 0, si = 0; i < nread; i++) {
if(SMTP_EOB[smtpc->eob] == data->req.upload_fromhere[i])
smtpc->eob++;
else if(smtpc->eob) {
/* previously a substring matched, output that first */
memcpy(&data->state.scratch[si], SMTP_EOB, smtpc->eob);
si += smtpc->eob;
/* then compare the first byte */
if(SMTP_EOB[0] == data->req.upload_fromhere[i])
smtpc->eob = 1;
else
smtpc->eob = 0;
}
if(SMTP_EOB_LEN == smtpc->eob) {
/* It matched, copy the replacement data to the target buffer
instead. Note that the replacement does not contain the
trailing CRLF but we instead continue to match on that one
to deal with repeated sequences. Like CRLF.CRLF.CRLF etc
*/
memcpy(&data->state.scratch[si], SMTP_EOB_REPL,
SMTP_EOB_REPL_LEN);
si += SMTP_EOB_REPL_LEN;
smtpc->eob = 2; /* start over at two bytes */
}
else if(!smtpc->eob)
data->state.scratch[si++] = data->req.upload_fromhere[i];
} /* for() */
if(si != nread) {
/* only use the new buffer if we replaced something */
nread = si;
/* upload from the new (replaced) buffer instead */
data->req.upload_fromhere = data->state.scratch;
/* set the new amount too */
data->req.upload_present = nread;
}
return CURLE_OK;
}
#endif /* CURL_DISABLE_SMTP */
| ./CrossVul/dataset_final_sorted/CWE-89/c/bad_3567_4 |
crossvul-cpp_data_good_513_0 | /* $OpenBSD: scp.c,v 1.198 2018/11/16 03:03:10 djm Exp $ */
/*
* scp - secure remote copy. This is basically patched BSD rcp which
* uses ssh to do the data transfer (instead of using rcmd).
*
* NOTE: This version should NOT be suid root. (This uses ssh to
* do the transfer and ssh has the necessary privileges.)
*
* 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
*
* As far as I am concerned, the code I have written for this software
* can be used freely for any purpose. Any derived versions of this
* software must be clearly marked as such, and if the derived work is
* incompatible with the protocol description in the RFC file, it must be
* called by a name other than "ssh" or "Secure Shell".
*/
/*
* Copyright (c) 1999 Theo de Raadt. All rights reserved.
* Copyright (c) 1999 Aaron Campbell. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Parts from:
*
* Copyright (c) 1983, 1990, 1992, 1993, 1995
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include "includes.h"
#include <sys/types.h>
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_POLL_H
#include <poll.h>
#else
# ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
# endif
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <sys/wait.h>
#include <sys/uio.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <locale.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
#include <vis.h>
#endif
#include "xmalloc.h"
#include "ssh.h"
#include "atomicio.h"
#include "pathnames.h"
#include "log.h"
#include "misc.h"
#include "progressmeter.h"
#include "utf8.h"
extern char *__progname;
#define COPY_BUFLEN 16384
int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
/* Struct for addargs */
arglist args;
arglist remote_remote_args;
/* Bandwidth limit */
long long limit_kbps = 0;
struct bwlimit bwlimit;
/* Name of current file being transferred. */
char *curfile;
/* This is set to non-zero to enable verbose mode. */
int verbose_mode = 0;
/* This is set to zero if the progressmeter is not desired. */
int showprogress = 1;
/*
* This is set to non-zero if remote-remote copy should be piped
* through this process.
*/
int throughlocal = 0;
/* Non-standard port to use for the ssh connection or -1. */
int sshport = -1;
/* This is the program to execute for the secured connection. ("ssh" or -S) */
char *ssh_program = _PATH_SSH_PROGRAM;
/* This is used to store the pid of ssh_program */
pid_t do_cmd_pid = -1;
static void
killchild(int signo)
{
if (do_cmd_pid > 1) {
kill(do_cmd_pid, signo ? signo : SIGTERM);
waitpid(do_cmd_pid, NULL, 0);
}
if (signo)
_exit(1);
exit(1);
}
static void
suspchild(int signo)
{
int status;
if (do_cmd_pid > 1) {
kill(do_cmd_pid, signo);
while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
errno == EINTR)
;
kill(getpid(), SIGSTOP);
}
}
static int
do_local_cmd(arglist *a)
{
u_int i;
int status;
pid_t pid;
if (a->num == 0)
fatal("do_local_cmd: no arguments");
if (verbose_mode) {
fprintf(stderr, "Executing:");
for (i = 0; i < a->num; i++)
fmprintf(stderr, " %s", a->list[i]);
fprintf(stderr, "\n");
}
if ((pid = fork()) == -1)
fatal("do_local_cmd: fork: %s", strerror(errno));
if (pid == 0) {
execvp(a->list[0], a->list);
perror(a->list[0]);
exit(1);
}
do_cmd_pid = pid;
signal(SIGTERM, killchild);
signal(SIGINT, killchild);
signal(SIGHUP, killchild);
while (waitpid(pid, &status, 0) == -1)
if (errno != EINTR)
fatal("do_local_cmd: waitpid: %s", strerror(errno));
do_cmd_pid = -1;
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
return (-1);
return (0);
}
/*
* This function executes the given command as the specified user on the
* given host. This returns < 0 if execution fails, and >= 0 otherwise. This
* assigns the input and output file descriptors on success.
*/
int
do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
{
int pin[2], pout[2], reserved[2];
if (verbose_mode)
fmprintf(stderr,
"Executing: program %s host %s, user %s, command %s\n",
ssh_program, host,
remuser ? remuser : "(unspecified)", cmd);
if (port == -1)
port = sshport;
/*
* Reserve two descriptors so that the real pipes won't get
* descriptors 0 and 1 because that will screw up dup2 below.
*/
if (pipe(reserved) < 0)
fatal("pipe: %s", strerror(errno));
/* Create a socket pair for communicating with ssh. */
if (pipe(pin) < 0)
fatal("pipe: %s", strerror(errno));
if (pipe(pout) < 0)
fatal("pipe: %s", strerror(errno));
/* Free the reserved descriptors. */
close(reserved[0]);
close(reserved[1]);
signal(SIGTSTP, suspchild);
signal(SIGTTIN, suspchild);
signal(SIGTTOU, suspchild);
/* Fork a child to execute the command on the remote host using ssh. */
do_cmd_pid = fork();
if (do_cmd_pid == 0) {
/* Child. */
close(pin[1]);
close(pout[0]);
dup2(pin[0], 0);
dup2(pout[1], 1);
close(pin[0]);
close(pout[1]);
replacearg(&args, 0, "%s", ssh_program);
if (port != -1) {
addargs(&args, "-p");
addargs(&args, "%d", port);
}
if (remuser != NULL) {
addargs(&args, "-l");
addargs(&args, "%s", remuser);
}
addargs(&args, "--");
addargs(&args, "%s", host);
addargs(&args, "%s", cmd);
execvp(ssh_program, args.list);
perror(ssh_program);
exit(1);
} else if (do_cmd_pid == -1) {
fatal("fork: %s", strerror(errno));
}
/* Parent. Close the other side, and return the local side. */
close(pin[0]);
*fdout = pin[1];
close(pout[1]);
*fdin = pout[0];
signal(SIGTERM, killchild);
signal(SIGINT, killchild);
signal(SIGHUP, killchild);
return 0;
}
/*
* This function executes a command similar to do_cmd(), but expects the
* input and output descriptors to be setup by a previous call to do_cmd().
* This way the input and output of two commands can be connected.
*/
int
do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
{
pid_t pid;
int status;
if (verbose_mode)
fmprintf(stderr,
"Executing: 2nd program %s host %s, user %s, command %s\n",
ssh_program, host,
remuser ? remuser : "(unspecified)", cmd);
if (port == -1)
port = sshport;
/* Fork a child to execute the command on the remote host using ssh. */
pid = fork();
if (pid == 0) {
dup2(fdin, 0);
dup2(fdout, 1);
replacearg(&args, 0, "%s", ssh_program);
if (port != -1) {
addargs(&args, "-p");
addargs(&args, "%d", port);
}
if (remuser != NULL) {
addargs(&args, "-l");
addargs(&args, "%s", remuser);
}
addargs(&args, "--");
addargs(&args, "%s", host);
addargs(&args, "%s", cmd);
execvp(ssh_program, args.list);
perror(ssh_program);
exit(1);
} else if (pid == -1) {
fatal("fork: %s", strerror(errno));
}
while (waitpid(pid, &status, 0) == -1)
if (errno != EINTR)
fatal("do_cmd2: waitpid: %s", strerror(errno));
return 0;
}
typedef struct {
size_t cnt;
char *buf;
} BUF;
BUF *allocbuf(BUF *, int, int);
void lostconn(int);
int okname(char *);
void run_err(const char *,...);
void verifydir(char *);
struct passwd *pwd;
uid_t userid;
int errs, remin, remout;
int pflag, iamremote, iamrecursive, targetshouldbedirectory;
#define CMDNEEDS 64
char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
int response(void);
void rsource(char *, struct stat *);
void sink(int, char *[]);
void source(int, char *[]);
void tolocal(int, char *[]);
void toremote(int, char *[]);
void usage(void);
int
main(int argc, char **argv)
{
int ch, fflag, tflag, status, n;
char **newargv;
const char *errstr;
extern char *optarg;
extern int optind;
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
msetlocale();
/* Copy argv, because we modify it */
newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
for (n = 0; n < argc; n++)
newargv[n] = xstrdup(argv[n]);
argv = newargv;
__progname = ssh_get_progname(argv[0]);
memset(&args, '\0', sizeof(args));
memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
args.list = remote_remote_args.list = NULL;
addargs(&args, "%s", ssh_program);
addargs(&args, "-x");
addargs(&args, "-oForwardAgent=no");
addargs(&args, "-oPermitLocalCommand=no");
addargs(&args, "-oClearAllForwardings=yes");
addargs(&args, "-oRemoteCommand=none");
addargs(&args, "-oRequestTTY=no");
fflag = tflag = 0;
while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
switch (ch) {
/* User-visible flags. */
case '1':
fatal("SSH protocol v.1 is no longer supported");
break;
case '2':
/* Ignored */
break;
case '4':
case '6':
case 'C':
addargs(&args, "-%c", ch);
addargs(&remote_remote_args, "-%c", ch);
break;
case '3':
throughlocal = 1;
break;
case 'o':
case 'c':
case 'i':
case 'F':
addargs(&remote_remote_args, "-%c", ch);
addargs(&remote_remote_args, "%s", optarg);
addargs(&args, "-%c", ch);
addargs(&args, "%s", optarg);
break;
case 'P':
sshport = a2port(optarg);
if (sshport <= 0)
fatal("bad port \"%s\"\n", optarg);
break;
case 'B':
addargs(&remote_remote_args, "-oBatchmode=yes");
addargs(&args, "-oBatchmode=yes");
break;
case 'l':
limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
&errstr);
if (errstr != NULL)
usage();
limit_kbps *= 1024; /* kbps */
bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
break;
case 'p':
pflag = 1;
break;
case 'r':
iamrecursive = 1;
break;
case 'S':
ssh_program = xstrdup(optarg);
break;
case 'v':
addargs(&args, "-v");
addargs(&remote_remote_args, "-v");
verbose_mode = 1;
break;
case 'q':
addargs(&args, "-q");
addargs(&remote_remote_args, "-q");
showprogress = 0;
break;
/* Server options. */
case 'd':
targetshouldbedirectory = 1;
break;
case 'f': /* "from" */
iamremote = 1;
fflag = 1;
break;
case 't': /* "to" */
iamremote = 1;
tflag = 1;
#ifdef HAVE_CYGWIN
setmode(0, O_BINARY);
#endif
break;
default:
usage();
}
argc -= optind;
argv += optind;
if ((pwd = getpwuid(userid = getuid())) == NULL)
fatal("unknown user %u", (u_int) userid);
if (!isatty(STDOUT_FILENO))
showprogress = 0;
if (pflag) {
/* Cannot pledge: -p allows setuid/setgid files... */
} else {
if (pledge("stdio rpath wpath cpath fattr tty proc exec",
NULL) == -1) {
perror("pledge");
exit(1);
}
}
remin = STDIN_FILENO;
remout = STDOUT_FILENO;
if (fflag) {
/* Follow "protocol", send data. */
(void) response();
source(argc, argv);
exit(errs != 0);
}
if (tflag) {
/* Receive data. */
sink(argc, argv);
exit(errs != 0);
}
if (argc < 2)
usage();
if (argc > 2)
targetshouldbedirectory = 1;
remin = remout = -1;
do_cmd_pid = -1;
/* Command to be executed on remote system using "ssh". */
(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
verbose_mode ? " -v" : "",
iamrecursive ? " -r" : "", pflag ? " -p" : "",
targetshouldbedirectory ? " -d" : "");
(void) signal(SIGPIPE, lostconn);
if (colon(argv[argc - 1])) /* Dest is remote host. */
toremote(argc, argv);
else {
if (targetshouldbedirectory)
verifydir(argv[argc - 1]);
tolocal(argc, argv); /* Dest is local host. */
}
/*
* Finally check the exit status of the ssh process, if one was forked
* and no error has occurred yet
*/
if (do_cmd_pid != -1 && errs == 0) {
if (remin != -1)
(void) close(remin);
if (remout != -1)
(void) close(remout);
if (waitpid(do_cmd_pid, &status, 0) == -1)
errs = 1;
else {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
errs = 1;
}
}
exit(errs != 0);
}
/* Callback from atomicio6 to update progress meter and limit bandwidth */
static int
scpio(void *_cnt, size_t s)
{
off_t *cnt = (off_t *)_cnt;
*cnt += s;
if (limit_kbps > 0)
bandwidth_limit(&bwlimit, s);
return 0;
}
static int
do_times(int fd, int verb, const struct stat *sb)
{
/* strlen(2^64) == 20; strlen(10^6) == 7 */
char buf[(20 + 7 + 2) * 2 + 2];
(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
(unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
(unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
if (verb) {
fprintf(stderr, "File mtime %lld atime %lld\n",
(long long)sb->st_mtime, (long long)sb->st_atime);
fprintf(stderr, "Sending file timestamps: %s", buf);
}
(void) atomicio(vwrite, fd, buf, strlen(buf));
return (response());
}
static int
parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
char **pathp)
{
int r;
r = parse_uri("scp", uri, userp, hostp, portp, pathp);
if (r == 0 && *pathp == NULL)
*pathp = xstrdup(".");
return r;
}
void
toremote(int argc, char **argv)
{
char *suser = NULL, *host = NULL, *src = NULL;
char *bp, *tuser, *thost, *targ;
int sport = -1, tport = -1;
arglist alist;
int i, r;
u_int j;
memset(&alist, '\0', sizeof(alist));
alist.list = NULL;
/* Parse target */
r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
++errs;
goto out;
}
if (r != 0) {
if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
&targ) == -1) {
fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
++errs;
goto out;
}
}
if (tuser != NULL && !okname(tuser)) {
++errs;
goto out;
}
/* Parse source files */
for (i = 0; i < argc - 1; i++) {
free(suser);
free(host);
free(src);
r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[i]);
++errs;
continue;
}
if (r != 0) {
parse_user_host_path(argv[i], &suser, &host, &src);
}
if (suser != NULL && !okname(suser)) {
++errs;
continue;
}
if (host && throughlocal) { /* extended remote to remote */
xasprintf(&bp, "%s -f %s%s", cmd,
*src == '-' ? "-- " : "", src);
if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
exit(1);
free(bp);
xasprintf(&bp, "%s -t %s%s", cmd,
*targ == '-' ? "-- " : "", targ);
if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
exit(1);
free(bp);
(void) close(remin);
(void) close(remout);
remin = remout = -1;
} else if (host) { /* standard remote to remote */
if (tport != -1 && tport != SSH_DEFAULT_PORT) {
/* This would require the remote support URIs */
fatal("target port not supported with two "
"remote hosts without the -3 option");
}
freeargs(&alist);
addargs(&alist, "%s", ssh_program);
addargs(&alist, "-x");
addargs(&alist, "-oClearAllForwardings=yes");
addargs(&alist, "-n");
for (j = 0; j < remote_remote_args.num; j++) {
addargs(&alist, "%s",
remote_remote_args.list[j]);
}
if (sport != -1) {
addargs(&alist, "-p");
addargs(&alist, "%d", sport);
}
if (suser) {
addargs(&alist, "-l");
addargs(&alist, "%s", suser);
}
addargs(&alist, "--");
addargs(&alist, "%s", host);
addargs(&alist, "%s", cmd);
addargs(&alist, "%s", src);
addargs(&alist, "%s%s%s:%s",
tuser ? tuser : "", tuser ? "@" : "",
thost, targ);
if (do_local_cmd(&alist) != 0)
errs = 1;
} else { /* local to remote */
if (remin == -1) {
xasprintf(&bp, "%s -t %s%s", cmd,
*targ == '-' ? "-- " : "", targ);
if (do_cmd(thost, tuser, tport, bp, &remin,
&remout) < 0)
exit(1);
if (response() < 0)
exit(1);
free(bp);
}
source(1, argv + i);
}
}
out:
free(tuser);
free(thost);
free(targ);
free(suser);
free(host);
free(src);
}
void
tolocal(int argc, char **argv)
{
char *bp, *host = NULL, *src = NULL, *suser = NULL;
arglist alist;
int i, r, sport = -1;
memset(&alist, '\0', sizeof(alist));
alist.list = NULL;
for (i = 0; i < argc - 1; i++) {
free(suser);
free(host);
free(src);
r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[i]);
++errs;
continue;
}
if (r != 0)
parse_user_host_path(argv[i], &suser, &host, &src);
if (suser != NULL && !okname(suser)) {
++errs;
continue;
}
if (!host) { /* Local to local. */
freeargs(&alist);
addargs(&alist, "%s", _PATH_CP);
if (iamrecursive)
addargs(&alist, "-r");
if (pflag)
addargs(&alist, "-p");
addargs(&alist, "--");
addargs(&alist, "%s", argv[i]);
addargs(&alist, "%s", argv[argc-1]);
if (do_local_cmd(&alist))
++errs;
continue;
}
/* Remote to local. */
xasprintf(&bp, "%s -f %s%s",
cmd, *src == '-' ? "-- " : "", src);
if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
free(bp);
++errs;
continue;
}
free(bp);
sink(1, argv + argc - 1);
(void) close(remin);
remin = remout = -1;
}
free(suser);
free(host);
free(src);
}
void
source(int argc, char **argv)
{
struct stat stb;
static BUF buffer;
BUF *bp;
off_t i, statbytes;
size_t amt, nr;
int fd = -1, haderr, indx;
char *last, *name, buf[2048], encname[PATH_MAX];
int len;
for (indx = 0; indx < argc; ++indx) {
name = argv[indx];
statbytes = 0;
len = strlen(name);
while (len > 1 && name[len-1] == '/')
name[--len] = '\0';
if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
goto syserr;
if (strchr(name, '\n') != NULL) {
strnvis(encname, name, sizeof(encname), VIS_NL);
name = encname;
}
if (fstat(fd, &stb) < 0) {
syserr: run_err("%s: %s", name, strerror(errno));
goto next;
}
if (stb.st_size < 0) {
run_err("%s: %s", name, "Negative file size");
goto next;
}
unset_nonblock(fd);
switch (stb.st_mode & S_IFMT) {
case S_IFREG:
break;
case S_IFDIR:
if (iamrecursive) {
rsource(name, &stb);
goto next;
}
/* FALLTHROUGH */
default:
run_err("%s: not a regular file", name);
goto next;
}
if ((last = strrchr(name, '/')) == NULL)
last = name;
else
++last;
curfile = last;
if (pflag) {
if (do_times(remout, verbose_mode, &stb) < 0)
goto next;
}
#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
snprintf(buf, sizeof buf, "C%04o %lld %s\n",
(u_int) (stb.st_mode & FILEMODEMASK),
(long long)stb.st_size, last);
if (verbose_mode)
fmprintf(stderr, "Sending file modes: %s", buf);
(void) atomicio(vwrite, remout, buf, strlen(buf));
if (response() < 0)
goto next;
if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
next: if (fd != -1) {
(void) close(fd);
fd = -1;
}
continue;
}
if (showprogress)
start_progress_meter(curfile, stb.st_size, &statbytes);
set_nonblock(remout);
for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
amt = bp->cnt;
if (i + (off_t)amt > stb.st_size)
amt = stb.st_size - i;
if (!haderr) {
if ((nr = atomicio(read, fd,
bp->buf, amt)) != amt) {
haderr = errno;
memset(bp->buf + nr, 0, amt - nr);
}
}
/* Keep writing after error to retain sync */
if (haderr) {
(void)atomicio(vwrite, remout, bp->buf, amt);
memset(bp->buf, 0, amt);
continue;
}
if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
&statbytes) != amt)
haderr = errno;
}
unset_nonblock(remout);
if (fd != -1) {
if (close(fd) < 0 && !haderr)
haderr = errno;
fd = -1;
}
if (!haderr)
(void) atomicio(vwrite, remout, "", 1);
else
run_err("%s: %s", name, strerror(haderr));
(void) response();
if (showprogress)
stop_progress_meter();
}
}
void
rsource(char *name, struct stat *statp)
{
DIR *dirp;
struct dirent *dp;
char *last, *vect[1], path[PATH_MAX];
if (!(dirp = opendir(name))) {
run_err("%s: %s", name, strerror(errno));
return;
}
last = strrchr(name, '/');
if (last == NULL)
last = name;
else
last++;
if (pflag) {
if (do_times(remout, verbose_mode, statp) < 0) {
closedir(dirp);
return;
}
}
(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
(u_int) (statp->st_mode & FILEMODEMASK), 0, last);
if (verbose_mode)
fmprintf(stderr, "Entering directory: %s", path);
(void) atomicio(vwrite, remout, path, strlen(path));
if (response() < 0) {
closedir(dirp);
return;
}
while ((dp = readdir(dirp)) != NULL) {
if (dp->d_ino == 0)
continue;
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
run_err("%s/%s: name too long", name, dp->d_name);
continue;
}
(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
vect[0] = path;
source(1, vect);
}
(void) closedir(dirp);
(void) atomicio(vwrite, remout, "E\n", 2);
(void) response();
}
#define TYPE_OVERFLOW(type, val) \
((sizeof(type) == 4 && (val) > INT32_MAX) || \
(sizeof(type) == 8 && (val) > INT64_MAX) || \
(sizeof(type) != 4 && sizeof(type) != 8))
void
sink(int argc, char **argv)
{
static BUF buffer;
struct stat stb;
enum {
YES, NO, DISPLAYED
} wrerr;
BUF *bp;
off_t i;
size_t j, count;
int amt, exists, first, ofd;
mode_t mode, omode, mask;
off_t size, statbytes;
unsigned long long ull;
int setimes, targisdir, wrerrno = 0;
char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
struct timeval tv[2];
#define atime tv[0]
#define mtime tv[1]
#define SCREWUP(str) { why = str; goto screwup; }
if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
SCREWUP("Unexpected off_t/time_t size");
setimes = targisdir = 0;
mask = umask(0);
if (!pflag)
(void) umask(mask);
if (argc != 1) {
run_err("ambiguous target");
exit(1);
}
targ = *argv;
if (targetshouldbedirectory)
verifydir(targ);
(void) atomicio(vwrite, remout, "", 1);
if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
targisdir = 1;
for (first = 1;; first = 0) {
cp = buf;
if (atomicio(read, remin, cp, 1) != 1)
return;
if (*cp++ == '\n')
SCREWUP("unexpected <newline>");
do {
if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
SCREWUP("lost connection");
*cp++ = ch;
} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
*cp = 0;
if (verbose_mode)
fmprintf(stderr, "Sink: %s", buf);
if (buf[0] == '\01' || buf[0] == '\02') {
if (iamremote == 0) {
(void) snmprintf(visbuf, sizeof(visbuf),
NULL, "%s", buf + 1);
(void) atomicio(vwrite, STDERR_FILENO,
visbuf, strlen(visbuf));
}
if (buf[0] == '\02')
exit(1);
++errs;
continue;
}
if (buf[0] == 'E') {
(void) atomicio(vwrite, remout, "", 1);
return;
}
if (ch == '\n')
*--cp = 0;
cp = buf;
if (*cp == 'T') {
setimes++;
cp++;
if (!isdigit((unsigned char)*cp))
SCREWUP("mtime.sec not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("mtime.sec not delimited");
if (TYPE_OVERFLOW(time_t, ull))
setimes = 0; /* out of range */
mtime.tv_sec = ull;
mtime.tv_usec = strtol(cp, &cp, 10);
if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
mtime.tv_usec > 999999)
SCREWUP("mtime.usec not delimited");
if (!isdigit((unsigned char)*cp))
SCREWUP("atime.sec not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("atime.sec not delimited");
if (TYPE_OVERFLOW(time_t, ull))
setimes = 0; /* out of range */
atime.tv_sec = ull;
atime.tv_usec = strtol(cp, &cp, 10);
if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
atime.tv_usec > 999999)
SCREWUP("atime.usec not delimited");
(void) atomicio(vwrite, remout, "", 1);
continue;
}
if (*cp != 'C' && *cp != 'D') {
/*
* Check for the case "rcp remote:foo\* local:bar".
* In this case, the line "No match." can be returned
* by the shell before the rcp command on the remote is
* executed so the ^Aerror_message convention isn't
* followed.
*/
if (first) {
run_err("%s", cp);
exit(1);
}
SCREWUP("expected control record");
}
mode = 0;
for (++cp; cp < buf + 5; cp++) {
if (*cp < '0' || *cp > '7')
SCREWUP("bad mode");
mode = (mode << 3) | (*cp - '0');
}
if (!pflag)
mode &= ~mask;
if (*cp++ != ' ')
SCREWUP("mode not delimited");
if (!isdigit((unsigned char)*cp))
SCREWUP("size not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("size not delimited");
if (TYPE_OVERFLOW(off_t, ull))
SCREWUP("size out of range");
size = (off_t)ull;
if (*cp == '\0' || strchr(cp, '/') != NULL ||
strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
run_err("error: unexpected filename: %s", cp);
exit(1);
}
if (targisdir) {
static char *namebuf;
static size_t cursize;
size_t need;
need = strlen(targ) + strlen(cp) + 250;
if (need > cursize) {
free(namebuf);
namebuf = xmalloc(need);
cursize = need;
}
(void) snprintf(namebuf, need, "%s%s%s", targ,
strcmp(targ, "/") ? "/" : "", cp);
np = namebuf;
} else
np = targ;
curfile = cp;
exists = stat(np, &stb) == 0;
if (buf[0] == 'D') {
int mod_flag = pflag;
if (!iamrecursive)
SCREWUP("received directory without -r");
if (exists) {
if (!S_ISDIR(stb.st_mode)) {
errno = ENOTDIR;
goto bad;
}
if (pflag)
(void) chmod(np, mode);
} else {
/* Handle copying from a read-only
directory */
mod_flag = 1;
if (mkdir(np, mode | S_IRWXU) < 0)
goto bad;
}
vect[0] = xstrdup(np);
sink(1, vect);
if (setimes) {
setimes = 0;
if (utimes(vect[0], tv) < 0)
run_err("%s: set times: %s",
vect[0], strerror(errno));
}
if (mod_flag)
(void) chmod(vect[0], mode);
free(vect[0]);
continue;
}
omode = mode;
mode |= S_IWUSR;
if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
bad: run_err("%s: %s", np, strerror(errno));
continue;
}
(void) atomicio(vwrite, remout, "", 1);
if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
(void) close(ofd);
continue;
}
cp = bp->buf;
wrerr = NO;
statbytes = 0;
if (showprogress)
start_progress_meter(curfile, size, &statbytes);
set_nonblock(remin);
for (count = i = 0; i < size; i += bp->cnt) {
amt = bp->cnt;
if (i + amt > size)
amt = size - i;
count += amt;
do {
j = atomicio6(read, remin, cp, amt,
scpio, &statbytes);
if (j == 0) {
run_err("%s", j != EPIPE ?
strerror(errno) :
"dropped connection");
exit(1);
}
amt -= j;
cp += j;
} while (amt > 0);
if (count == bp->cnt) {
/* Keep reading so we stay sync'd up. */
if (wrerr == NO) {
if (atomicio(vwrite, ofd, bp->buf,
count) != count) {
wrerr = YES;
wrerrno = errno;
}
}
count = 0;
cp = bp->buf;
}
}
unset_nonblock(remin);
if (count != 0 && wrerr == NO &&
atomicio(vwrite, ofd, bp->buf, count) != count) {
wrerr = YES;
wrerrno = errno;
}
if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
ftruncate(ofd, size) != 0) {
run_err("%s: truncate: %s", np, strerror(errno));
wrerr = DISPLAYED;
}
if (pflag) {
if (exists || omode != mode)
#ifdef HAVE_FCHMOD
if (fchmod(ofd, omode)) {
#else /* HAVE_FCHMOD */
if (chmod(np, omode)) {
#endif /* HAVE_FCHMOD */
run_err("%s: set mode: %s",
np, strerror(errno));
wrerr = DISPLAYED;
}
} else {
if (!exists && omode != mode)
#ifdef HAVE_FCHMOD
if (fchmod(ofd, omode & ~mask)) {
#else /* HAVE_FCHMOD */
if (chmod(np, omode & ~mask)) {
#endif /* HAVE_FCHMOD */
run_err("%s: set mode: %s",
np, strerror(errno));
wrerr = DISPLAYED;
}
}
if (close(ofd) == -1) {
wrerr = YES;
wrerrno = errno;
}
(void) response();
if (showprogress)
stop_progress_meter();
if (setimes && wrerr == NO) {
setimes = 0;
if (utimes(np, tv) < 0) {
run_err("%s: set times: %s",
np, strerror(errno));
wrerr = DISPLAYED;
}
}
switch (wrerr) {
case YES:
run_err("%s: %s", np, strerror(wrerrno));
break;
case NO:
(void) atomicio(vwrite, remout, "", 1);
break;
case DISPLAYED:
break;
}
}
screwup:
run_err("protocol error: %s", why);
exit(1);
}
int
response(void)
{
char ch, *cp, resp, rbuf[2048], visbuf[2048];
if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
lostconn(0);
cp = rbuf;
switch (resp) {
case 0: /* ok */
return (0);
default:
*cp++ = resp;
/* FALLTHROUGH */
case 1: /* error, followed by error msg */
case 2: /* fatal error, "" */
do {
if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
lostconn(0);
*cp++ = ch;
} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
if (!iamremote) {
cp[-1] = '\0';
(void) snmprintf(visbuf, sizeof(visbuf),
NULL, "%s\n", rbuf);
(void) atomicio(vwrite, STDERR_FILENO,
visbuf, strlen(visbuf));
}
++errs;
if (resp == 1)
return (-1);
exit(1);
}
/* NOTREACHED */
}
void
usage(void)
{
(void) fprintf(stderr,
"usage: scp [-346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
" [-l limit] [-o ssh_option] [-P port] [-S program] source ... target\n");
exit(1);
}
void
run_err(const char *fmt,...)
{
static FILE *fp;
va_list ap;
++errs;
if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
(void) fprintf(fp, "%c", 0x01);
(void) fprintf(fp, "scp: ");
va_start(ap, fmt);
(void) vfprintf(fp, fmt, ap);
va_end(ap);
(void) fprintf(fp, "\n");
(void) fflush(fp);
}
if (!iamremote) {
va_start(ap, fmt);
vfmprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
}
void
verifydir(char *cp)
{
struct stat stb;
if (!stat(cp, &stb)) {
if (S_ISDIR(stb.st_mode))
return;
errno = ENOTDIR;
}
run_err("%s: %s", cp, strerror(errno));
killchild(0);
}
int
okname(char *cp0)
{
int c;
char *cp;
cp = cp0;
do {
c = (int)*cp;
if (c & 0200)
goto bad;
if (!isalpha(c) && !isdigit((unsigned char)c)) {
switch (c) {
case '\'':
case '"':
case '`':
case ' ':
case '#':
goto bad;
default:
break;
}
}
} while (*++cp);
return (1);
bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
return (0);
}
BUF *
allocbuf(BUF *bp, int fd, int blksize)
{
size_t size;
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
struct stat stb;
if (fstat(fd, &stb) < 0) {
run_err("fstat: %s", strerror(errno));
return (0);
}
size = ROUNDUP(stb.st_blksize, blksize);
if (size == 0)
size = blksize;
#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
size = blksize;
#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
if (bp->cnt >= size)
return (bp);
bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
bp->cnt = size;
return (bp);
}
void
lostconn(int signo)
{
if (!iamremote)
(void)write(STDERR_FILENO, "lost connection\n", 16);
if (signo)
_exit(1);
else
exit(1);
}
| ./CrossVul/dataset_final_sorted/CWE-706/c/good_513_0 |
crossvul-cpp_data_bad_513_0 | /* $OpenBSD: scp.c,v 1.197 2018/06/01 04:31:48 dtucker Exp $ */
/*
* scp - secure remote copy. This is basically patched BSD rcp which
* uses ssh to do the data transfer (instead of using rcmd).
*
* NOTE: This version should NOT be suid root. (This uses ssh to
* do the transfer and ssh has the necessary privileges.)
*
* 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
*
* As far as I am concerned, the code I have written for this software
* can be used freely for any purpose. Any derived versions of this
* software must be clearly marked as such, and if the derived work is
* incompatible with the protocol description in the RFC file, it must be
* called by a name other than "ssh" or "Secure Shell".
*/
/*
* Copyright (c) 1999 Theo de Raadt. All rights reserved.
* Copyright (c) 1999 Aaron Campbell. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Parts from:
*
* Copyright (c) 1983, 1990, 1992, 1993, 1995
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include "includes.h"
#include <sys/types.h>
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_POLL_H
#include <poll.h>
#else
# ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
# endif
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <sys/wait.h>
#include <sys/uio.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <locale.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
#include <vis.h>
#endif
#include "xmalloc.h"
#include "ssh.h"
#include "atomicio.h"
#include "pathnames.h"
#include "log.h"
#include "misc.h"
#include "progressmeter.h"
#include "utf8.h"
extern char *__progname;
#define COPY_BUFLEN 16384
int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
/* Struct for addargs */
arglist args;
arglist remote_remote_args;
/* Bandwidth limit */
long long limit_kbps = 0;
struct bwlimit bwlimit;
/* Name of current file being transferred. */
char *curfile;
/* This is set to non-zero to enable verbose mode. */
int verbose_mode = 0;
/* This is set to zero if the progressmeter is not desired. */
int showprogress = 1;
/*
* This is set to non-zero if remote-remote copy should be piped
* through this process.
*/
int throughlocal = 0;
/* Non-standard port to use for the ssh connection or -1. */
int sshport = -1;
/* This is the program to execute for the secured connection. ("ssh" or -S) */
char *ssh_program = _PATH_SSH_PROGRAM;
/* This is used to store the pid of ssh_program */
pid_t do_cmd_pid = -1;
static void
killchild(int signo)
{
if (do_cmd_pid > 1) {
kill(do_cmd_pid, signo ? signo : SIGTERM);
waitpid(do_cmd_pid, NULL, 0);
}
if (signo)
_exit(1);
exit(1);
}
static void
suspchild(int signo)
{
int status;
if (do_cmd_pid > 1) {
kill(do_cmd_pid, signo);
while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
errno == EINTR)
;
kill(getpid(), SIGSTOP);
}
}
static int
do_local_cmd(arglist *a)
{
u_int i;
int status;
pid_t pid;
if (a->num == 0)
fatal("do_local_cmd: no arguments");
if (verbose_mode) {
fprintf(stderr, "Executing:");
for (i = 0; i < a->num; i++)
fmprintf(stderr, " %s", a->list[i]);
fprintf(stderr, "\n");
}
if ((pid = fork()) == -1)
fatal("do_local_cmd: fork: %s", strerror(errno));
if (pid == 0) {
execvp(a->list[0], a->list);
perror(a->list[0]);
exit(1);
}
do_cmd_pid = pid;
signal(SIGTERM, killchild);
signal(SIGINT, killchild);
signal(SIGHUP, killchild);
while (waitpid(pid, &status, 0) == -1)
if (errno != EINTR)
fatal("do_local_cmd: waitpid: %s", strerror(errno));
do_cmd_pid = -1;
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
return (-1);
return (0);
}
/*
* This function executes the given command as the specified user on the
* given host. This returns < 0 if execution fails, and >= 0 otherwise. This
* assigns the input and output file descriptors on success.
*/
int
do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
{
int pin[2], pout[2], reserved[2];
if (verbose_mode)
fmprintf(stderr,
"Executing: program %s host %s, user %s, command %s\n",
ssh_program, host,
remuser ? remuser : "(unspecified)", cmd);
if (port == -1)
port = sshport;
/*
* Reserve two descriptors so that the real pipes won't get
* descriptors 0 and 1 because that will screw up dup2 below.
*/
if (pipe(reserved) < 0)
fatal("pipe: %s", strerror(errno));
/* Create a socket pair for communicating with ssh. */
if (pipe(pin) < 0)
fatal("pipe: %s", strerror(errno));
if (pipe(pout) < 0)
fatal("pipe: %s", strerror(errno));
/* Free the reserved descriptors. */
close(reserved[0]);
close(reserved[1]);
signal(SIGTSTP, suspchild);
signal(SIGTTIN, suspchild);
signal(SIGTTOU, suspchild);
/* Fork a child to execute the command on the remote host using ssh. */
do_cmd_pid = fork();
if (do_cmd_pid == 0) {
/* Child. */
close(pin[1]);
close(pout[0]);
dup2(pin[0], 0);
dup2(pout[1], 1);
close(pin[0]);
close(pout[1]);
replacearg(&args, 0, "%s", ssh_program);
if (port != -1) {
addargs(&args, "-p");
addargs(&args, "%d", port);
}
if (remuser != NULL) {
addargs(&args, "-l");
addargs(&args, "%s", remuser);
}
addargs(&args, "--");
addargs(&args, "%s", host);
addargs(&args, "%s", cmd);
execvp(ssh_program, args.list);
perror(ssh_program);
exit(1);
} else if (do_cmd_pid == -1) {
fatal("fork: %s", strerror(errno));
}
/* Parent. Close the other side, and return the local side. */
close(pin[0]);
*fdout = pin[1];
close(pout[1]);
*fdin = pout[0];
signal(SIGTERM, killchild);
signal(SIGINT, killchild);
signal(SIGHUP, killchild);
return 0;
}
/*
* This function executes a command similar to do_cmd(), but expects the
* input and output descriptors to be setup by a previous call to do_cmd().
* This way the input and output of two commands can be connected.
*/
int
do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
{
pid_t pid;
int status;
if (verbose_mode)
fmprintf(stderr,
"Executing: 2nd program %s host %s, user %s, command %s\n",
ssh_program, host,
remuser ? remuser : "(unspecified)", cmd);
if (port == -1)
port = sshport;
/* Fork a child to execute the command on the remote host using ssh. */
pid = fork();
if (pid == 0) {
dup2(fdin, 0);
dup2(fdout, 1);
replacearg(&args, 0, "%s", ssh_program);
if (port != -1) {
addargs(&args, "-p");
addargs(&args, "%d", port);
}
if (remuser != NULL) {
addargs(&args, "-l");
addargs(&args, "%s", remuser);
}
addargs(&args, "--");
addargs(&args, "%s", host);
addargs(&args, "%s", cmd);
execvp(ssh_program, args.list);
perror(ssh_program);
exit(1);
} else if (pid == -1) {
fatal("fork: %s", strerror(errno));
}
while (waitpid(pid, &status, 0) == -1)
if (errno != EINTR)
fatal("do_cmd2: waitpid: %s", strerror(errno));
return 0;
}
typedef struct {
size_t cnt;
char *buf;
} BUF;
BUF *allocbuf(BUF *, int, int);
void lostconn(int);
int okname(char *);
void run_err(const char *,...);
void verifydir(char *);
struct passwd *pwd;
uid_t userid;
int errs, remin, remout;
int pflag, iamremote, iamrecursive, targetshouldbedirectory;
#define CMDNEEDS 64
char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
int response(void);
void rsource(char *, struct stat *);
void sink(int, char *[]);
void source(int, char *[]);
void tolocal(int, char *[]);
void toremote(int, char *[]);
void usage(void);
int
main(int argc, char **argv)
{
int ch, fflag, tflag, status, n;
char **newargv;
const char *errstr;
extern char *optarg;
extern int optind;
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
msetlocale();
/* Copy argv, because we modify it */
newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
for (n = 0; n < argc; n++)
newargv[n] = xstrdup(argv[n]);
argv = newargv;
__progname = ssh_get_progname(argv[0]);
memset(&args, '\0', sizeof(args));
memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
args.list = remote_remote_args.list = NULL;
addargs(&args, "%s", ssh_program);
addargs(&args, "-x");
addargs(&args, "-oForwardAgent=no");
addargs(&args, "-oPermitLocalCommand=no");
addargs(&args, "-oClearAllForwardings=yes");
addargs(&args, "-oRemoteCommand=none");
addargs(&args, "-oRequestTTY=no");
fflag = tflag = 0;
while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
switch (ch) {
/* User-visible flags. */
case '1':
fatal("SSH protocol v.1 is no longer supported");
break;
case '2':
/* Ignored */
break;
case '4':
case '6':
case 'C':
addargs(&args, "-%c", ch);
addargs(&remote_remote_args, "-%c", ch);
break;
case '3':
throughlocal = 1;
break;
case 'o':
case 'c':
case 'i':
case 'F':
addargs(&remote_remote_args, "-%c", ch);
addargs(&remote_remote_args, "%s", optarg);
addargs(&args, "-%c", ch);
addargs(&args, "%s", optarg);
break;
case 'P':
sshport = a2port(optarg);
if (sshport <= 0)
fatal("bad port \"%s\"\n", optarg);
break;
case 'B':
addargs(&remote_remote_args, "-oBatchmode=yes");
addargs(&args, "-oBatchmode=yes");
break;
case 'l':
limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
&errstr);
if (errstr != NULL)
usage();
limit_kbps *= 1024; /* kbps */
bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
break;
case 'p':
pflag = 1;
break;
case 'r':
iamrecursive = 1;
break;
case 'S':
ssh_program = xstrdup(optarg);
break;
case 'v':
addargs(&args, "-v");
addargs(&remote_remote_args, "-v");
verbose_mode = 1;
break;
case 'q':
addargs(&args, "-q");
addargs(&remote_remote_args, "-q");
showprogress = 0;
break;
/* Server options. */
case 'd':
targetshouldbedirectory = 1;
break;
case 'f': /* "from" */
iamremote = 1;
fflag = 1;
break;
case 't': /* "to" */
iamremote = 1;
tflag = 1;
#ifdef HAVE_CYGWIN
setmode(0, O_BINARY);
#endif
break;
default:
usage();
}
argc -= optind;
argv += optind;
if ((pwd = getpwuid(userid = getuid())) == NULL)
fatal("unknown user %u", (u_int) userid);
if (!isatty(STDOUT_FILENO))
showprogress = 0;
if (pflag) {
/* Cannot pledge: -p allows setuid/setgid files... */
} else {
if (pledge("stdio rpath wpath cpath fattr tty proc exec",
NULL) == -1) {
perror("pledge");
exit(1);
}
}
remin = STDIN_FILENO;
remout = STDOUT_FILENO;
if (fflag) {
/* Follow "protocol", send data. */
(void) response();
source(argc, argv);
exit(errs != 0);
}
if (tflag) {
/* Receive data. */
sink(argc, argv);
exit(errs != 0);
}
if (argc < 2)
usage();
if (argc > 2)
targetshouldbedirectory = 1;
remin = remout = -1;
do_cmd_pid = -1;
/* Command to be executed on remote system using "ssh". */
(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
verbose_mode ? " -v" : "",
iamrecursive ? " -r" : "", pflag ? " -p" : "",
targetshouldbedirectory ? " -d" : "");
(void) signal(SIGPIPE, lostconn);
if (colon(argv[argc - 1])) /* Dest is remote host. */
toremote(argc, argv);
else {
if (targetshouldbedirectory)
verifydir(argv[argc - 1]);
tolocal(argc, argv); /* Dest is local host. */
}
/*
* Finally check the exit status of the ssh process, if one was forked
* and no error has occurred yet
*/
if (do_cmd_pid != -1 && errs == 0) {
if (remin != -1)
(void) close(remin);
if (remout != -1)
(void) close(remout);
if (waitpid(do_cmd_pid, &status, 0) == -1)
errs = 1;
else {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
errs = 1;
}
}
exit(errs != 0);
}
/* Callback from atomicio6 to update progress meter and limit bandwidth */
static int
scpio(void *_cnt, size_t s)
{
off_t *cnt = (off_t *)_cnt;
*cnt += s;
if (limit_kbps > 0)
bandwidth_limit(&bwlimit, s);
return 0;
}
static int
do_times(int fd, int verb, const struct stat *sb)
{
/* strlen(2^64) == 20; strlen(10^6) == 7 */
char buf[(20 + 7 + 2) * 2 + 2];
(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
(unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
(unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
if (verb) {
fprintf(stderr, "File mtime %lld atime %lld\n",
(long long)sb->st_mtime, (long long)sb->st_atime);
fprintf(stderr, "Sending file timestamps: %s", buf);
}
(void) atomicio(vwrite, fd, buf, strlen(buf));
return (response());
}
static int
parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
char **pathp)
{
int r;
r = parse_uri("scp", uri, userp, hostp, portp, pathp);
if (r == 0 && *pathp == NULL)
*pathp = xstrdup(".");
return r;
}
void
toremote(int argc, char **argv)
{
char *suser = NULL, *host = NULL, *src = NULL;
char *bp, *tuser, *thost, *targ;
int sport = -1, tport = -1;
arglist alist;
int i, r;
u_int j;
memset(&alist, '\0', sizeof(alist));
alist.list = NULL;
/* Parse target */
r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
++errs;
goto out;
}
if (r != 0) {
if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
&targ) == -1) {
fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
++errs;
goto out;
}
}
if (tuser != NULL && !okname(tuser)) {
++errs;
goto out;
}
/* Parse source files */
for (i = 0; i < argc - 1; i++) {
free(suser);
free(host);
free(src);
r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[i]);
++errs;
continue;
}
if (r != 0) {
parse_user_host_path(argv[i], &suser, &host, &src);
}
if (suser != NULL && !okname(suser)) {
++errs;
continue;
}
if (host && throughlocal) { /* extended remote to remote */
xasprintf(&bp, "%s -f %s%s", cmd,
*src == '-' ? "-- " : "", src);
if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
exit(1);
free(bp);
xasprintf(&bp, "%s -t %s%s", cmd,
*targ == '-' ? "-- " : "", targ);
if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
exit(1);
free(bp);
(void) close(remin);
(void) close(remout);
remin = remout = -1;
} else if (host) { /* standard remote to remote */
if (tport != -1 && tport != SSH_DEFAULT_PORT) {
/* This would require the remote support URIs */
fatal("target port not supported with two "
"remote hosts without the -3 option");
}
freeargs(&alist);
addargs(&alist, "%s", ssh_program);
addargs(&alist, "-x");
addargs(&alist, "-oClearAllForwardings=yes");
addargs(&alist, "-n");
for (j = 0; j < remote_remote_args.num; j++) {
addargs(&alist, "%s",
remote_remote_args.list[j]);
}
if (sport != -1) {
addargs(&alist, "-p");
addargs(&alist, "%d", sport);
}
if (suser) {
addargs(&alist, "-l");
addargs(&alist, "%s", suser);
}
addargs(&alist, "--");
addargs(&alist, "%s", host);
addargs(&alist, "%s", cmd);
addargs(&alist, "%s", src);
addargs(&alist, "%s%s%s:%s",
tuser ? tuser : "", tuser ? "@" : "",
thost, targ);
if (do_local_cmd(&alist) != 0)
errs = 1;
} else { /* local to remote */
if (remin == -1) {
xasprintf(&bp, "%s -t %s%s", cmd,
*targ == '-' ? "-- " : "", targ);
if (do_cmd(thost, tuser, tport, bp, &remin,
&remout) < 0)
exit(1);
if (response() < 0)
exit(1);
free(bp);
}
source(1, argv + i);
}
}
out:
free(tuser);
free(thost);
free(targ);
free(suser);
free(host);
free(src);
}
void
tolocal(int argc, char **argv)
{
char *bp, *host = NULL, *src = NULL, *suser = NULL;
arglist alist;
int i, r, sport = -1;
memset(&alist, '\0', sizeof(alist));
alist.list = NULL;
for (i = 0; i < argc - 1; i++) {
free(suser);
free(host);
free(src);
r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
if (r == -1) {
fmprintf(stderr, "%s: invalid uri\n", argv[i]);
++errs;
continue;
}
if (r != 0)
parse_user_host_path(argv[i], &suser, &host, &src);
if (suser != NULL && !okname(suser)) {
++errs;
continue;
}
if (!host) { /* Local to local. */
freeargs(&alist);
addargs(&alist, "%s", _PATH_CP);
if (iamrecursive)
addargs(&alist, "-r");
if (pflag)
addargs(&alist, "-p");
addargs(&alist, "--");
addargs(&alist, "%s", argv[i]);
addargs(&alist, "%s", argv[argc-1]);
if (do_local_cmd(&alist))
++errs;
continue;
}
/* Remote to local. */
xasprintf(&bp, "%s -f %s%s",
cmd, *src == '-' ? "-- " : "", src);
if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
free(bp);
++errs;
continue;
}
free(bp);
sink(1, argv + argc - 1);
(void) close(remin);
remin = remout = -1;
}
free(suser);
free(host);
free(src);
}
void
source(int argc, char **argv)
{
struct stat stb;
static BUF buffer;
BUF *bp;
off_t i, statbytes;
size_t amt, nr;
int fd = -1, haderr, indx;
char *last, *name, buf[2048], encname[PATH_MAX];
int len;
for (indx = 0; indx < argc; ++indx) {
name = argv[indx];
statbytes = 0;
len = strlen(name);
while (len > 1 && name[len-1] == '/')
name[--len] = '\0';
if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
goto syserr;
if (strchr(name, '\n') != NULL) {
strnvis(encname, name, sizeof(encname), VIS_NL);
name = encname;
}
if (fstat(fd, &stb) < 0) {
syserr: run_err("%s: %s", name, strerror(errno));
goto next;
}
if (stb.st_size < 0) {
run_err("%s: %s", name, "Negative file size");
goto next;
}
unset_nonblock(fd);
switch (stb.st_mode & S_IFMT) {
case S_IFREG:
break;
case S_IFDIR:
if (iamrecursive) {
rsource(name, &stb);
goto next;
}
/* FALLTHROUGH */
default:
run_err("%s: not a regular file", name);
goto next;
}
if ((last = strrchr(name, '/')) == NULL)
last = name;
else
++last;
curfile = last;
if (pflag) {
if (do_times(remout, verbose_mode, &stb) < 0)
goto next;
}
#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
snprintf(buf, sizeof buf, "C%04o %lld %s\n",
(u_int) (stb.st_mode & FILEMODEMASK),
(long long)stb.st_size, last);
if (verbose_mode)
fmprintf(stderr, "Sending file modes: %s", buf);
(void) atomicio(vwrite, remout, buf, strlen(buf));
if (response() < 0)
goto next;
if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
next: if (fd != -1) {
(void) close(fd);
fd = -1;
}
continue;
}
if (showprogress)
start_progress_meter(curfile, stb.st_size, &statbytes);
set_nonblock(remout);
for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
amt = bp->cnt;
if (i + (off_t)amt > stb.st_size)
amt = stb.st_size - i;
if (!haderr) {
if ((nr = atomicio(read, fd,
bp->buf, amt)) != amt) {
haderr = errno;
memset(bp->buf + nr, 0, amt - nr);
}
}
/* Keep writing after error to retain sync */
if (haderr) {
(void)atomicio(vwrite, remout, bp->buf, amt);
memset(bp->buf, 0, amt);
continue;
}
if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
&statbytes) != amt)
haderr = errno;
}
unset_nonblock(remout);
if (fd != -1) {
if (close(fd) < 0 && !haderr)
haderr = errno;
fd = -1;
}
if (!haderr)
(void) atomicio(vwrite, remout, "", 1);
else
run_err("%s: %s", name, strerror(haderr));
(void) response();
if (showprogress)
stop_progress_meter();
}
}
void
rsource(char *name, struct stat *statp)
{
DIR *dirp;
struct dirent *dp;
char *last, *vect[1], path[PATH_MAX];
if (!(dirp = opendir(name))) {
run_err("%s: %s", name, strerror(errno));
return;
}
last = strrchr(name, '/');
if (last == NULL)
last = name;
else
last++;
if (pflag) {
if (do_times(remout, verbose_mode, statp) < 0) {
closedir(dirp);
return;
}
}
(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
(u_int) (statp->st_mode & FILEMODEMASK), 0, last);
if (verbose_mode)
fmprintf(stderr, "Entering directory: %s", path);
(void) atomicio(vwrite, remout, path, strlen(path));
if (response() < 0) {
closedir(dirp);
return;
}
while ((dp = readdir(dirp)) != NULL) {
if (dp->d_ino == 0)
continue;
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
run_err("%s/%s: name too long", name, dp->d_name);
continue;
}
(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
vect[0] = path;
source(1, vect);
}
(void) closedir(dirp);
(void) atomicio(vwrite, remout, "E\n", 2);
(void) response();
}
#define TYPE_OVERFLOW(type, val) \
((sizeof(type) == 4 && (val) > INT32_MAX) || \
(sizeof(type) == 8 && (val) > INT64_MAX) || \
(sizeof(type) != 4 && sizeof(type) != 8))
void
sink(int argc, char **argv)
{
static BUF buffer;
struct stat stb;
enum {
YES, NO, DISPLAYED
} wrerr;
BUF *bp;
off_t i;
size_t j, count;
int amt, exists, first, ofd;
mode_t mode, omode, mask;
off_t size, statbytes;
unsigned long long ull;
int setimes, targisdir, wrerrno = 0;
char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
struct timeval tv[2];
#define atime tv[0]
#define mtime tv[1]
#define SCREWUP(str) { why = str; goto screwup; }
if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
SCREWUP("Unexpected off_t/time_t size");
setimes = targisdir = 0;
mask = umask(0);
if (!pflag)
(void) umask(mask);
if (argc != 1) {
run_err("ambiguous target");
exit(1);
}
targ = *argv;
if (targetshouldbedirectory)
verifydir(targ);
(void) atomicio(vwrite, remout, "", 1);
if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
targisdir = 1;
for (first = 1;; first = 0) {
cp = buf;
if (atomicio(read, remin, cp, 1) != 1)
return;
if (*cp++ == '\n')
SCREWUP("unexpected <newline>");
do {
if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
SCREWUP("lost connection");
*cp++ = ch;
} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
*cp = 0;
if (verbose_mode)
fmprintf(stderr, "Sink: %s", buf);
if (buf[0] == '\01' || buf[0] == '\02') {
if (iamremote == 0) {
(void) snmprintf(visbuf, sizeof(visbuf),
NULL, "%s", buf + 1);
(void) atomicio(vwrite, STDERR_FILENO,
visbuf, strlen(visbuf));
}
if (buf[0] == '\02')
exit(1);
++errs;
continue;
}
if (buf[0] == 'E') {
(void) atomicio(vwrite, remout, "", 1);
return;
}
if (ch == '\n')
*--cp = 0;
cp = buf;
if (*cp == 'T') {
setimes++;
cp++;
if (!isdigit((unsigned char)*cp))
SCREWUP("mtime.sec not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("mtime.sec not delimited");
if (TYPE_OVERFLOW(time_t, ull))
setimes = 0; /* out of range */
mtime.tv_sec = ull;
mtime.tv_usec = strtol(cp, &cp, 10);
if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
mtime.tv_usec > 999999)
SCREWUP("mtime.usec not delimited");
if (!isdigit((unsigned char)*cp))
SCREWUP("atime.sec not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("atime.sec not delimited");
if (TYPE_OVERFLOW(time_t, ull))
setimes = 0; /* out of range */
atime.tv_sec = ull;
atime.tv_usec = strtol(cp, &cp, 10);
if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
atime.tv_usec > 999999)
SCREWUP("atime.usec not delimited");
(void) atomicio(vwrite, remout, "", 1);
continue;
}
if (*cp != 'C' && *cp != 'D') {
/*
* Check for the case "rcp remote:foo\* local:bar".
* In this case, the line "No match." can be returned
* by the shell before the rcp command on the remote is
* executed so the ^Aerror_message convention isn't
* followed.
*/
if (first) {
run_err("%s", cp);
exit(1);
}
SCREWUP("expected control record");
}
mode = 0;
for (++cp; cp < buf + 5; cp++) {
if (*cp < '0' || *cp > '7')
SCREWUP("bad mode");
mode = (mode << 3) | (*cp - '0');
}
if (!pflag)
mode &= ~mask;
if (*cp++ != ' ')
SCREWUP("mode not delimited");
if (!isdigit((unsigned char)*cp))
SCREWUP("size not present");
ull = strtoull(cp, &cp, 10);
if (!cp || *cp++ != ' ')
SCREWUP("size not delimited");
if (TYPE_OVERFLOW(off_t, ull))
SCREWUP("size out of range");
size = (off_t)ull;
if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
run_err("error: unexpected filename: %s", cp);
exit(1);
}
if (targisdir) {
static char *namebuf;
static size_t cursize;
size_t need;
need = strlen(targ) + strlen(cp) + 250;
if (need > cursize) {
free(namebuf);
namebuf = xmalloc(need);
cursize = need;
}
(void) snprintf(namebuf, need, "%s%s%s", targ,
strcmp(targ, "/") ? "/" : "", cp);
np = namebuf;
} else
np = targ;
curfile = cp;
exists = stat(np, &stb) == 0;
if (buf[0] == 'D') {
int mod_flag = pflag;
if (!iamrecursive)
SCREWUP("received directory without -r");
if (exists) {
if (!S_ISDIR(stb.st_mode)) {
errno = ENOTDIR;
goto bad;
}
if (pflag)
(void) chmod(np, mode);
} else {
/* Handle copying from a read-only
directory */
mod_flag = 1;
if (mkdir(np, mode | S_IRWXU) < 0)
goto bad;
}
vect[0] = xstrdup(np);
sink(1, vect);
if (setimes) {
setimes = 0;
if (utimes(vect[0], tv) < 0)
run_err("%s: set times: %s",
vect[0], strerror(errno));
}
if (mod_flag)
(void) chmod(vect[0], mode);
free(vect[0]);
continue;
}
omode = mode;
mode |= S_IWUSR;
if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
bad: run_err("%s: %s", np, strerror(errno));
continue;
}
(void) atomicio(vwrite, remout, "", 1);
if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
(void) close(ofd);
continue;
}
cp = bp->buf;
wrerr = NO;
statbytes = 0;
if (showprogress)
start_progress_meter(curfile, size, &statbytes);
set_nonblock(remin);
for (count = i = 0; i < size; i += bp->cnt) {
amt = bp->cnt;
if (i + amt > size)
amt = size - i;
count += amt;
do {
j = atomicio6(read, remin, cp, amt,
scpio, &statbytes);
if (j == 0) {
run_err("%s", j != EPIPE ?
strerror(errno) :
"dropped connection");
exit(1);
}
amt -= j;
cp += j;
} while (amt > 0);
if (count == bp->cnt) {
/* Keep reading so we stay sync'd up. */
if (wrerr == NO) {
if (atomicio(vwrite, ofd, bp->buf,
count) != count) {
wrerr = YES;
wrerrno = errno;
}
}
count = 0;
cp = bp->buf;
}
}
unset_nonblock(remin);
if (count != 0 && wrerr == NO &&
atomicio(vwrite, ofd, bp->buf, count) != count) {
wrerr = YES;
wrerrno = errno;
}
if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
ftruncate(ofd, size) != 0) {
run_err("%s: truncate: %s", np, strerror(errno));
wrerr = DISPLAYED;
}
if (pflag) {
if (exists || omode != mode)
#ifdef HAVE_FCHMOD
if (fchmod(ofd, omode)) {
#else /* HAVE_FCHMOD */
if (chmod(np, omode)) {
#endif /* HAVE_FCHMOD */
run_err("%s: set mode: %s",
np, strerror(errno));
wrerr = DISPLAYED;
}
} else {
if (!exists && omode != mode)
#ifdef HAVE_FCHMOD
if (fchmod(ofd, omode & ~mask)) {
#else /* HAVE_FCHMOD */
if (chmod(np, omode & ~mask)) {
#endif /* HAVE_FCHMOD */
run_err("%s: set mode: %s",
np, strerror(errno));
wrerr = DISPLAYED;
}
}
if (close(ofd) == -1) {
wrerr = YES;
wrerrno = errno;
}
(void) response();
if (showprogress)
stop_progress_meter();
if (setimes && wrerr == NO) {
setimes = 0;
if (utimes(np, tv) < 0) {
run_err("%s: set times: %s",
np, strerror(errno));
wrerr = DISPLAYED;
}
}
switch (wrerr) {
case YES:
run_err("%s: %s", np, strerror(wrerrno));
break;
case NO:
(void) atomicio(vwrite, remout, "", 1);
break;
case DISPLAYED:
break;
}
}
screwup:
run_err("protocol error: %s", why);
exit(1);
}
int
response(void)
{
char ch, *cp, resp, rbuf[2048], visbuf[2048];
if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
lostconn(0);
cp = rbuf;
switch (resp) {
case 0: /* ok */
return (0);
default:
*cp++ = resp;
/* FALLTHROUGH */
case 1: /* error, followed by error msg */
case 2: /* fatal error, "" */
do {
if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
lostconn(0);
*cp++ = ch;
} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
if (!iamremote) {
cp[-1] = '\0';
(void) snmprintf(visbuf, sizeof(visbuf),
NULL, "%s\n", rbuf);
(void) atomicio(vwrite, STDERR_FILENO,
visbuf, strlen(visbuf));
}
++errs;
if (resp == 1)
return (-1);
exit(1);
}
/* NOTREACHED */
}
void
usage(void)
{
(void) fprintf(stderr,
"usage: scp [-346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
" [-l limit] [-o ssh_option] [-P port] [-S program] source ... target\n");
exit(1);
}
void
run_err(const char *fmt,...)
{
static FILE *fp;
va_list ap;
++errs;
if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
(void) fprintf(fp, "%c", 0x01);
(void) fprintf(fp, "scp: ");
va_start(ap, fmt);
(void) vfprintf(fp, fmt, ap);
va_end(ap);
(void) fprintf(fp, "\n");
(void) fflush(fp);
}
if (!iamremote) {
va_start(ap, fmt);
vfmprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
}
void
verifydir(char *cp)
{
struct stat stb;
if (!stat(cp, &stb)) {
if (S_ISDIR(stb.st_mode))
return;
errno = ENOTDIR;
}
run_err("%s: %s", cp, strerror(errno));
killchild(0);
}
int
okname(char *cp0)
{
int c;
char *cp;
cp = cp0;
do {
c = (int)*cp;
if (c & 0200)
goto bad;
if (!isalpha(c) && !isdigit((unsigned char)c)) {
switch (c) {
case '\'':
case '"':
case '`':
case ' ':
case '#':
goto bad;
default:
break;
}
}
} while (*++cp);
return (1);
bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
return (0);
}
BUF *
allocbuf(BUF *bp, int fd, int blksize)
{
size_t size;
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
struct stat stb;
if (fstat(fd, &stb) < 0) {
run_err("fstat: %s", strerror(errno));
return (0);
}
size = ROUNDUP(stb.st_blksize, blksize);
if (size == 0)
size = blksize;
#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
size = blksize;
#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
if (bp->cnt >= size)
return (bp);
bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
bp->cnt = size;
return (bp);
}
void
lostconn(int signo)
{
if (!iamremote)
(void)write(STDERR_FILENO, "lost connection\n", 16);
if (signo)
_exit(1);
else
exit(1);
}
| ./CrossVul/dataset_final_sorted/CWE-706/c/bad_513_0 |
crossvul-cpp_data_bad_2800_0 | #include <pb_controller.h>
#include <pb_view.h>
#include <poddlthread.h>
#include <config.h>
#include <utils.h>
#include <strprintf.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <cstdlib>
#include <thread>
#include <signal.h>
#include <unistd.h>
#include <getopt.h>
#include <keymap.h>
#include <configcontainer.h>
#include <colormanager.h>
#include <exceptions.h>
#include <queueloader.h>
#include <logger.h>
using namespace newsbeuter;
static std::string lock_file = "pb-lock.pid";
static void ctrl_c_action(int sig) {
LOG(level::DEBUG,"caugh signal %d",sig);
stfl::reset();
utils::remove_fs_lock(lock_file);
::exit(EXIT_FAILURE);
}
namespace podbeuter {
#define LOCK_SUFFIX ".lock"
/**
* \brief Try to setup XDG style dirs.
*
* returns false, if that fails
*/
bool pb_controller::setup_dirs_xdg(const char *env_home) {
const char *env_xdg_config;
const char *env_xdg_data;
std::string xdg_config_dir;
std::string xdg_data_dir;
env_xdg_config = ::getenv("XDG_CONFIG_HOME");
if (env_xdg_config) {
xdg_config_dir = env_xdg_config;
} else {
xdg_config_dir = env_home;
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(".config");
}
env_xdg_data = ::getenv("XDG_DATA_HOME");
if (env_xdg_data) {
xdg_data_dir = env_xdg_data;
} else {
xdg_data_dir = env_home;
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(".local");
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append("share");
}
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(NEWSBEUTER_SUBDIR_XDG);
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(NEWSBEUTER_SUBDIR_XDG);
bool config_dir_exists = 0 == access(xdg_config_dir.c_str(), R_OK | X_OK);
if (!config_dir_exists) {
std::cerr
<< strprintf::fmt(
_("XDG: configuration directory '%s' not accessible, "
"using '%s' instead."),
xdg_config_dir,
config_dir)
<< std::endl;
return false;
}
/* Invariant: config dir exists.
*
* At this point, we're confident we'll be using XDG. We don't check if
* data dir exists, because if it doesn't we'll create it. */
config_dir = xdg_config_dir;
// create data directory if it doesn't exist
utils::mkdir_parents(xdg_data_dir, 0700);
/* in config */
url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file;
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
/* in data */
cache_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file;
lock_file = cache_file + LOCK_SUFFIX;
queue_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
searchfile = strprintf::fmt("%s%shistory.search", xdg_data_dir, NEWSBEUTER_PATH_SEP);
cmdlinefile = strprintf::fmt("%s%shistory.cmdline", xdg_data_dir, NEWSBEUTER_PATH_SEP);
return true;
}
pb_controller::pb_controller() : v(0), config_file("config"), queue_file("queue"), cfg(0), view_update_(true), max_dls(1), ql(0) {
char * cfgdir;
if (!(cfgdir = ::getenv("HOME"))) {
struct passwd * spw = ::getpwuid(::getuid());
if (spw) {
cfgdir = spw->pw_dir;
} else {
std::cout << _("Fatal error: couldn't determine home directory!") << std::endl;
std::cout << strprintf::fmt(_("Please set the HOME environment variable or add a valid user for UID %u!"), ::getuid()) << std::endl;
::exit(EXIT_FAILURE);
}
}
config_dir = cfgdir;
if (setup_dirs_xdg(cfgdir))
return;
config_dir.append(NEWSBEUTER_PATH_SEP);
config_dir.append(NEWSBEUTER_CONFIG_SUBDIR);
::mkdir(config_dir.c_str(),0700); // create configuration directory if it doesn't exist
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
queue_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
lock_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + lock_file;
}
pb_controller::~pb_controller() {
delete cfg;
}
void pb_controller::run(int argc, char * argv[]) {
int c;
bool automatic_dl = false;
::signal(SIGINT, ctrl_c_action);
static const char getopt_str[] = "C:q:d:l:havV";
static const struct option longopts[] = {
{"config-file" , required_argument, 0, 'C'},
{"queue-file" , required_argument, 0, 'q'},
{"log-file" , required_argument, 0, 'd'},
{"log-level" , required_argument, 0, 'l'},
{"help" , no_argument , 0, 'h'},
{"autodownload" , no_argument , 0, 'a'},
{"version" , no_argument , 0, 'v'},
{0 , 0 , 0, 0 }
};
while ((c = ::getopt_long(argc, argv, getopt_str, longopts, nullptr)) != -1) {
switch (c) {
case ':':
case '?':
usage(argv[0]);
break;
case 'C':
config_file = optarg;
break;
case 'q':
queue_file = optarg;
break;
case 'a':
automatic_dl = true;
break;
case 'd':
logger::getInstance().set_logfile(optarg);
break;
case 'l': {
level l = static_cast<level>(atoi(optarg));
if (l > level::NONE && l <= level::DEBUG) {
logger::getInstance().set_loglevel(l);
} else {
std::cerr << strprintf::fmt(_("%s: %d: invalid loglevel value"), argv[0], l) << std::endl;
::std::exit(EXIT_FAILURE);
}
}
break;
case 'h':
usage(argv[0]);
break;
default:
std::cout << strprintf::fmt(_("%s: unknown option - %c"), argv[0], static_cast<char>(c)) << std::endl;
usage(argv[0]);
break;
}
};
std::cout << strprintf::fmt(_("Starting %s %s..."), "podbeuter", PROGRAM_VERSION) << std::endl;
pid_t pid;
if (!utils::try_fs_lock(lock_file, pid)) {
std::cout << strprintf::fmt(_("Error: an instance of %s is already running (PID: %u)"), "podbeuter", pid) << std::endl;
return;
}
std::cout << _("Loading configuration...");
std::cout.flush();
configparser cfgparser;
cfg = new configcontainer();
cfg->register_commands(cfgparser);
colormanager * colorman = new colormanager();
colorman->register_commands(cfgparser);
keymap keys(KM_PODBEUTER);
cfgparser.register_handler("bind-key", &keys);
cfgparser.register_handler("unbind-key", &keys);
null_config_action_handler null_cah;
cfgparser.register_handler("macro", &null_cah);
cfgparser.register_handler("ignore-article", &null_cah);
cfgparser.register_handler("always-download", &null_cah);
cfgparser.register_handler("define-filter", &null_cah);
cfgparser.register_handler("highlight", &null_cah);
cfgparser.register_handler("highlight-article", &null_cah);
cfgparser.register_handler("reset-unread-on-update", &null_cah);
try {
cfgparser.parse("/etc/newsbeuter/config");
cfgparser.parse(config_file);
} catch (const configexception& ex) {
std::cout << ex.what() << std::endl;
delete colorman;
return;
}
if (colorman->colors_loaded())
colorman->set_pb_colors(v);
delete colorman;
max_dls = cfg->get_configvalue_as_int("max-downloads");
std::cout << _("done.") << std::endl;
ql = new queueloader(queue_file, this);
ql->reload(downloads_);
v->set_keymap(&keys);
v->run(automatic_dl);
stfl::reset();
std::cout << _("Cleaning up queue...");
std::cout.flush();
ql->reload(downloads_);
delete ql;
std::cout << _("done.") << std::endl;
utils::remove_fs_lock(lock_file);
}
void pb_controller::usage(const char * argv0) {
auto msg =
strprintf::fmt(_("%s %s\nusage %s [-C <file>] [-q <file>] [-h]\n"),
"podbeuter",
PROGRAM_VERSION,
argv0);
std::cout << msg;
struct arg {
const char name;
const std::string longname;
const std::string params;
const std::string desc;
};
static const std::vector<arg> args = {
{ 'C', "config-file" , _s("<configfile>"), _s("read configuration from <configfile>") } ,
{ 'q', "queue-file" , _s("<queuefile>") , _s("use <queuefile> as queue file") } ,
{ 'a', "autodownload", "" , _s("start download on startup") } ,
{ 'l', "log-level" , _s("<loglevel>") , _s("write a log with a certain loglevel (valid values: 1 to 6)") },
{ 'd', "log-file" , _s("<logfile>") , _s("use <logfile> as output log file") } ,
{ 'h', "help" , "" , _s("this help") }
};
for (const auto & a : args) {
std::string longcolumn("-");
longcolumn += a.name;
longcolumn += ", --" + a.longname;
longcolumn += a.params.size() > 0 ? "=" + a.params : "";
std::cout << "\t" << longcolumn;
for (unsigned int j = 0; j < utils::gentabs(longcolumn); j++) {
std::cout << "\t";
}
std::cout << a.desc << std::endl;
}
::exit(EXIT_FAILURE);
}
std::string pb_controller::get_dlpath() {
return cfg->get_configvalue("download-path");
}
unsigned int pb_controller::downloads_in_progress() {
unsigned int count = 0;
for (auto dl : downloads_) {
if (dl.status() == dlstatus::DOWNLOADING)
++count;
}
return count;
}
unsigned int pb_controller::get_maxdownloads() {
return max_dls;
}
void pb_controller::reload_queue(bool remove_unplayed) {
if (ql) {
ql->reload(downloads_, remove_unplayed);
}
}
double pb_controller::get_total_kbps() {
double result = 0.0;
for (auto dl : downloads_) {
if (dl.status() == dlstatus::DOWNLOADING) {
result += dl.kbps();
}
}
return result;
}
void pb_controller::start_downloads() {
int dl2start = get_maxdownloads() - downloads_in_progress();
for (auto& download : downloads_) {
if (dl2start == 0) break;
if (download.status() == dlstatus::QUEUED) {
std::thread t {poddlthread(&download, cfg)};
--dl2start;
t.detach();
}
}
}
void pb_controller::increase_parallel_downloads() {
++max_dls;
}
void pb_controller::decrease_parallel_downloads() {
if (max_dls > 1)
--max_dls;
}
void pb_controller::play_file(const std::string& file) {
std::string cmdline;
std::string player = cfg->get_configvalue("player");
if (player == "")
return;
cmdline.append(player);
cmdline.append(" \"");
cmdline.append(utils::replace_all(file,"\"", "\\\""));
cmdline.append("\"");
stfl::reset();
utils::run_interactively(cmdline, "pb_controller::play_file");
}
} // namespace
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/bad_2800_0 |
crossvul-cpp_data_good_2799_1 | #include <stflpp.h>
#include <utils.h>
#include <queueloader.h>
#include <cstdlib>
#include <logger.h>
#include <fstream>
#include <cstring>
#include <config.h>
#include <libgen.h>
#include <unistd.h>
using namespace newsbeuter;
namespace podbeuter {
queueloader::queueloader(const std::string& file, pb_controller * c) : queuefile(file), ctrl(c) {
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed) {
std::vector<download> dltemp;
std::fstream f;
for (auto dl : downloads) {
if (dl.status() == DL_DOWNLOADING) { // we are not allowed to reload if a download is in progress!
LOG(LOG_INFO, "queueloader::reload: aborting reload due to DL_DOWNLOADING status");
return;
}
switch (dl.status()) {
case DL_QUEUED:
case DL_CANCELLED:
case DL_FAILED:
case DL_ALREADY_DOWNLOADED:
case DL_READY:
LOG(LOG_DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
break;
case DL_PLAYED:
case DL_FINISHED:
if (!remove_unplayed) {
LOG(LOG_DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
if (f.is_open()) {
std::string line;
do {
getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(LOG_DEBUG, "queueloader::reload: loaded `%s' from queue file", line.c_str());
std::vector<std::string> fields = utils::tokenize_quoted(line);
bool url_found = false;
for (auto dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(LOG_INFO, "queueloader::reload: found `%s' in old vector", fields[0].c_str());
url_found = true;
break;
}
}
for (auto dl : downloads) {
if (fields[0] == dl.url()) {
LOG(LOG_INFO, "queueloader::reload: found `%s' in new vector", line.c_str());
url_found = true;
break;
}
}
if (!url_found) {
LOG(LOG_INFO, "queueloader::reload: found `%s' nowhere -> storing to new vector", line.c_str());
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK)==0) {
LOG(LOG_INFO, "queueloader::reload: found `%s' on file system -> mark as already downloaded", fn.c_str());
if (fields.size() >= 3) {
if (fields[2] == "downloaded")
d.set_status(DL_READY);
if (fields[2] == "played")
d.set_status(DL_PLAYED);
} else
d.set_status(DL_ALREADY_DOWNLOADED); // TODO: scrap DL_ALREADY_DOWNLOADED state
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (auto dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == DL_READY)
f << " downloaded";
if (dl.status() == DL_PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str) {
std::string fn = ctrl->get_dlpath();
if (fn[fn.length()-1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char * base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(NULL);
strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t));
fn.append(lbuf);
} else {
fn.append(utils::replace_all(base, "'", "%27"));
}
return fn;
}
}
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/good_2799_1 |
crossvul-cpp_data_bad_2799_0 | #include <pb_controller.h>
#include <pb_view.h>
#include <poddlthread.h>
#include <config.h>
#include <utils.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <cstdlib>
#include <thread>
#include <signal.h>
#include <unistd.h>
#include <keymap.h>
#include <configcontainer.h>
#include <colormanager.h>
#include <exceptions.h>
#include <queueloader.h>
#include <logger.h>
using namespace newsbeuter;
static std::string lock_file = "pb-lock.pid";
static void ctrl_c_action(int sig) {
LOG(LOG_DEBUG,"caugh signal %d",sig);
stfl::reset();
utils::remove_fs_lock(lock_file);
::exit(EXIT_FAILURE);
}
namespace podbeuter {
#define LOCK_SUFFIX ".lock"
/**
* \brief Try to setup XDG style dirs.
*
* returns false, if that fails
*/
bool pb_controller::setup_dirs_xdg(const char *env_home) {
const char *env_xdg_config;
const char *env_xdg_data;
std::string xdg_config_dir;
std::string xdg_data_dir;
env_xdg_config = ::getenv("XDG_CONFIG_HOME");
if (env_xdg_config) {
xdg_config_dir = env_xdg_config;
} else {
xdg_config_dir = env_home;
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(".config");
}
env_xdg_data = ::getenv("XDG_DATA_HOME");
if (env_xdg_data) {
xdg_data_dir = env_xdg_data;
} else {
xdg_data_dir = env_home;
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(".local");
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append("share");
}
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(NEWSBEUTER_SUBDIR_XDG);
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(NEWSBEUTER_SUBDIR_XDG);
if (access(xdg_config_dir.c_str(), R_OK | X_OK) != 0) {
std::cout << utils::strprintf(_("XDG: configuration directory '%s' not accessible, using '%s' instead."), xdg_config_dir.c_str(), config_dir.c_str()) << std::endl;
return false;
}
if (access(xdg_data_dir.c_str(), R_OK | X_OK | W_OK) != 0) {
std::cout << utils::strprintf(_("XDG: data directory '%s' not accessible, using '%s' instead."), xdg_data_dir.c_str(), config_dir.c_str()) << std::endl;
return false;
}
config_dir = xdg_config_dir;
/* in config */
url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file;
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
/* in data */
cache_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file;
lock_file = cache_file + LOCK_SUFFIX;
queue_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
searchfile = utils::strprintf("%s%shistory.search", xdg_data_dir.c_str(), NEWSBEUTER_PATH_SEP);
cmdlinefile = utils::strprintf("%s%shistory.cmdline", xdg_data_dir.c_str(), NEWSBEUTER_PATH_SEP);
return true;
}
pb_controller::pb_controller() : v(0), config_file("config"), queue_file("queue"), cfg(0), view_update_(true), max_dls(1), ql(0) {
char * cfgdir;
if (!(cfgdir = ::getenv("HOME"))) {
struct passwd * spw = ::getpwuid(::getuid());
if (spw) {
cfgdir = spw->pw_dir;
} else {
std::cout << _("Fatal error: couldn't determine home directory!") << std::endl;
std::cout << utils::strprintf(_("Please set the HOME environment variable or add a valid user for UID %u!"), ::getuid()) << std::endl;
::exit(EXIT_FAILURE);
}
}
config_dir = cfgdir;
if (setup_dirs_xdg(cfgdir))
return;
config_dir.append(NEWSBEUTER_PATH_SEP);
config_dir.append(NEWSBEUTER_CONFIG_SUBDIR);
::mkdir(config_dir.c_str(),0700); // create configuration directory if it doesn't exist
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
queue_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
lock_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + lock_file;
}
pb_controller::~pb_controller() {
delete cfg;
}
void pb_controller::run(int argc, char * argv[]) {
int c;
bool automatic_dl = false;
::signal(SIGINT, ctrl_c_action);
do {
if ((c = ::getopt(argc, argv, "C:q:d:l:ha")) < 0)
continue;
switch (c) {
case ':':
case '?':
usage(argv[0]);
break;
case 'C':
config_file = optarg;
break;
case 'q':
queue_file = optarg;
break;
case 'a':
automatic_dl = true;
break;
case 'd': // this is an undocumented debug commandline option!
logger::getInstance().set_logfile(optarg);
break;
case 'l': { // this is an undocumented debug commandline option!
loglevel level = static_cast<loglevel>(atoi(optarg));
if (level > LOG_NONE && level <= LOG_DEBUG)
logger::getInstance().set_loglevel(level);
}
break;
case 'h':
usage(argv[0]);
break;
default:
std::cout << utils::strprintf(_("%s: unknown option - %c"), argv[0], static_cast<char>(c)) << std::endl;
usage(argv[0]);
break;
}
} while (c != -1);
std::cout << utils::strprintf(_("Starting %s %s..."), "podbeuter", PROGRAM_VERSION) << std::endl;
pid_t pid;
if (!utils::try_fs_lock(lock_file, pid)) {
std::cout << utils::strprintf(_("Error: an instance of %s is already running (PID: %u)"), "podbeuter", pid) << std::endl;
return;
}
std::cout << _("Loading configuration...");
std::cout.flush();
configparser cfgparser;
cfg = new configcontainer();
cfg->register_commands(cfgparser);
colormanager * colorman = new colormanager();
colorman->register_commands(cfgparser);
keymap keys(KM_PODBEUTER);
cfgparser.register_handler("bind-key", &keys);
cfgparser.register_handler("unbind-key", &keys);
null_config_action_handler null_cah;
cfgparser.register_handler("macro", &null_cah);
cfgparser.register_handler("ignore-article", &null_cah);
cfgparser.register_handler("always-download", &null_cah);
cfgparser.register_handler("define-filter", &null_cah);
cfgparser.register_handler("highlight", &null_cah);
cfgparser.register_handler("highlight-article", &null_cah);
cfgparser.register_handler("reset-unread-on-update", &null_cah);
try {
cfgparser.parse("/etc/newsbeuter/config");
cfgparser.parse(config_file);
} catch (const configexception& ex) {
std::cout << ex.what() << std::endl;
delete colorman;
return;
}
if (colorman->colors_loaded())
colorman->set_pb_colors(v);
delete colorman;
max_dls = cfg->get_configvalue_as_int("max-downloads");
std::cout << _("done.") << std::endl;
ql = new queueloader(queue_file, this);
ql->reload(downloads_);
v->set_keymap(&keys);
v->run(automatic_dl);
stfl::reset();
std::cout << _("Cleaning up queue...");
std::cout.flush();
ql->reload(downloads_);
delete ql;
std::cout << _("done.") << std::endl;
utils::remove_fs_lock(lock_file);
}
void pb_controller::usage(const char * argv0) {
std::cout << utils::strprintf(_("%s %s\nusage %s [-C <file>] [-q <file>] [-h]\n"
"-C <configfile> read configuration from <configfile>\n"
"-q <queuefile> use <queuefile> as queue file\n"
"-a start download on startup\n"
"-h this help\n"), "podbeuter", PROGRAM_VERSION, argv0);
::exit(EXIT_FAILURE);
}
std::string pb_controller::get_dlpath() {
return cfg->get_configvalue("download-path");
}
unsigned int pb_controller::downloads_in_progress() {
unsigned int count = 0;
for (auto dl : downloads_) {
if (dl.status() == DL_DOWNLOADING)
++count;
}
return count;
}
unsigned int pb_controller::get_maxdownloads() {
return max_dls;
}
void pb_controller::reload_queue(bool remove_unplayed) {
if (ql) {
ql->reload(downloads_, remove_unplayed);
}
}
double pb_controller::get_total_kbps() {
double result = 0.0;
for (auto dl : downloads_) {
if (dl.status() == DL_DOWNLOADING) {
result += dl.kbps();
}
}
return result;
}
void pb_controller::start_downloads() {
int dl2start = get_maxdownloads() - downloads_in_progress();
for (auto it=downloads_.begin(); dl2start > 0 && it!=downloads_.end(); ++it) {
if (it->status() == DL_QUEUED) {
std::thread t {poddlthread(&(*it), cfg)};
--dl2start;
}
}
}
void pb_controller::increase_parallel_downloads() {
++max_dls;
}
void pb_controller::decrease_parallel_downloads() {
if (max_dls > 1)
--max_dls;
}
void pb_controller::play_file(const std::string& file) {
std::string cmdline;
std::string player = cfg->get_configvalue("player");
if (player == "")
return;
cmdline.append(player);
cmdline.append(" \"");
cmdline.append(utils::replace_all(file,"\"", "\\\""));
cmdline.append("\"");
stfl::reset();
LOG(LOG_DEBUG, "pb_controller::play_file: running `%s'", cmdline.c_str());
::system(cmdline.c_str());
}
} // namespace
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/bad_2799_0 |
crossvul-cpp_data_bad_2800_1 | #include <stflpp.h>
#include <utils.h>
#include <queueloader.h>
#include <cstdlib>
#include <logger.h>
#include <fstream>
#include <cstring>
#include <config.h>
#include <libgen.h>
#include <unistd.h>
using namespace newsbeuter;
namespace podbeuter {
queueloader::queueloader(const std::string& file, pb_controller * c) : queuefile(file), ctrl(c) {
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed) {
std::vector<download> dltemp;
std::fstream f;
for (auto dl : downloads) {
if (dl.status() == dlstatus::DOWNLOADING) { // we are not allowed to reload if a download is in progress!
LOG(level::INFO, "queueloader::reload: aborting reload due to dlstatus::DOWNLOADING status");
return;
}
switch (dl.status()) {
case dlstatus::QUEUED:
case dlstatus::CANCELLED:
case dlstatus::FAILED:
case dlstatus::ALREADY_DOWNLOADED:
case dlstatus::READY:
LOG(level::DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
break;
case dlstatus::PLAYED:
case dlstatus::FINISHED:
if (!remove_unplayed) {
LOG(level::DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
if (f.is_open()) {
std::string line;
do {
std::getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(level::DEBUG, "queueloader::reload: loaded `%s' from queue file", line);
std::vector<std::string> fields = utils::tokenize_quoted(line);
bool url_found = false;
for (auto dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(level::INFO, "queueloader::reload: found `%s' in old vector", fields[0]);
url_found = true;
break;
}
}
for (auto dl : downloads) {
if (fields[0] == dl.url()) {
LOG(level::INFO, "queueloader::reload: found `%s' in new vector", line);
url_found = true;
break;
}
}
if (!url_found) {
LOG(level::INFO, "queueloader::reload: found `%s' nowhere -> storing to new vector", line);
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK)==0) {
LOG(level::INFO, "queueloader::reload: found `%s' on file system -> mark as already downloaded", fn);
if (fields.size() >= 3) {
if (fields[2] == "downloaded")
d.set_status(dlstatus::READY);
if (fields[2] == "played")
d.set_status(dlstatus::PLAYED);
} else
d.set_status(dlstatus::ALREADY_DOWNLOADED); // TODO: scrap dlstatus::ALREADY_DOWNLOADED state
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (auto dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == dlstatus::READY)
f << " downloaded";
if (dl.status() == dlstatus::PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str) {
std::string fn = ctrl->get_dlpath();
if (fn[fn.length()-1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char * base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(nullptr);
strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t));
fn.append(lbuf);
} else {
fn.append(base);
}
return fn;
}
}
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/bad_2800_1 |
crossvul-cpp_data_good_2800_1 | #include <stflpp.h>
#include <utils.h>
#include <queueloader.h>
#include <cstdlib>
#include <logger.h>
#include <fstream>
#include <cstring>
#include <config.h>
#include <libgen.h>
#include <unistd.h>
using namespace newsbeuter;
namespace podbeuter {
queueloader::queueloader(const std::string& file, pb_controller * c) : queuefile(file), ctrl(c) {
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed) {
std::vector<download> dltemp;
std::fstream f;
for (auto dl : downloads) {
if (dl.status() == dlstatus::DOWNLOADING) { // we are not allowed to reload if a download is in progress!
LOG(level::INFO, "queueloader::reload: aborting reload due to dlstatus::DOWNLOADING status");
return;
}
switch (dl.status()) {
case dlstatus::QUEUED:
case dlstatus::CANCELLED:
case dlstatus::FAILED:
case dlstatus::ALREADY_DOWNLOADED:
case dlstatus::READY:
LOG(level::DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
break;
case dlstatus::PLAYED:
case dlstatus::FINISHED:
if (!remove_unplayed) {
LOG(level::DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
if (f.is_open()) {
std::string line;
do {
std::getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(level::DEBUG, "queueloader::reload: loaded `%s' from queue file", line);
std::vector<std::string> fields = utils::tokenize_quoted(line);
bool url_found = false;
for (auto dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(level::INFO, "queueloader::reload: found `%s' in old vector", fields[0]);
url_found = true;
break;
}
}
for (auto dl : downloads) {
if (fields[0] == dl.url()) {
LOG(level::INFO, "queueloader::reload: found `%s' in new vector", line);
url_found = true;
break;
}
}
if (!url_found) {
LOG(level::INFO, "queueloader::reload: found `%s' nowhere -> storing to new vector", line);
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK)==0) {
LOG(level::INFO, "queueloader::reload: found `%s' on file system -> mark as already downloaded", fn);
if (fields.size() >= 3) {
if (fields[2] == "downloaded")
d.set_status(dlstatus::READY);
if (fields[2] == "played")
d.set_status(dlstatus::PLAYED);
} else
d.set_status(dlstatus::ALREADY_DOWNLOADED); // TODO: scrap dlstatus::ALREADY_DOWNLOADED state
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (auto dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == dlstatus::READY)
f << " downloaded";
if (dl.status() == dlstatus::PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str) {
std::string fn = ctrl->get_dlpath();
if (fn[fn.length()-1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char * base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(nullptr);
strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t));
fn.append(lbuf);
} else {
fn.append(utils::replace_all(base, "'", "%27"));
}
return fn;
}
}
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/good_2800_1 |
crossvul-cpp_data_good_2799_0 | #include <pb_controller.h>
#include <pb_view.h>
#include <poddlthread.h>
#include <config.h>
#include <utils.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <cstdlib>
#include <thread>
#include <signal.h>
#include <unistd.h>
#include <keymap.h>
#include <configcontainer.h>
#include <colormanager.h>
#include <exceptions.h>
#include <queueloader.h>
#include <logger.h>
using namespace newsbeuter;
static std::string lock_file = "pb-lock.pid";
static void ctrl_c_action(int sig) {
LOG(LOG_DEBUG,"caugh signal %d",sig);
stfl::reset();
utils::remove_fs_lock(lock_file);
::exit(EXIT_FAILURE);
}
namespace podbeuter {
#define LOCK_SUFFIX ".lock"
/**
* \brief Try to setup XDG style dirs.
*
* returns false, if that fails
*/
bool pb_controller::setup_dirs_xdg(const char *env_home) {
const char *env_xdg_config;
const char *env_xdg_data;
std::string xdg_config_dir;
std::string xdg_data_dir;
env_xdg_config = ::getenv("XDG_CONFIG_HOME");
if (env_xdg_config) {
xdg_config_dir = env_xdg_config;
} else {
xdg_config_dir = env_home;
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(".config");
}
env_xdg_data = ::getenv("XDG_DATA_HOME");
if (env_xdg_data) {
xdg_data_dir = env_xdg_data;
} else {
xdg_data_dir = env_home;
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(".local");
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append("share");
}
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(NEWSBEUTER_SUBDIR_XDG);
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(NEWSBEUTER_SUBDIR_XDG);
if (access(xdg_config_dir.c_str(), R_OK | X_OK) != 0) {
std::cout << utils::strprintf(_("XDG: configuration directory '%s' not accessible, using '%s' instead."), xdg_config_dir.c_str(), config_dir.c_str()) << std::endl;
return false;
}
if (access(xdg_data_dir.c_str(), R_OK | X_OK | W_OK) != 0) {
std::cout << utils::strprintf(_("XDG: data directory '%s' not accessible, using '%s' instead."), xdg_data_dir.c_str(), config_dir.c_str()) << std::endl;
return false;
}
config_dir = xdg_config_dir;
/* in config */
url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file;
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
/* in data */
cache_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file;
lock_file = cache_file + LOCK_SUFFIX;
queue_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
searchfile = utils::strprintf("%s%shistory.search", xdg_data_dir.c_str(), NEWSBEUTER_PATH_SEP);
cmdlinefile = utils::strprintf("%s%shistory.cmdline", xdg_data_dir.c_str(), NEWSBEUTER_PATH_SEP);
return true;
}
pb_controller::pb_controller() : v(0), config_file("config"), queue_file("queue"), cfg(0), view_update_(true), max_dls(1), ql(0) {
char * cfgdir;
if (!(cfgdir = ::getenv("HOME"))) {
struct passwd * spw = ::getpwuid(::getuid());
if (spw) {
cfgdir = spw->pw_dir;
} else {
std::cout << _("Fatal error: couldn't determine home directory!") << std::endl;
std::cout << utils::strprintf(_("Please set the HOME environment variable or add a valid user for UID %u!"), ::getuid()) << std::endl;
::exit(EXIT_FAILURE);
}
}
config_dir = cfgdir;
if (setup_dirs_xdg(cfgdir))
return;
config_dir.append(NEWSBEUTER_PATH_SEP);
config_dir.append(NEWSBEUTER_CONFIG_SUBDIR);
::mkdir(config_dir.c_str(),0700); // create configuration directory if it doesn't exist
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
queue_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
lock_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + lock_file;
}
pb_controller::~pb_controller() {
delete cfg;
}
void pb_controller::run(int argc, char * argv[]) {
int c;
bool automatic_dl = false;
::signal(SIGINT, ctrl_c_action);
do {
if ((c = ::getopt(argc, argv, "C:q:d:l:ha")) < 0)
continue;
switch (c) {
case ':':
case '?':
usage(argv[0]);
break;
case 'C':
config_file = optarg;
break;
case 'q':
queue_file = optarg;
break;
case 'a':
automatic_dl = true;
break;
case 'd': // this is an undocumented debug commandline option!
logger::getInstance().set_logfile(optarg);
break;
case 'l': { // this is an undocumented debug commandline option!
loglevel level = static_cast<loglevel>(atoi(optarg));
if (level > LOG_NONE && level <= LOG_DEBUG)
logger::getInstance().set_loglevel(level);
}
break;
case 'h':
usage(argv[0]);
break;
default:
std::cout << utils::strprintf(_("%s: unknown option - %c"), argv[0], static_cast<char>(c)) << std::endl;
usage(argv[0]);
break;
}
} while (c != -1);
std::cout << utils::strprintf(_("Starting %s %s..."), "podbeuter", PROGRAM_VERSION) << std::endl;
pid_t pid;
if (!utils::try_fs_lock(lock_file, pid)) {
std::cout << utils::strprintf(_("Error: an instance of %s is already running (PID: %u)"), "podbeuter", pid) << std::endl;
return;
}
std::cout << _("Loading configuration...");
std::cout.flush();
configparser cfgparser;
cfg = new configcontainer();
cfg->register_commands(cfgparser);
colormanager * colorman = new colormanager();
colorman->register_commands(cfgparser);
keymap keys(KM_PODBEUTER);
cfgparser.register_handler("bind-key", &keys);
cfgparser.register_handler("unbind-key", &keys);
null_config_action_handler null_cah;
cfgparser.register_handler("macro", &null_cah);
cfgparser.register_handler("ignore-article", &null_cah);
cfgparser.register_handler("always-download", &null_cah);
cfgparser.register_handler("define-filter", &null_cah);
cfgparser.register_handler("highlight", &null_cah);
cfgparser.register_handler("highlight-article", &null_cah);
cfgparser.register_handler("reset-unread-on-update", &null_cah);
try {
cfgparser.parse("/etc/newsbeuter/config");
cfgparser.parse(config_file);
} catch (const configexception& ex) {
std::cout << ex.what() << std::endl;
delete colorman;
return;
}
if (colorman->colors_loaded())
colorman->set_pb_colors(v);
delete colorman;
max_dls = cfg->get_configvalue_as_int("max-downloads");
std::cout << _("done.") << std::endl;
ql = new queueloader(queue_file, this);
ql->reload(downloads_);
v->set_keymap(&keys);
v->run(automatic_dl);
stfl::reset();
std::cout << _("Cleaning up queue...");
std::cout.flush();
ql->reload(downloads_);
delete ql;
std::cout << _("done.") << std::endl;
utils::remove_fs_lock(lock_file);
}
void pb_controller::usage(const char * argv0) {
std::cout << utils::strprintf(_("%s %s\nusage %s [-C <file>] [-q <file>] [-h]\n"
"-C <configfile> read configuration from <configfile>\n"
"-q <queuefile> use <queuefile> as queue file\n"
"-a start download on startup\n"
"-h this help\n"), "podbeuter", PROGRAM_VERSION, argv0);
::exit(EXIT_FAILURE);
}
std::string pb_controller::get_dlpath() {
return cfg->get_configvalue("download-path");
}
unsigned int pb_controller::downloads_in_progress() {
unsigned int count = 0;
for (auto dl : downloads_) {
if (dl.status() == DL_DOWNLOADING)
++count;
}
return count;
}
unsigned int pb_controller::get_maxdownloads() {
return max_dls;
}
void pb_controller::reload_queue(bool remove_unplayed) {
if (ql) {
ql->reload(downloads_, remove_unplayed);
}
}
double pb_controller::get_total_kbps() {
double result = 0.0;
for (auto dl : downloads_) {
if (dl.status() == DL_DOWNLOADING) {
result += dl.kbps();
}
}
return result;
}
void pb_controller::start_downloads() {
int dl2start = get_maxdownloads() - downloads_in_progress();
for (auto it=downloads_.begin(); dl2start > 0 && it!=downloads_.end(); ++it) {
if (it->status() == DL_QUEUED) {
std::thread t {poddlthread(&(*it), cfg)};
--dl2start;
}
}
}
void pb_controller::increase_parallel_downloads() {
++max_dls;
}
void pb_controller::decrease_parallel_downloads() {
if (max_dls > 1)
--max_dls;
}
void pb_controller::play_file(const std::string& file) {
std::string cmdline;
std::string player = cfg->get_configvalue("player");
if (player == "")
return;
cmdline.append(player);
cmdline.append(" \'");
cmdline.append(utils::replace_all(file,"'", "%27"));
cmdline.append("\'");
stfl::reset();
LOG(LOG_DEBUG, "pb_controller::play_file: running `%s'", cmdline.c_str());
::system(cmdline.c_str());
}
} // namespace
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/good_2799_0 |
crossvul-cpp_data_good_2800_0 | #include <pb_controller.h>
#include <pb_view.h>
#include <poddlthread.h>
#include <config.h>
#include <utils.h>
#include <strprintf.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <cstdlib>
#include <thread>
#include <signal.h>
#include <unistd.h>
#include <getopt.h>
#include <keymap.h>
#include <configcontainer.h>
#include <colormanager.h>
#include <exceptions.h>
#include <queueloader.h>
#include <logger.h>
using namespace newsbeuter;
static std::string lock_file = "pb-lock.pid";
static void ctrl_c_action(int sig) {
LOG(level::DEBUG,"caugh signal %d",sig);
stfl::reset();
utils::remove_fs_lock(lock_file);
::exit(EXIT_FAILURE);
}
namespace podbeuter {
#define LOCK_SUFFIX ".lock"
/**
* \brief Try to setup XDG style dirs.
*
* returns false, if that fails
*/
bool pb_controller::setup_dirs_xdg(const char *env_home) {
const char *env_xdg_config;
const char *env_xdg_data;
std::string xdg_config_dir;
std::string xdg_data_dir;
env_xdg_config = ::getenv("XDG_CONFIG_HOME");
if (env_xdg_config) {
xdg_config_dir = env_xdg_config;
} else {
xdg_config_dir = env_home;
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(".config");
}
env_xdg_data = ::getenv("XDG_DATA_HOME");
if (env_xdg_data) {
xdg_data_dir = env_xdg_data;
} else {
xdg_data_dir = env_home;
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(".local");
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append("share");
}
xdg_config_dir.append(NEWSBEUTER_PATH_SEP);
xdg_config_dir.append(NEWSBEUTER_SUBDIR_XDG);
xdg_data_dir.append(NEWSBEUTER_PATH_SEP);
xdg_data_dir.append(NEWSBEUTER_SUBDIR_XDG);
bool config_dir_exists = 0 == access(xdg_config_dir.c_str(), R_OK | X_OK);
if (!config_dir_exists) {
std::cerr
<< strprintf::fmt(
_("XDG: configuration directory '%s' not accessible, "
"using '%s' instead."),
xdg_config_dir,
config_dir)
<< std::endl;
return false;
}
/* Invariant: config dir exists.
*
* At this point, we're confident we'll be using XDG. We don't check if
* data dir exists, because if it doesn't we'll create it. */
config_dir = xdg_config_dir;
// create data directory if it doesn't exist
utils::mkdir_parents(xdg_data_dir, 0700);
/* in config */
url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file;
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
/* in data */
cache_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file;
lock_file = cache_file + LOCK_SUFFIX;
queue_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
searchfile = strprintf::fmt("%s%shistory.search", xdg_data_dir, NEWSBEUTER_PATH_SEP);
cmdlinefile = strprintf::fmt("%s%shistory.cmdline", xdg_data_dir, NEWSBEUTER_PATH_SEP);
return true;
}
pb_controller::pb_controller() : v(0), config_file("config"), queue_file("queue"), cfg(0), view_update_(true), max_dls(1), ql(0) {
char * cfgdir;
if (!(cfgdir = ::getenv("HOME"))) {
struct passwd * spw = ::getpwuid(::getuid());
if (spw) {
cfgdir = spw->pw_dir;
} else {
std::cout << _("Fatal error: couldn't determine home directory!") << std::endl;
std::cout << strprintf::fmt(_("Please set the HOME environment variable or add a valid user for UID %u!"), ::getuid()) << std::endl;
::exit(EXIT_FAILURE);
}
}
config_dir = cfgdir;
if (setup_dirs_xdg(cfgdir))
return;
config_dir.append(NEWSBEUTER_PATH_SEP);
config_dir.append(NEWSBEUTER_CONFIG_SUBDIR);
::mkdir(config_dir.c_str(),0700); // create configuration directory if it doesn't exist
config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file;
queue_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file;
lock_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + lock_file;
}
pb_controller::~pb_controller() {
delete cfg;
}
void pb_controller::run(int argc, char * argv[]) {
int c;
bool automatic_dl = false;
::signal(SIGINT, ctrl_c_action);
static const char getopt_str[] = "C:q:d:l:havV";
static const struct option longopts[] = {
{"config-file" , required_argument, 0, 'C'},
{"queue-file" , required_argument, 0, 'q'},
{"log-file" , required_argument, 0, 'd'},
{"log-level" , required_argument, 0, 'l'},
{"help" , no_argument , 0, 'h'},
{"autodownload" , no_argument , 0, 'a'},
{"version" , no_argument , 0, 'v'},
{0 , 0 , 0, 0 }
};
while ((c = ::getopt_long(argc, argv, getopt_str, longopts, nullptr)) != -1) {
switch (c) {
case ':':
case '?':
usage(argv[0]);
break;
case 'C':
config_file = optarg;
break;
case 'q':
queue_file = optarg;
break;
case 'a':
automatic_dl = true;
break;
case 'd':
logger::getInstance().set_logfile(optarg);
break;
case 'l': {
level l = static_cast<level>(atoi(optarg));
if (l > level::NONE && l <= level::DEBUG) {
logger::getInstance().set_loglevel(l);
} else {
std::cerr << strprintf::fmt(_("%s: %d: invalid loglevel value"), argv[0], l) << std::endl;
::std::exit(EXIT_FAILURE);
}
}
break;
case 'h':
usage(argv[0]);
break;
default:
std::cout << strprintf::fmt(_("%s: unknown option - %c"), argv[0], static_cast<char>(c)) << std::endl;
usage(argv[0]);
break;
}
};
std::cout << strprintf::fmt(_("Starting %s %s..."), "podbeuter", PROGRAM_VERSION) << std::endl;
pid_t pid;
if (!utils::try_fs_lock(lock_file, pid)) {
std::cout << strprintf::fmt(_("Error: an instance of %s is already running (PID: %u)"), "podbeuter", pid) << std::endl;
return;
}
std::cout << _("Loading configuration...");
std::cout.flush();
configparser cfgparser;
cfg = new configcontainer();
cfg->register_commands(cfgparser);
colormanager * colorman = new colormanager();
colorman->register_commands(cfgparser);
keymap keys(KM_PODBEUTER);
cfgparser.register_handler("bind-key", &keys);
cfgparser.register_handler("unbind-key", &keys);
null_config_action_handler null_cah;
cfgparser.register_handler("macro", &null_cah);
cfgparser.register_handler("ignore-article", &null_cah);
cfgparser.register_handler("always-download", &null_cah);
cfgparser.register_handler("define-filter", &null_cah);
cfgparser.register_handler("highlight", &null_cah);
cfgparser.register_handler("highlight-article", &null_cah);
cfgparser.register_handler("reset-unread-on-update", &null_cah);
try {
cfgparser.parse("/etc/newsbeuter/config");
cfgparser.parse(config_file);
} catch (const configexception& ex) {
std::cout << ex.what() << std::endl;
delete colorman;
return;
}
if (colorman->colors_loaded())
colorman->set_pb_colors(v);
delete colorman;
max_dls = cfg->get_configvalue_as_int("max-downloads");
std::cout << _("done.") << std::endl;
ql = new queueloader(queue_file, this);
ql->reload(downloads_);
v->set_keymap(&keys);
v->run(automatic_dl);
stfl::reset();
std::cout << _("Cleaning up queue...");
std::cout.flush();
ql->reload(downloads_);
delete ql;
std::cout << _("done.") << std::endl;
utils::remove_fs_lock(lock_file);
}
void pb_controller::usage(const char * argv0) {
auto msg =
strprintf::fmt(_("%s %s\nusage %s [-C <file>] [-q <file>] [-h]\n"),
"podbeuter",
PROGRAM_VERSION,
argv0);
std::cout << msg;
struct arg {
const char name;
const std::string longname;
const std::string params;
const std::string desc;
};
static const std::vector<arg> args = {
{ 'C', "config-file" , _s("<configfile>"), _s("read configuration from <configfile>") } ,
{ 'q', "queue-file" , _s("<queuefile>") , _s("use <queuefile> as queue file") } ,
{ 'a', "autodownload", "" , _s("start download on startup") } ,
{ 'l', "log-level" , _s("<loglevel>") , _s("write a log with a certain loglevel (valid values: 1 to 6)") },
{ 'd', "log-file" , _s("<logfile>") , _s("use <logfile> as output log file") } ,
{ 'h', "help" , "" , _s("this help") }
};
for (const auto & a : args) {
std::string longcolumn("-");
longcolumn += a.name;
longcolumn += ", --" + a.longname;
longcolumn += a.params.size() > 0 ? "=" + a.params : "";
std::cout << "\t" << longcolumn;
for (unsigned int j = 0; j < utils::gentabs(longcolumn); j++) {
std::cout << "\t";
}
std::cout << a.desc << std::endl;
}
::exit(EXIT_FAILURE);
}
std::string pb_controller::get_dlpath() {
return cfg->get_configvalue("download-path");
}
unsigned int pb_controller::downloads_in_progress() {
unsigned int count = 0;
for (auto dl : downloads_) {
if (dl.status() == dlstatus::DOWNLOADING)
++count;
}
return count;
}
unsigned int pb_controller::get_maxdownloads() {
return max_dls;
}
void pb_controller::reload_queue(bool remove_unplayed) {
if (ql) {
ql->reload(downloads_, remove_unplayed);
}
}
double pb_controller::get_total_kbps() {
double result = 0.0;
for (auto dl : downloads_) {
if (dl.status() == dlstatus::DOWNLOADING) {
result += dl.kbps();
}
}
return result;
}
void pb_controller::start_downloads() {
int dl2start = get_maxdownloads() - downloads_in_progress();
for (auto& download : downloads_) {
if (dl2start == 0) break;
if (download.status() == dlstatus::QUEUED) {
std::thread t {poddlthread(&download, cfg)};
--dl2start;
t.detach();
}
}
}
void pb_controller::increase_parallel_downloads() {
++max_dls;
}
void pb_controller::decrease_parallel_downloads() {
if (max_dls > 1)
--max_dls;
}
void pb_controller::play_file(const std::string& file) {
std::string cmdline;
std::string player = cfg->get_configvalue("player");
if (player == "")
return;
cmdline.append(player);
cmdline.append(" '");
cmdline.append(utils::replace_all(file,"'", "%27"));
cmdline.append("'");
stfl::reset();
utils::run_interactively(cmdline, "pb_controller::play_file");
}
} // namespace
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/good_2800_0 |
crossvul-cpp_data_bad_2799_1 | #include <stflpp.h>
#include <utils.h>
#include <queueloader.h>
#include <cstdlib>
#include <logger.h>
#include <fstream>
#include <cstring>
#include <config.h>
#include <libgen.h>
#include <unistd.h>
using namespace newsbeuter;
namespace podbeuter {
queueloader::queueloader(const std::string& file, pb_controller * c) : queuefile(file), ctrl(c) {
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed) {
std::vector<download> dltemp;
std::fstream f;
for (auto dl : downloads) {
if (dl.status() == DL_DOWNLOADING) { // we are not allowed to reload if a download is in progress!
LOG(LOG_INFO, "queueloader::reload: aborting reload due to DL_DOWNLOADING status");
return;
}
switch (dl.status()) {
case DL_QUEUED:
case DL_CANCELLED:
case DL_FAILED:
case DL_ALREADY_DOWNLOADED:
case DL_READY:
LOG(LOG_DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
break;
case DL_PLAYED:
case DL_FINISHED:
if (!remove_unplayed) {
LOG(LOG_DEBUG, "queueloader::reload: storing %s to new vector", dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
if (f.is_open()) {
std::string line;
do {
getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(LOG_DEBUG, "queueloader::reload: loaded `%s' from queue file", line.c_str());
std::vector<std::string> fields = utils::tokenize_quoted(line);
bool url_found = false;
for (auto dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(LOG_INFO, "queueloader::reload: found `%s' in old vector", fields[0].c_str());
url_found = true;
break;
}
}
for (auto dl : downloads) {
if (fields[0] == dl.url()) {
LOG(LOG_INFO, "queueloader::reload: found `%s' in new vector", line.c_str());
url_found = true;
break;
}
}
if (!url_found) {
LOG(LOG_INFO, "queueloader::reload: found `%s' nowhere -> storing to new vector", line.c_str());
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK)==0) {
LOG(LOG_INFO, "queueloader::reload: found `%s' on file system -> mark as already downloaded", fn.c_str());
if (fields.size() >= 3) {
if (fields[2] == "downloaded")
d.set_status(DL_READY);
if (fields[2] == "played")
d.set_status(DL_PLAYED);
} else
d.set_status(DL_ALREADY_DOWNLOADED); // TODO: scrap DL_ALREADY_DOWNLOADED state
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (auto dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == DL_READY)
f << " downloaded";
if (dl.status() == DL_PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str) {
std::string fn = ctrl->get_dlpath();
if (fn[fn.length()-1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char * base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(NULL);
strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t));
fn.append(lbuf);
} else {
fn.append(base);
}
return fn;
}
}
| ./CrossVul/dataset_final_sorted/CWE-78/cpp/bad_2799_1 |
crossvul-cpp_data_good_4099_0 | /* radare - LGPL - Copyright 2014-2017 - inisider */
#include <string.h>
#include <r_util.h>
#include <r_core.h>
#include "pdb_downloader.h"
static bool checkExtract() {
#if __WINDOWS__
if (r_sys_cmd ("expand -? >nul") != 0) {
return false;
}
#else
if (r_sys_cmd ("cabextract -v > /dev/null") != 0) {
return false;
}
#endif
return true;
}
static bool download_and_write(SPDBDownloaderOpt *opt, const char *file) {
char *dir = r_str_newf ("%s%s%s%s%s",
opt->symbol_store_path, R_SYS_DIR,
opt->dbg_file, R_SYS_DIR,
opt->guid);
if (!r_sys_mkdirp (dir)) {
free (dir);
return false;
}
char *url = r_str_newf ("%s/%s/%s/%s", opt->symbol_server, opt->dbg_file, opt->guid, file);
int len;
char *file_buf = r_socket_http_get (url, NULL, &len);
free (url);
if (!len || R_STR_ISEMPTY (file_buf)) {
free (dir);
free (file_buf);
return false;
}
char *path = r_str_newf ("%s%s%s", dir, R_SYS_DIR, opt->dbg_file);
FILE *f = fopen (path, "wb");
if (f) {
fwrite (file_buf, sizeof (char), (size_t)len, f);
fclose (f);
}
free (dir);
free (path);
free (file_buf);
return true;
}
static int download(struct SPDBDownloader *pd) {
SPDBDownloaderOpt *opt = pd->opt;
int res = 0;
int cmd_ret;
if (!opt->dbg_file || !*opt->dbg_file) {
// no pdb debug file
return 0;
}
char *abspath_to_file = r_str_newf ("%s%s%s%s%s%s%s",
opt->symbol_store_path, R_SYS_DIR,
opt->dbg_file, R_SYS_DIR,
opt->guid, R_SYS_DIR,
opt->dbg_file);
if (r_file_exists (abspath_to_file)) {
eprintf ("File already downloaded.\n");
free (abspath_to_file);
return 1;
}
if (checkExtract () || opt->extract == 0) {
char *extractor_cmd = NULL;
char *archive_name = strdup (opt->dbg_file);
archive_name[strlen (archive_name) - 1] = '_';
char *abspath_to_archive = r_str_newf ("%s%s%s%s%s%s%s",
opt->symbol_store_path, R_SYS_DIR,
opt->dbg_file, R_SYS_DIR,
opt->guid, R_SYS_DIR,
archive_name);
eprintf ("Attempting to download compressed pdb in %s\n", abspath_to_archive);
char *abs_arch_esc = r_str_escape_sh (abspath_to_archive);
#if __WINDOWS__
char *abs_file_esc = r_str_escape_sh (abspath_to_file);
// expand %1 %2
// %1 - absolute path to archive
// %2 - absolute path to file that will be dearchive
extractor_cmd = r_str_newf ("expand \"%s\" \"%s\"", abs_arch_esc, abs_file_esc);
free (abs_file_esc);
#else
char *abspath_to_dir = r_file_dirname (abspath_to_archive);
char *abs_dir_esc = r_str_escape_sh (abspath_to_dir);
// cabextract -d %1 %2
// %1 - path to directory where to extract all files from cab archive
// %2 - absolute path to cab archive
extractor_cmd = r_str_newf ("cabextract -d \"%s\" \"%s\"", abs_arch_esc, abs_dir_esc);
free (abs_dir_esc);
free (abspath_to_dir);
#endif
free (abs_arch_esc);
res = download_and_write (opt, archive_name);
if (opt->extract > 0 && res) {
eprintf ("Attempting to decompress pdb\n");
if (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {
eprintf ("cab extractor exited with error %d\n", cmd_ret);
res = 0;
}
r_file_rm (abspath_to_archive);
}
free (archive_name);
free (abspath_to_archive);
}
if (res == 0) {
eprintf ("Falling back to uncompressed pdb\n");
eprintf ("Attempting to download uncompressed pdb in %s\n", abspath_to_file);
res = download_and_write (opt, opt->dbg_file);
}
free (abspath_to_file);
return res;
}
void init_pdb_downloader(SPDBDownloaderOpt *opt, SPDBDownloader *pd) {
pd->opt = R_NEW0 (SPDBDownloaderOpt);
if (!pd->opt) {
pd->download = 0;
eprintf ("Cannot allocate memory for SPDBDownloaderOpt.\n");
return;
}
pd->opt->dbg_file = strdup (opt->dbg_file);
pd->opt->guid = strdup (opt->guid);
pd->opt->symbol_server = strdup (opt->symbol_server);
pd->opt->user_agent = strdup (opt->user_agent);
pd->opt->symbol_store_path = strdup (opt->symbol_store_path);
pd->opt->extract = opt->extract;
pd->download = download;
}
void deinit_pdb_downloader(SPDBDownloader *pd) {
R_FREE (pd->opt->dbg_file);
R_FREE (pd->opt->guid);
R_FREE (pd->opt->symbol_server);
R_FREE (pd->opt->user_agent);
R_FREE (pd->opt->symbol_store_path);
R_FREE (pd->opt);
pd->download = 0;
}
static bool is_valid_guid(const char *guid) {
if (!guid) {
return false;
}
size_t i;
for (i = 0; guid[i]; i++) {
if (!isxdigit (guid[i])) {
return false;
}
}
return i >= 33; // len of GUID and age
}
int r_bin_pdb_download(RCore *core, int isradjson, int *actions_done, SPDBOptions *options) {
int ret;
SPDBDownloaderOpt opt;
SPDBDownloader pdb_downloader;
RBinInfo *info = r_bin_get_info (core->bin);
if (!info || !info->debug_file_name) {
eprintf ("Can't find debug filename\n");
return 1;
}
if (!is_valid_guid (info->guid)) {
eprintf ("Invalid GUID for file\n");
return 1;
}
if (!options || !options->symbol_server || !options->user_agent) {
eprintf ("Can't retrieve pdb configurations\n");
return 1;
}
opt.dbg_file = (char*) r_file_basename (info->debug_file_name);
opt.guid = info->guid;
opt.symbol_server = options->symbol_server;
opt.user_agent = options->user_agent;
opt.symbol_store_path = options->symbol_store_path;
opt.extract = options->extract;
init_pdb_downloader (&opt, &pdb_downloader);
ret = pdb_downloader.download ? pdb_downloader.download (&pdb_downloader) : 0;
if (isradjson && actions_done) {
printf ("%s\"pdb\":{\"file\":\"%s\",\"download\":%s}",
*actions_done ? "," : "", opt.dbg_file, ret ? "true" : "false");
} else {
printf ("PDB \"%s\" download %s\n",
opt.dbg_file, ret ? "success" : "failed");
}
if (actions_done) {
(*actions_done)++;
}
deinit_pdb_downloader (&pdb_downloader);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/good_4099_0 |
crossvul-cpp_data_bad_2888_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-78/c/bad_2888_0 |
crossvul-cpp_data_good_2888_0 | /*
* server.c - Provide shadowsocks service
*
* Copyright (C) 2013 - 2017, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev 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.
*
* shadowsocks-libev 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 shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <dirent.h>
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <pwd.h>
#include <libcork/core.h>
#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
#include <net/if.h>
#include <sys/ioctl.h>
#define SET_INTERFACE
#endif
#include "json.h"
#include "utils.h"
#include "manager.h"
#include "netutils.h"
#ifndef BUF_SIZE
#define BUF_SIZE 65535
#endif
int verbose = 0;
char *executable = "ss-server";
char *working_dir = NULL;
int working_dir_size = 0;
static struct cork_hash_table *server_table;
static int
setnonblocking(int fd)
{
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
static void
destroy_server(struct server *server) {
// function used to free memories alloced in **get_server**
if (server->method) ss_free(server->method);
if (server->plugin) ss_free(server->plugin);
if (server->plugin_opts) ss_free(server->plugin_opts);
if (server->mode) ss_free(server->mode);
}
static void
build_config(char *prefix, struct manager_ctx *manager, struct server *server)
{
char *path = NULL;
int path_size = strlen(prefix) + strlen(server->port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port);
FILE *f = fopen(path, "w+");
if (f == NULL) {
if (verbose) {
LOGE("unable to open config file");
}
ss_free(path);
return;
}
fprintf(f, "{\n");
fprintf(f, "\"server_port\":%d,\n", atoi(server->port));
fprintf(f, "\"password\":\"%s\"", server->password);
if (server->method)
fprintf(f, ",\n\"method\":\"%s\"", server->method);
else if (manager->method)
fprintf(f, ",\n\"method\":\"%s\"", manager->method);
if (server->fast_open[0])
fprintf(f, ",\n\"fast_open\": %s", server->fast_open);
if (server->mode)
fprintf(f, ",\n\"mode\":\"%s\"", server->mode);
if (server->plugin)
fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin);
if (server->plugin_opts)
fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts);
fprintf(f, "\n}\n");
fclose(f);
ss_free(path);
}
static char *
construct_command_line(struct manager_ctx *manager, struct server *server)
{
static char cmd[BUF_SIZE];
int i;
int port;
port = atoi(server->port);
build_config(working_dir, manager, server);
memset(cmd, 0, BUF_SIZE);
snprintf(cmd, BUF_SIZE,
"%s --manager-address %s -f %s/.shadowsocks_%d.pid -c %s/.shadowsocks_%d.conf",
executable, manager->manager_address, working_dir, port, working_dir, port);
if (manager->acl != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl);
}
if (manager->timeout != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout);
}
#ifdef HAVE_SETRLIMIT
if (manager->nofile) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile);
}
#endif
if (manager->user != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user);
}
if (manager->verbose) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -v");
}
if (server->mode == NULL && manager->mode == UDP_ONLY) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -U");
}
if (server->mode == NULL && manager->mode == TCP_AND_UDP) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -u");
}
if (server->fast_open[0] == 0 && manager->fast_open) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --fast-open");
}
if (manager->ipv6first) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -6");
}
if (manager->mtu) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu);
}
if (server->plugin == NULL && manager->plugin) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --plugin \"%s\"", manager->plugin);
}
if (server->plugin_opts == NULL && manager->plugin_opts) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --plugin-opts \"%s\"", manager->plugin_opts);
}
for (i = 0; i < manager->nameserver_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]);
}
for (i = 0; i < manager->host_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]);
}
// Always enable reuse port
{
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --reuse-port");
}
if (verbose) {
LOGI("cmd: %s", cmd);
}
return cmd;
}
static char *
get_data(char *buf, int len)
{
char *data;
int pos = 0;
while (pos < len && buf[pos] != '{')
pos++;
if (pos == len) {
return NULL;
}
data = buf + pos - 1;
return data;
}
static char *
get_action(char *buf, int len)
{
char *action;
int pos = 0;
while (pos < len && isspace((unsigned char)buf[pos]))
pos++;
if (pos == len) {
return NULL;
}
action = buf + pos;
while (pos < len && (!isspace((unsigned char)buf[pos]) && buf[pos] != ':'))
pos++;
buf[pos] = '\0';
return action;
}
static struct server *
get_server(char *buf, int len)
{
char *data = get_data(buf, len);
char error_buf[512];
if (data == NULL) {
LOGE("No data found");
return NULL;
}
json_settings settings = { 0 };
json_value *obj = json_parse_ex(&settings, data, strlen(data), error_buf);
if (obj == NULL) {
LOGE("%s", error_buf);
return NULL;
}
struct server *server = ss_malloc(sizeof(struct server));
memset(server, 0, sizeof(struct server));
if (obj->type == json_object) {
int i = 0;
for (i = 0; i < obj->u.object.length; i++) {
char *name = obj->u.object.values[i].name;
json_value *value = obj->u.object.values[i].value;
if (strcmp(name, "server_port") == 0) {
if (value->type == json_string) {
strncpy(server->port, value->u.string.ptr, 8);
} else if (value->type == json_integer) {
snprintf(server->port, 8, "%" PRIu64 "", value->u.integer);
}
} else if (strcmp(name, "password") == 0) {
if (value->type == json_string) {
strncpy(server->password, value->u.string.ptr, 128);
}
} else if (strcmp(name, "method") == 0) {
if (value->type == json_string) {
server->method = strdup(value->u.string.ptr);
}
} else if (strcmp(name, "fast_open") == 0) {
if (value->type == json_boolean) {
strncpy(server->fast_open, (value->u.boolean ? "true" : "false"), 8);
}
} else if (strcmp(name, "plugin") == 0) {
if (value->type == json_string) {
server->plugin = strdup(value->u.string.ptr);
}
} else if (strcmp(name, "plugin_opts") == 0) {
if (value->type == json_string) {
server->plugin_opts = strdup(value->u.string.ptr);
}
} else if (strcmp(name, "mode") == 0) {
if (value->type == json_string) {
server->mode = strdup(value->u.string.ptr);
}
} else {
LOGE("invalid data: %s", data);
break;
}
}
}
json_value_free(obj);
return server;
}
static int
parse_traffic(char *buf, int len, char *port, uint64_t *traffic)
{
char *data = get_data(buf, len);
char error_buf[512];
json_settings settings = { 0 };
if (data == NULL) {
LOGE("No data found");
return -1;
}
json_value *obj = json_parse_ex(&settings, data, strlen(data), error_buf);
if (obj == NULL) {
LOGE("%s", error_buf);
return -1;
}
if (obj->type == json_object) {
int i = 0;
for (i = 0; i < obj->u.object.length; i++) {
char *name = obj->u.object.values[i].name;
json_value *value = obj->u.object.values[i].value;
if (value->type == json_integer) {
strncpy(port, name, 8);
*traffic = value->u.integer;
}
}
}
json_value_free(obj);
return 0;
}
static int
create_and_bind(const char *host, const char *port, int protocol)
{
struct addrinfo hints;
struct addrinfo *result, *rp, *ipv4v6bindall;
int s, listen_sock = -1;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = protocol == IPPROTO_TCP ?
SOCK_STREAM : SOCK_DGRAM; /* We want a TCP or UDP socket */
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; /* For wildcard IP address */
hints.ai_protocol = protocol;
s = getaddrinfo(host, port, &hints, &result);
if (s != 0) {
LOGE("getaddrinfo: %s", gai_strerror(s));
return -1;
}
rp = result;
/*
* On Linux, with net.ipv6.bindv6only = 0 (the default), getaddrinfo(NULL) with
* AI_PASSIVE returns 0.0.0.0 and :: (in this order). AI_PASSIVE was meant to
* return a list of addresses to listen on, but it is impossible to listen on
* 0.0.0.0 and :: at the same time, if :: implies dualstack mode.
*/
if (!host) {
ipv4v6bindall = result;
/* Loop over all address infos found until a IPV6 address is found. */
while (ipv4v6bindall) {
if (ipv4v6bindall->ai_family == AF_INET6) {
rp = ipv4v6bindall; /* Take first IPV6 address available */
break;
}
ipv4v6bindall = ipv4v6bindall->ai_next; /* Get next address info, if any */
}
}
for (/*rp = result*/; rp != NULL; rp = rp->ai_next) {
listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (listen_sock == -1) {
continue;
}
if (rp->ai_family == AF_INET6) {
int ipv6only = host ? 1 : 0;
setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6only, sizeof(ipv6only));
}
int opt = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
close(listen_sock);
break;
} else {
ERROR("bind");
}
}
if (!result) {
freeaddrinfo(result);
}
if (rp == NULL) {
LOGE("Could not bind");
return -1;
}
return listen_sock;
}
static int
check_port(struct manager_ctx *manager, struct server *server)
{
bool both_tcp_udp = manager->mode == TCP_AND_UDP;
int fd_count = manager->host_num * (both_tcp_udp ? 2 : 1);
int bind_err = 0;
int *sock_fds = (int *)ss_malloc(fd_count * sizeof(int));
memset(sock_fds, 0, fd_count * sizeof(int));
/* try to bind each interface */
for (int i = 0; i < manager->host_num; i++) {
LOGI("try to bind interface: %s, port: %s", manager->hosts[i], server->port);
if (manager->mode == UDP_ONLY) {
sock_fds[i] = create_and_bind(manager->hosts[i], server->port, IPPROTO_UDP);
} else {
sock_fds[i] = create_and_bind(manager->hosts[i], server->port, IPPROTO_TCP);
}
if (both_tcp_udp) {
sock_fds[i + manager->host_num] = create_and_bind(manager->hosts[i], server->port, IPPROTO_UDP);
}
if (sock_fds[i] == -1 || (both_tcp_udp && sock_fds[i + manager->host_num] == -1)) {
bind_err = -1;
break;
}
}
/* clean socks */
for (int i = 0; i < fd_count; i++) {
if (sock_fds[i] > 0) {
close(sock_fds[i]);
}
}
ss_free(sock_fds);
return bind_err == -1 ? -1 : 0;
}
static int
add_server(struct manager_ctx *manager, struct server *server)
{
int ret = check_port(manager, server);
if (ret == -1) {
LOGE("port is not available, please check.");
return -1;
}
bool new = false;
cork_hash_table_put(server_table, (void *)server->port, (void *)server, &new, NULL, NULL);
char *cmd = construct_command_line(manager, server);
if (system(cmd) == -1) {
ERROR("add_server_system");
return -1;
}
return 0;
}
static void
kill_server(char *prefix, char *pid_file)
{
char *path = NULL;
int pid, path_size = strlen(prefix) + strlen(pid_file) + 2;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/%s", prefix, pid_file);
FILE *f = fopen(path, "r");
if (f == NULL) {
if (verbose) {
LOGE("unable to open pid file");
}
ss_free(path);
return;
}
if (fscanf(f, "%d", &pid) != EOF) {
kill(pid, SIGTERM);
}
fclose(f);
remove(path);
ss_free(path);
}
static void
stop_server(char *prefix, char *port)
{
char *path = NULL;
int pid, path_size = strlen(prefix) + strlen(port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.pid", prefix, port);
FILE *f = fopen(path, "r");
if (f == NULL) {
if (verbose) {
LOGE("unable to open pid file");
}
ss_free(path);
return;
}
if (fscanf(f, "%d", &pid) != EOF) {
kill(pid, SIGTERM);
}
fclose(f);
ss_free(path);
}
static void
remove_server(char *prefix, char *port)
{
char *old_port = NULL;
struct server *old_server = NULL;
cork_hash_table_delete(server_table, (void *)port, (void **)&old_port, (void **)&old_server);
if (old_server != NULL) {
destroy_server(old_server);
ss_free(old_server);
}
stop_server(prefix, port);
}
static void
update_stat(char *port, uint64_t traffic)
{
if (verbose) {
LOGI("update traffic %" PRIu64 " for port %s", traffic, port);
}
void *ret = cork_hash_table_get(server_table, (void *)port);
if (ret != NULL) {
struct server *server = (struct server *)ret;
server->traffic = traffic;
}
}
static void
manager_recv_cb(EV_P_ ev_io *w, int revents)
{
struct manager_ctx *manager = (struct manager_ctx *)w;
socklen_t len;
ssize_t r;
struct sockaddr_un claddr;
char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
len = sizeof(struct sockaddr_un);
r = recvfrom(manager->fd, buf, BUF_SIZE, 0, (struct sockaddr *)&claddr, &len);
if (r == -1) {
ERROR("manager_recvfrom");
return;
}
if (r > BUF_SIZE / 2) {
LOGE("too large request: %d", (int)r);
return;
}
char *action = get_action(buf, r);
if (action == NULL) {
return;
}
if (strcmp(action, "add") == 0) {
struct server *server = get_server(buf, r);
if (server == NULL || server->port[0] == 0 || server->password[0] == 0) {
LOGE("invalid command: %s:%s", buf, get_data(buf, r));
if (server != NULL) {
destroy_server(server);
ss_free(server);
}
goto ERROR_MSG;
}
remove_server(working_dir, server->port);
int ret = add_server(manager, server);
char *msg;
int msg_len;
if (ret == -1) {
msg = "port is not available";
msg_len = 21;
} else {
msg = "ok";
msg_len = 2;
}
if (sendto(manager->fd, msg, msg_len, 0, (struct sockaddr *)&claddr, len) != 2) {
ERROR("add_sendto");
}
} else if (strcmp(action, "list") == 0) {
struct cork_hash_table_iterator iter;
struct cork_hash_table_entry *entry;
char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
sprintf(buf, "[");
cork_hash_table_iterator_init(server_table, &iter);
while ((entry = cork_hash_table_iterator_next(&iter)) != NULL) {
struct server *server = (struct server *)entry->value;
char *method = server->method?server->method:manager->method;
size_t pos = strlen(buf);
size_t entry_len = strlen(server->port) + strlen(server->password) + strlen(method);
if (pos > BUF_SIZE-entry_len-50) {
if (sendto(manager->fd, buf, pos, 0, (struct sockaddr *)&claddr, len)
!= pos) {
ERROR("list_sendto");
}
memset(buf, 0, BUF_SIZE);
pos = 0;
}
sprintf(buf + pos, "\n\t{\"server_port\":\"%s\",\"password\":\"%s\",\"method\":\"%s\"},",
server->port,server->password,method);
}
size_t pos = strlen(buf);
strcpy(buf + pos - 1, "\n]"); //Remove trailing ","
pos = strlen(buf);
if (sendto(manager->fd, buf, pos, 0, (struct sockaddr *)&claddr, len)
!= pos) {
ERROR("list_sendto");
}
} else if (strcmp(action, "remove") == 0) {
struct server *server = get_server(buf, r);
if (server == NULL || server->port[0] == 0) {
LOGE("invalid command: %s:%s", buf, get_data(buf, r));
if (server != NULL) {
destroy_server(server);
ss_free(server);
}
goto ERROR_MSG;
}
remove_server(working_dir, server->port);
destroy_server(server);
ss_free(server);
char msg[3] = "ok";
if (sendto(manager->fd, msg, 2, 0, (struct sockaddr *)&claddr, len) != 2) {
ERROR("remove_sendto");
}
} else if (strcmp(action, "stat") == 0) {
char port[8];
uint64_t traffic = 0;
if (parse_traffic(buf, r, port, &traffic) == -1) {
LOGE("invalid command: %s:%s", buf, get_data(buf, r));
return;
}
update_stat(port, traffic);
} else if (strcmp(action, "ping") == 0) {
struct cork_hash_table_entry *entry;
struct cork_hash_table_iterator server_iter;
char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
sprintf(buf, "stat: {");
cork_hash_table_iterator_init(server_table, &server_iter);
while ((entry = cork_hash_table_iterator_next(&server_iter)) != NULL) {
struct server *server = (struct server *)entry->value;
size_t pos = strlen(buf);
if (pos > BUF_SIZE / 2) {
buf[pos - 1] = '}';
if (sendto(manager->fd, buf, pos, 0, (struct sockaddr *)&claddr, len)
!= pos) {
ERROR("ping_sendto");
}
memset(buf, 0, BUF_SIZE);
} else {
sprintf(buf + pos, "\"%s\":%" PRIu64 ",", server->port, server->traffic);
}
}
size_t pos = strlen(buf);
if (pos > 7) {
buf[pos - 1] = '}';
} else {
buf[pos] = '}';
pos++;
}
if (sendto(manager->fd, buf, pos, 0, (struct sockaddr *)&claddr, len)
!= pos) {
ERROR("ping_sendto");
}
}
return;
ERROR_MSG:
strcpy(buf, "err");
if (sendto(manager->fd, buf, 3, 0, (struct sockaddr *)&claddr, len) != 3) {
ERROR("error_sendto");
}
}
static void
signal_cb(EV_P_ ev_signal *w, int revents)
{
if (revents & EV_SIGNAL) {
switch (w->signum) {
case SIGINT:
case SIGTERM:
ev_unloop(EV_A_ EVUNLOOP_ALL);
}
}
}
int
create_server_socket(const char *host, const char *port)
{
struct addrinfo hints;
struct addrinfo *result, *rp, *ipv4v6bindall;
int s, server_sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_DGRAM; /* We want a UDP socket */
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; /* For wildcard IP address */
hints.ai_protocol = IPPROTO_UDP;
s = getaddrinfo(host, port, &hints, &result);
if (s != 0) {
LOGE("getaddrinfo: %s", gai_strerror(s));
return -1;
}
rp = result;
/*
* On Linux, with net.ipv6.bindv6only = 0 (the default), getaddrinfo(NULL) with
* AI_PASSIVE returns 0.0.0.0 and :: (in this order). AI_PASSIVE was meant to
* return a list of addresses to listen on, but it is impossible to listen on
* 0.0.0.0 and :: at the same time, if :: implies dualstack mode.
*/
if (!host) {
ipv4v6bindall = result;
/* Loop over all address infos found until a IPV6 address is found. */
while (ipv4v6bindall) {
if (ipv4v6bindall->ai_family == AF_INET6) {
rp = ipv4v6bindall; /* Take first IPV6 address available */
break;
}
ipv4v6bindall = ipv4v6bindall->ai_next; /* Get next address info, if any */
}
}
for (/*rp = result*/; rp != NULL; rp = rp->ai_next) {
server_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (server_sock == -1) {
continue;
}
if (rp->ai_family == AF_INET6) {
int ipv6only = host ? 1 : 0;
setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6only, sizeof(ipv6only));
}
int opt = 1;
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
s = bind(server_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
} else {
ERROR("bind");
}
close(server_sock);
}
if (rp == NULL) {
LOGE("cannot bind");
return -1;
}
freeaddrinfo(result);
return server_sock;
}
int
main(int argc, char **argv)
{
int i, c;
int pid_flags = 0;
char *acl = NULL;
char *user = NULL;
char *password = NULL;
char *timeout = NULL;
char *method = NULL;
char *pid_path = NULL;
char *conf_path = NULL;
char *iface = NULL;
char *manager_address = NULL;
char *plugin = NULL;
char *plugin_opts = NULL;
int fast_open = 0;
int reuse_port = 0;
int mode = TCP_ONLY;
int mtu = 0;
int ipv6first = 0;
#ifdef HAVE_SETRLIMIT
static int nofile = 0;
#endif
int server_num = 0;
char *server_host[MAX_REMOTE_NUM];
char *nameservers[MAX_DNS_NUM + 1];
int nameserver_num = 0;
jconf_t *conf = NULL;
static struct option long_options[] = {
{ "fast-open", no_argument, NULL, GETOPT_VAL_FAST_OPEN },
{ "reuse-port", no_argument, NULL, GETOPT_VAL_REUSE_PORT },
{ "acl", required_argument, NULL, GETOPT_VAL_ACL },
{ "manager-address", required_argument, NULL,
GETOPT_VAL_MANAGER_ADDRESS },
{ "executable", required_argument, NULL,
GETOPT_VAL_EXECUTABLE },
{ "mtu", required_argument, NULL, GETOPT_VAL_MTU },
{ "plugin", required_argument, NULL, GETOPT_VAL_PLUGIN },
{ "plugin-opts", required_argument, NULL, GETOPT_VAL_PLUGIN_OPTS },
{ "password", required_argument, NULL, GETOPT_VAL_PASSWORD },
{ "help", no_argument, NULL, GETOPT_VAL_HELP },
{ NULL, 0, NULL, 0 }
};
opterr = 0;
USE_TTY();
while ((c = getopt_long(argc, argv, "f:s:l:k:t:m:c:i:d:a:n:6huUvA",
long_options, NULL)) != -1)
switch (c) {
case GETOPT_VAL_REUSE_PORT:
reuse_port = 1;
break;
case GETOPT_VAL_FAST_OPEN:
fast_open = 1;
break;
case GETOPT_VAL_ACL:
acl = optarg;
break;
case GETOPT_VAL_MANAGER_ADDRESS:
manager_address = optarg;
break;
case GETOPT_VAL_EXECUTABLE:
executable = optarg;
break;
case GETOPT_VAL_MTU:
mtu = atoi(optarg);
break;
case GETOPT_VAL_PLUGIN:
plugin = optarg;
break;
case GETOPT_VAL_PLUGIN_OPTS:
plugin_opts = optarg;
break;
case 's':
if (server_num < MAX_REMOTE_NUM) {
server_host[server_num++] = optarg;
}
break;
case GETOPT_VAL_PASSWORD:
case 'k':
password = optarg;
break;
case 'f':
pid_flags = 1;
pid_path = optarg;
break;
case 't':
timeout = optarg;
break;
case 'm':
method = optarg;
break;
case 'c':
conf_path = optarg;
break;
case 'i':
iface = optarg;
break;
case 'd':
if (nameserver_num < MAX_DNS_NUM) {
nameservers[nameserver_num++] = optarg;
}
break;
case 'a':
user = optarg;
break;
case 'u':
mode = TCP_AND_UDP;
break;
case 'U':
mode = UDP_ONLY;
break;
case '6':
ipv6first = 1;
break;
case 'v':
verbose = 1;
break;
case GETOPT_VAL_HELP:
case 'h':
usage();
exit(EXIT_SUCCESS);
#ifdef HAVE_SETRLIMIT
case 'n':
nofile = atoi(optarg);
break;
#endif
case 'A':
FATAL("One time auth has been deprecated. Try AEAD ciphers instead.");
break;
case '?':
// The option character is not recognized.
LOGE("Unrecognized option: %s", optarg);
opterr = 1;
break;
}
if (opterr) {
usage();
exit(EXIT_FAILURE);
}
if (conf_path != NULL) {
conf = read_jconf(conf_path);
if (server_num == 0) {
server_num = conf->remote_num;
for (i = 0; i < server_num; i++)
server_host[i] = conf->remote_addr[i].host;
}
if (password == NULL) {
password = conf->password;
}
if (method == NULL) {
method = conf->method;
}
if (timeout == NULL) {
timeout = conf->timeout;
}
if (user == NULL) {
user = conf->user;
}
if (fast_open == 0) {
fast_open = conf->fast_open;
}
if (reuse_port == 0) {
reuse_port = conf->reuse_port;
}
if (conf->nameserver != NULL) {
nameservers[nameserver_num++] = conf->nameserver;
}
if (mode == TCP_ONLY) {
mode = conf->mode;
}
if (mtu == 0) {
mtu = conf->mtu;
}
if (plugin == NULL) {
plugin = conf->plugin;
}
if (plugin_opts == NULL) {
plugin_opts = conf->plugin_opts;
}
if (ipv6first == 0) {
ipv6first = conf->ipv6_first;
}
#ifdef HAVE_SETRLIMIT
if (nofile == 0) {
nofile = conf->nofile;
}
#endif
}
if (server_num == 0) {
server_host[server_num++] = "0.0.0.0";
}
if (method == NULL) {
method = "table";
}
if (timeout == NULL) {
timeout = "60";
}
USE_SYSLOG(argv[0], pid_flags);
if (pid_flags) {
daemonize(pid_path);
}
if (manager_address == NULL) {
manager_address = "127.0.0.1:8839";
LOGI("using the default manager address: %s", manager_address);
}
if (server_num == 0 || manager_address == NULL) {
usage();
exit(EXIT_FAILURE);
}
if (fast_open == 1) {
#ifdef TCP_FASTOPEN
LOGI("using tcp fast open");
#else
LOGE("tcp fast open is not supported by this environment");
#endif
}
// ignore SIGPIPE
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
signal(SIGABRT, SIG_IGN);
struct ev_signal sigint_watcher;
struct ev_signal sigterm_watcher;
ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
ev_signal_start(EV_DEFAULT, &sigint_watcher);
ev_signal_start(EV_DEFAULT, &sigterm_watcher);
struct manager_ctx manager;
memset(&manager, 0, sizeof(struct manager_ctx));
manager.reuse_port = reuse_port;
manager.fast_open = fast_open;
manager.verbose = verbose;
manager.mode = mode;
manager.password = password;
manager.timeout = timeout;
manager.method = method;
manager.iface = iface;
manager.acl = acl;
manager.user = user;
manager.manager_address = manager_address;
manager.hosts = server_host;
manager.host_num = server_num;
manager.nameservers = nameservers;
manager.nameserver_num = nameserver_num;
manager.mtu = mtu;
manager.plugin = plugin;
manager.plugin_opts = plugin_opts;
manager.ipv6first = ipv6first;
#ifdef HAVE_SETRLIMIT
manager.nofile = nofile;
#endif
// initialize ev loop
struct ev_loop *loop = EV_DEFAULT;
if (geteuid() == 0) {
LOGI("running from root user");
}
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
working_dir_size = strlen(homedir) + 15;
working_dir = ss_malloc(working_dir_size);
snprintf(working_dir, working_dir_size, "%s/.shadowsocks", homedir);
int err = mkdir(working_dir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (err != 0 && errno != EEXIST) {
ERROR("mkdir");
ss_free(working_dir);
FATAL("unable to create working directory");
}
// Clean up all existed processes
DIR *dp;
struct dirent *ep;
dp = opendir(working_dir);
if (dp != NULL) {
while ((ep = readdir(dp)) != NULL) {
size_t len = strlen(ep->d_name);
if (strcmp(ep->d_name + len - 3, "pid") == 0) {
kill_server(working_dir, ep->d_name);
if (verbose)
LOGI("kill %s", ep->d_name);
}
}
closedir(dp);
} else {
ss_free(working_dir);
FATAL("Couldn't open the directory");
}
server_table = cork_string_hash_table_new(MAX_PORT_NUM, 0);
if (conf != NULL) {
for (i = 0; i < conf->port_password_num; i++) {
struct server *server = ss_malloc(sizeof(struct server));
memset(server, 0, sizeof(struct server));
strncpy(server->port, conf->port_password[i].port, 8);
strncpy(server->password, conf->port_password[i].password, 128);
add_server(&manager, server);
}
}
int sfd;
ss_addr_t ip_addr = { .host = NULL, .port = NULL };
parse_addr(manager_address, &ip_addr);
if (ip_addr.host == NULL || ip_addr.port == NULL) {
struct sockaddr_un svaddr;
sfd = socket(AF_UNIX, SOCK_DGRAM, 0); /* Create server socket */
if (sfd == -1) {
ss_free(working_dir);
FATAL("socket");
}
setnonblocking(sfd);
if (remove(manager_address) == -1 && errno != ENOENT) {
ERROR("bind");
ss_free(working_dir);
exit(EXIT_FAILURE);
}
memset(&svaddr, 0, sizeof(struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
strncpy(svaddr.sun_path, manager_address, sizeof(svaddr.sun_path) - 1);
if (bind(sfd, (struct sockaddr *)&svaddr, sizeof(struct sockaddr_un)) == -1) {
ERROR("bind");
ss_free(working_dir);
exit(EXIT_FAILURE);
}
} else {
sfd = create_server_socket(ip_addr.host, ip_addr.port);
if (sfd == -1) {
ss_free(working_dir);
FATAL("socket");
}
}
manager.fd = sfd;
ev_io_init(&manager.io, manager_recv_cb, manager.fd, EV_READ);
ev_io_start(loop, &manager.io);
// start ev loop
ev_run(loop, 0);
if (verbose) {
LOGI("closed gracefully");
}
// Clean up
struct cork_hash_table_entry *entry;
struct cork_hash_table_iterator server_iter;
cork_hash_table_iterator_init(server_table, &server_iter);
while ((entry = cork_hash_table_iterator_next(&server_iter)) != NULL) {
struct server *server = (struct server *)entry->value;
stop_server(working_dir, server->port);
}
ev_signal_stop(EV_DEFAULT, &sigint_watcher);
ev_signal_stop(EV_DEFAULT, &sigterm_watcher);
ss_free(working_dir);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/good_2888_0 |
crossvul-cpp_data_bad_4099_0 | /* radare - LGPL - Copyright 2014-2017 - inisider */
#include <string.h>
#include <r_util.h>
#include <r_core.h>
#include "pdb_downloader.h"
static bool checkExtract() {
#if __WINDOWS__
if (r_sys_cmd ("expand -? >nul") != 0) {
return false;
}
#else
if (r_sys_cmd ("cabextract -v > /dev/null") != 0) {
return false;
}
#endif
return true;
}
static bool checkCurl() {
const char nul[] = R_SYS_DEVNULL;
if (r_sys_cmdf ("curl --version > %s", nul) != 0) {
return false;
}
return true;
}
static int download(struct SPDBDownloader *pd) {
SPDBDownloaderOpt *opt = pd->opt;
char *curl_cmd = NULL;
char *extractor_cmd = NULL;
char *abspath_to_archive = NULL;
char *abspath_to_file = NULL;
char *archive_name = NULL;
size_t archive_name_len = 0;
char *symbol_store_path = NULL;
char *dbg_file = NULL;
char *guid = NULL;
char *archive_name_escaped = NULL;
char *user_agent = NULL;
char *symbol_server = NULL;
int res = 0;
int cmd_ret;
if (!opt->dbg_file || !*opt->dbg_file) {
// no pdb debug file
return 0;
}
if (!checkCurl ()) {
return 0;
}
// dbg_file len is > 0
archive_name_len = strlen (opt->dbg_file);
archive_name = malloc (archive_name_len + 1);
if (!archive_name) {
return 0;
}
memcpy (archive_name, opt->dbg_file, archive_name_len + 1);
archive_name[archive_name_len - 1] = '_';
symbol_store_path = r_str_escape (opt->symbol_store_path);
dbg_file = r_str_escape (opt->dbg_file);
guid = r_str_escape (opt->guid);
archive_name_escaped = r_str_escape (archive_name);
user_agent = r_str_escape (opt->user_agent);
symbol_server = r_str_escape (opt->symbol_server);
abspath_to_archive = r_str_newf ("%s%s%s%s%s%s%s",
symbol_store_path, R_SYS_DIR,
dbg_file, R_SYS_DIR,
guid, R_SYS_DIR,
archive_name_escaped);
abspath_to_file = strdup (abspath_to_archive);
abspath_to_file[strlen (abspath_to_file) - 1] = 'b';
if (r_file_exists (abspath_to_file)) {
eprintf ("File already downloaded.\n");
R_FREE (user_agent);
R_FREE (abspath_to_archive);
R_FREE (archive_name_escaped);
R_FREE (symbol_store_path);
R_FREE (dbg_file);
R_FREE (guid);
R_FREE (archive_name);
R_FREE (abspath_to_file);
R_FREE (symbol_server);
return 1;
}
if (checkExtract () || opt->extract == 0) {
res = 1;
curl_cmd = r_str_newf ("curl -sfLA \"%s\" \"%s/%s/%s/%s\" --create-dirs -o \"%s\"",
user_agent,
symbol_server,
dbg_file,
guid,
archive_name_escaped,
abspath_to_archive);
#if __WINDOWS__
const char *cabextractor = "expand";
const char *format = "%s %s %s";
// extractor_cmd -> %1 %2 %3
// %1 - 'expand'
// %2 - absolute path to archive
// %3 - absolute path to file that will be dearchive
extractor_cmd = r_str_newf (format, cabextractor,
abspath_to_archive, abspath_to_file);
#else
const char *cabextractor = "cabextract";
const char *format = "%s -d \"%s\" \"%s\"";
char *abspath_to_dir = r_file_dirname (abspath_to_archive);
// cabextract -d %1 %2
// %1 - path to directory where to extract all files from cab archive
// %2 - absolute path to cab archive
extractor_cmd = r_str_newf (format, cabextractor, abspath_to_dir, abspath_to_archive);
R_FREE (abspath_to_dir);
#endif
eprintf ("Attempting to download compressed pdb in %s\n", abspath_to_archive);
if ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {
eprintf("curl exited with error %d\n", cmd_ret);
res = 0;
}
eprintf ("Attempting to decompress pdb\n");
if (opt->extract > 0) {
if (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {
eprintf ("cab extractor exited with error %d\n", cmd_ret);
res = 0;
}
r_file_rm (abspath_to_archive);
}
R_FREE (curl_cmd);
}
if (res == 0) {
eprintf ("Falling back to uncompressed pdb\n");
res = 1;
archive_name_escaped[strlen (archive_name_escaped) - 1] = 'b';
curl_cmd = r_str_newf ("curl -sfLA \"%s\" \"%s/%s/%s/%s\" --create-dirs -o \"%s\"",
opt->user_agent,
opt->symbol_server,
opt->dbg_file,
opt->guid,
archive_name_escaped,
abspath_to_file);
eprintf ("Attempting to download uncompressed pdb in %s\n", abspath_to_file);
if ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {
eprintf("curl exited with error %d\n", cmd_ret);
res = 0;
}
R_FREE (curl_cmd);
}
R_FREE (abspath_to_archive);
R_FREE (abspath_to_file);
R_FREE (archive_name);
R_FREE (extractor_cmd);
R_FREE (symbol_store_path);
R_FREE (dbg_file);
R_FREE (guid);
R_FREE (archive_name_escaped);
R_FREE (user_agent);
R_FREE (symbol_server);
return res;
}
void init_pdb_downloader(SPDBDownloaderOpt *opt, SPDBDownloader *pd) {
pd->opt = R_NEW0 (SPDBDownloaderOpt);
if (!pd->opt) {
pd->download = 0;
eprintf ("Cannot allocate memory for SPDBDownloaderOpt.\n");
return;
}
pd->opt->dbg_file = strdup (opt->dbg_file);
pd->opt->guid = strdup (opt->guid);
pd->opt->symbol_server = strdup (opt->symbol_server);
pd->opt->user_agent = strdup (opt->user_agent);
pd->opt->symbol_store_path = strdup (opt->symbol_store_path);
pd->opt->extract = opt->extract;
pd->download = download;
}
void deinit_pdb_downloader(SPDBDownloader *pd) {
R_FREE (pd->opt->dbg_file);
R_FREE (pd->opt->guid);
R_FREE (pd->opt->symbol_server);
R_FREE (pd->opt->user_agent);
R_FREE (pd->opt->symbol_store_path);
R_FREE (pd->opt);
pd->download = 0;
}
int r_bin_pdb_download(RCore *core, int isradjson, int *actions_done, SPDBOptions *options) {
int ret;
SPDBDownloaderOpt opt;
SPDBDownloader pdb_downloader;
RBinInfo *info = r_bin_get_info (core->bin);
if (!info || !info->debug_file_name) {
eprintf ("Can't find debug filename\n");
return 1;
}
if (!options || !options->symbol_server || !options->user_agent) {
eprintf ("Can't retrieve pdb configurations\n");
return 1;
}
opt.dbg_file = (char*) r_file_basename (info->debug_file_name);
opt.guid = info->guid;
opt.symbol_server = options->symbol_server;
opt.user_agent = options->user_agent;
opt.symbol_store_path = options->symbol_store_path;
opt.extract = options->extract;
init_pdb_downloader (&opt, &pdb_downloader);
ret = pdb_downloader.download ? pdb_downloader.download (&pdb_downloader) : 0;
if (isradjson && actions_done) {
printf ("%s\"pdb\":{\"file\":\"%s\",\"download\":%s}",
*actions_done ? "," : "", opt.dbg_file, ret ? "true" : "false");
} else {
printf ("PDB \"%s\" download %s\n",
opt.dbg_file, ret ? "success" : "failed");
}
if (actions_done) {
(*actions_done)++;
}
deinit_pdb_downloader (&pdb_downloader);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/bad_4099_0 |
crossvul-cpp_data_good_1104_0 | /* radare - LGPL - Copyright 2009-2019 - nibble, pancake */
#if 0
* Use RList
* Support callback for null command (why?)
* Show help of commands
- long commands not yet tested at all
- added interface to export command list into an autocompletable
argc, argv for dietline
* r_cmd must provide a nesting char table indexing for commands
- this is already partially done
- this is pretty similar to r_db
- every module can register their own commands
- commands can be listed like in a tree
#endif
#define INTERACTIVE_MAX_REP 1024
#include <r_core.h>
#include <r_anal.h>
#include <r_cons.h>
#include <r_cmd.h>
#include <stdint.h>
#include <sys/types.h>
#include <ctype.h>
#include <stdarg.h>
#if __UNIX__
#include <sys/utsname.h>
#endif
R_API void r_save_panels_layout(RCore *core, const char *_name);
R_API void r_load_panels_layout(RCore *core, const char *_name);
#define DEFINE_CMD_DESCRIPTOR(core, cmd_) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##cmd_; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
#define DEFINE_CMD_DESCRIPTOR_WITH_DETAIL(core, cmd_) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##cmd_; \
d->help_detail = help_detail_##cmd_; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
#define DEFINE_CMD_DESCRIPTOR_WITH_DETAIL2(core, cmd_) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##cmd_; \
d->help_detail = help_detail_##cmd_; \
d->help_detail2 = help_detail2_##cmd_; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
#define DEFINE_CMD_DESCRIPTOR_SPECIAL(core, cmd_, named_cmd) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##named_cmd; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
static int r_core_cmd_subst_i(RCore *core, char *cmd, char* colon, bool *tmpseek);
static void cmd_debug_reg(RCore *core, const char *str);
#include "cmd_quit.c"
#include "cmd_hash.c"
#include "cmd_debug.c"
#include "cmd_log.c"
#include "cmd_flag.c"
#include "cmd_zign.c"
#include "cmd_project.c"
#include "cmd_write.c"
#include "cmd_cmp.c"
#include "cmd_eval.c"
#include "cmd_anal.c"
#include "cmd_open.c"
#include "cmd_meta.c"
#include "cmd_type.c"
#include "cmd_egg.c"
#include "cmd_info.c"
#include "cmd_macro.c"
#include "cmd_magic.c"
#include "cmd_mount.c"
#include "cmd_seek.c"
#include "cmd_search.c" // defines incDigitBuffer... used by cmd_print
#include "cmd_print.c"
#include "cmd_help.c"
#include "cmd_colon.c"
static const char *help_msg_dollar[] = {
"Usage:", "$alias[=cmd] [args...]", "Alias commands and strings (See ?$? for help on $variables)",
"$", "", "list all defined aliases",
"$*", "", "list all the aliases as r2 commands in base64",
"$**", "", "same as above, but using plain text",
"$", "dis=base64:AAA==", "alias this base64 encoded text to be printed when $dis is called",
"$", "dis=$hello world", "alias this text to be printed when $dis is called",
"$", "dis=-", "open cfg.editor to set the new value for dis alias",
"$", "dis=af;pdf", "create command - analyze to show function",
"$", "test=#!pipe node /tmp/test.js", "create command - rlangpipe script",
"$", "dis=", "undefine alias",
"$", "dis", "execute the previously defined alias",
"$", "dis?", "show commands aliased by $dis",
NULL
};
static const char *help_msg_star[] = {
"Usage:", "*<addr>[=[0x]value]", "Pointer read/write data/values",
"*", "entry0=cc", "write trap in entrypoint",
"*", "entry0+10=0x804800", "write value in delta address",
"*", "entry0", "read byte at given address",
"TODO: last command should honor asm.bits", "", "",
NULL
};
static const char *help_msg_dot[] = {
"Usage:", ".[r2cmd] | [file] | [!command] | [(macro)]", "# define macro or interpret r2, r_lang,\n"
" cparse, d, es6, exe, go, js, lsp, pl, py, rb, sh, vala or zig file",
".", "", "repeat last command backward",
".", "r2cmd", "interpret the output of the command as r2 commands",
"..", " [file]", "run the output of the execution of a script as r2 commands",
"...", "", "repeat last command forward (same as \\n)",
".:", "8080", "listen for commands on given tcp port",
".--", "", "terminate tcp server for remote commands",
".", " foo.r2", "interpret script",
".-", "", "open cfg.editor and interpret tmp file",
".*", " file ...", "same as #!pipe open cfg.editor and interpret tmp file",
".!", "rabin -ri $FILE", "interpret output of command",
".", "(foo 1 2 3)", "run macro 'foo' with args 1, 2, 3",
"./", " ELF", "interpret output of command /m ELF as r. commands",
NULL
};
static const char *help_msg_equal[] = {
"Usage:", " =[:!+-=ghH] [...]", " # connect with other instances of r2",
"\nremote commands:", "", "",
"=", "", "list all open connections",
"=<", "[fd] cmd", "send output of local command to remote fd", // XXX may not be a special char
"=", "[fd] cmd", "exec cmd at remote 'fd' (last open is default one)",
"=!", " cmd", "run command via r_io_system",
"=+", " [proto://]host:port", "connect to remote host:port (*rap://, raps://, tcp://, udp://, http://)",
"=-", "[fd]", "remove all hosts or host 'fd'",
"==", "[fd]", "open remote session with host 'fd', 'q' to quit",
"=!=", "", "disable remote cmd mode",
"!=!", "", "enable remote cmd mode",
"\nservers:","","",
".:", "9000", "start the tcp server (echo x|nc ::1 9090 or curl ::1:9090/cmd/x)",
"=:", "port", "start the rap server (o rap://9999)",
"=g", "[?]", "start the gdbserver",
"=h", "[?]", "start the http webserver",
"=H", "[?]", "start the http webserver (and launch the web browser)",
"\nother:","","",
"=&", ":port", "start rap server in background (same as '&_=h')",
"=", ":host:port cmd", "run 'cmd' command on remote server",
"\nexamples:","","",
"=+", "tcp://localhost:9090/", "connect to: r2 -c.:9090 ./bin",
// "=+", "udp://localhost:9090/", "connect to: r2 -c.:9090 ./bin",
"=+", "rap://localhost:9090/", "connect to: r2 rap://:9090",
"=+", "http://localhost:9090/cmd/", "connect to: r2 -c'=h 9090' bin",
"o ", "rap://:9090/", "start the rap server on tcp port 9090",
NULL
};
#if 0
static const char *help_msg_equalh[] = {
"Usage:", "=h[---*&] [port]", " # manage http connections",
"=h", " port", "listen for http connections (r2 -qc=H /bin/ls)",
"=h-", "", "stop background webserver",
"=h--", "", "stop foreground webserver",
"=h*", "", "restart current webserver",
"=h&", " port", "start http server in background",
NULL
};
#endif
static const char *help_msg_equalh[] = {
"Usage:", " =[hH] [...]", " # http server",
"http server:", "", "",
"=h", " port", "listen for http connections (r2 -qc=H /bin/ls)",
"=h-", "", "stop background webserver",
"=h--", "", "stop foreground webserver",
"=h*", "", "restart current webserver",
"=h&", " port", "start http server in background",
"=H", " port", "launch browser and listen for http",
"=H&", " port", "launch browser and listen for http in background",
NULL
};
static const char *help_msg_equalg[] = {
"Usage:", " =[g] [...]", " # gdb server",
"gdbserver:", "", "",
"=g", " port file [args]", "listen on 'port' debugging 'file' using gdbserver",
"=g!", " port file [args]", "same as above, but debug protocol messages (like gdbserver --remote-debug)",
NULL
};
static const char *help_msg_b[] = {
"Usage:", "b[f] [arg]\n", "Get/Set block size",
"b", " 33", "set block size to 33",
"b", " eip+4", "numeric argument can be an expression",
"b", "", "display current block size",
"b", "+3", "increase blocksize by 3",
"b", "-16", "decrease blocksize by 16",
"b*", "", "display current block size in r2 command",
"bf", " foo", "set block size to flag size",
"bj", "", "display block size information in JSON",
"bm", " 1M", "set max block size",
NULL
};
static const char *help_msg_k[] = {
"Usage:", "k[s] [key[=value]]", "Sdb Query",
"k", " anal/**", "list namespaces under anal",
"k", " anal/meta/*", "list kv from anal > meta namespaces",
"k", " anal/meta/meta.0x80404", "get value for meta.0x80404 key",
"k", " foo", "show value",
"k", " foo=bar", "set value",
"k", "", "list keys",
"kd", " [file.sdb] [ns]", "dump namespace to disk",
"kj", "", "List all namespaces and sdb databases in JSON format",
"ko", " [file.sdb] [ns]", "open file into namespace",
"ks", " [ns]", "enter the sdb query shell",
//"kl", " ha.sdb", "load keyvalue from ha.sdb",
//"ks", " ha.sdb", "save keyvalue to ha.sdb",
NULL,
};
static const char *help_msg_r[] = {
"Usage:", "r[+-][ size]", "Resize file",
"r", "", "display file size",
"r", " size", "expand or truncate file to given size",
"r-", "num", "remove num bytes, move following data down",
"r+", "num", "insert num bytes, move following data up",
"rm" ," [file]", "remove file",
"rh" ,"", "show size in human format",
"r2" ," [file]", "launch r2 (same for rax2, rasm2, ...)",
"reset" ,"", "reset console settings (clear --hard)",
NULL
};
static const char *help_msg_u[] = {
"Usage:", "u", "uname or undo write/seek",
"u", "", "show system uname",
"uw", "", "alias for wc (requires: e io.cache=true)",
"us", "", "alias for s- (seek history)",
"uc", "", "undo core commands (uc?, ucl, uc*, ..)",
NULL
};
static const char *help_msg_y[] = {
"Usage:", "y[ptxy] [len] [[@]addr]", " # See wd? for memcpy, same as 'yf'.",
"y!", "", "open cfg.editor to edit the clipboard",
"y", " 16 0x200", "copy 16 bytes into clipboard from 0x200",
"y", " 16 @ 0x200", "copy 16 bytes into clipboard from 0x200",
"y", " 16", "copy 16 bytes into clipboard",
"y", "", "show yank buffer information (srcoff len bytes)",
"y*", "", "print in r2 commands what's been yanked",
"yf", " 64 0x200", "copy file 64 bytes from 0x200 from file",
"yfa", " file copy", "copy all bytes from file (opens w/ io)",
"yfx", " 10203040", "yank from hexpairs (same as ywx)",
"yj", "", "print in JSON commands what's been yanked",
"yp", "", "print contents of clipboard",
"yq", "", "print contents of clipboard in hexpairs",
"ys", "", "print contents of clipboard as string",
"yt", " 64 0x200", "copy 64 bytes from current seek to 0x200",
"ytf", " file", "dump the clipboard to given file",
"yw", " hello world", "yank from string",
"ywx", " 10203040", "yank from hexpairs (same as yfx)",
"yx", "", "print contents of clipboard in hexadecimal",
"yy", " 0x3344", "paste clipboard",
"yz", " [len]", "copy nul-terminated string (up to blocksize) into clipboard",
NULL
};
static const char *help_msg_triple_exclamation[] = {
"Usage:", "!!![-*][cmd] [arg|$type...]", " # user-defined autocompletion for commands",
"!!!", "", "list all autocompletions",
"!!!?", "", "show this help",
"!!!", "-*", "remove all user-defined autocompletions",
"!!!", "-\\*", "remove autocompletions matching this glob expression",
"!!!", "-foo", "remove autocompletion named 'foo'",
"!!!", "foo", "add 'foo' for autocompletion",
"!!!", "bar $flag", "add 'bar' for autocompletion with $flag as argument",
NULL
};
static const char *help_msg_vertical_bar[] = {
"Usage:", "[cmd] | [program|H|T|.|]", "",
"", "[cmd] |?", "show this help",
"", "[cmd] |", "disable scr.html and scr.color",
"", "[cmd] |H", "enable scr.html, respect scr.color",
"", "[cmd] |T", "use scr.tts to speak out the stdout",
"", "[cmd] | [program]", "pipe output of command to program",
"", "[cmd] |.", "alias for .[cmd]",
NULL
};
R_API void r_core_cmd_help(const RCore *core, const char *help[]) {
r_cons_cmd_help (help, core->print->flags & R_PRINT_FLAGS_COLOR);
}
static void recursive_help_go(RCore *core, int detail, RCmdDescriptor *desc) {
int i;
if (desc->help_msg) {
r_core_cmd_help (core, desc->help_msg);
}
if (detail >= 1) {
if (desc->help_detail) {
r_core_cmd_help (core, desc->help_detail);
}
if (detail >= 2 && desc->help_detail2) {
r_core_cmd_help (core, desc->help_detail2);
}
}
for (i = 32; i < R_ARRAY_SIZE (desc->sub); i++) {
if (desc->sub[i]) {
recursive_help_go (core, detail, desc->sub[i]);
}
}
}
static void recursive_help(RCore *core, int detail, const char *cmd_prefix) {
const ut8 *p;
RCmdDescriptor *desc = &core->root_cmd_descriptor;
for (p = (const ut8 *)cmd_prefix; *p && *p < R_ARRAY_SIZE (desc->sub); p++) {
if (!(desc = desc->sub[*p])) {
return;
}
}
recursive_help_go (core, detail, desc);
}
static int r_core_cmd_nullcallback(void *data) {
RCore *core = (RCore*) data;
if (core->cons->context->breaked) {
core->cons->context->breaked = false;
return 0;
}
if (!core->cmdrepeat) {
return 0;
}
r_core_cmd_repeat (core, true);
return 1;
}
static int cmd_uniq(void *data, const char *input) { // "uniq"
RCore *core = (RCore *)data;
const char *arg = strchr (input, ' ');
if (arg) {
arg = r_str_trim_ro (arg + 1);
}
switch (*input) {
case '?': // "uniq?"
eprintf ("Usage: uniq # uniq to list unique strings in file\n");
break;
default: // "uniq"
if (!arg) {
arg = "";
}
if (r_fs_check (core->fs, arg)) {
r_core_cmdf (core, "md %s", arg);
} else {
char *res = r_syscmd_uniq (arg);
if (res) {
r_cons_print (res);
free (res);
}
}
break;
}
return 0;
}
static int cmd_head (void *data, const char *_input) { // "head"
RCore *core = (RCore *)data;
int lines = 5;
char *input = strdup (_input);
char *arg = strchr (input, ' ');
char *tmp, *count;
if (arg) {
arg = (char *)r_str_trim_ro (arg + 1); // contains "count filename"
count = strchr (arg, ' ');
if (count) {
*count = 0; // split the count and file name
tmp = (char *)r_str_trim_ro (count + 1);
lines = atoi (arg);
arg = tmp;
}
}
switch (*input) {
case '?': // "head?"
eprintf ("Usage: head [file] # to list first n lines in file\n");
break;
default: // "head"
if (!arg) {
arg = "";
}
if (r_fs_check (core->fs, arg)) {
r_core_cmdf (core, "md %s", arg);
} else {
char *res = r_syscmd_head (arg, lines);
if (res) {
r_cons_print (res);
free (res);
}
}
break;
}
free (input);
return 0;
}
static int cmd_uname(void *data, const char *input) {
RCore *core = (RCore *)data;
switch (input[0]) {
case '?': // "u?"
r_core_cmd_help (data, help_msg_u);
return 1;
case 'c': // "uc"
switch (input[1]) {
case ' ': {
char *cmd = strdup (input + 2);
char *rcmd = strchr (cmd, ',');
if (rcmd) {
*rcmd++ = 0;
RCoreUndo *undo = r_core_undo_new (core->offset, cmd, rcmd);
r_core_undo_push (core, undo);
} else {
eprintf ("Usage: uc [cmd] [revert-cmd]");
}
free (cmd);
}
break;
case '?':
eprintf ("Usage: uc [cmd],[revert-cmd]\n");
eprintf (" uc. - list all reverts in current\n");
eprintf (" uc* - list all core undos\n");
eprintf (" uc - list all core undos\n");
eprintf (" uc- - undo last action\n");
break;
case '.': {
RCoreUndoCondition cond = {
.addr = core->offset,
.minstamp = 0,
.glob = NULL
};
r_core_undo_print (core, 1, &cond);
} break;
case '*':
r_core_undo_print (core, 1, NULL);
break;
case '-': // "uc-"
r_core_undo_pop (core);
break;
default:
r_core_undo_print (core, 0, NULL);
break;
}
return 1;
case 's': // "us"
r_core_cmdf (data, "s-%s", input + 1);
return 1;
case 'w': // "uw"
r_core_cmdf (data, "wc%s", input + 1);
return 1;
case 'n': // "un"
if (input[1] == 'i' && input[2] == 'q') {
cmd_uniq (core, input);
}
return 1;
}
#if __UNIX__
struct utsname un;
uname (&un);
r_cons_printf ("%s %s %s %s\n", un.sysname,
un.nodename, un.release, un.machine);
#elif __WINDOWS__
r_cons_printf ("windows\n");
#else
r_cons_printf ("unknown\n");
#endif
return 0;
}
static int cmd_alias(void *data, const char *input) {
RCore *core = (RCore *)data;
if (*input == '?') {
r_core_cmd_help (core, help_msg_dollar);
return 0;
}
int i = strlen (input);
char *buf = malloc (i + 2);
if (!buf) {
return 0;
}
*buf = '$'; // prefix aliases with a dollar
memcpy (buf + 1, input, i + 1);
char *q = strchr (buf, ' ');
char *def = strchr (buf, '=');
char *desc = strchr (buf, '?');
/* create alias */
if ((def && q && (def < q)) || (def && !q)) {
*def++ = 0;
size_t len = strlen (def);
/* Remove quotes */
if (len > 0 && (def[0] == '\'') && (def[len - 1] == '\'')) {
def[len - 1] = 0x00;
def++;
}
if (!q || (q && q > def)) {
if (*def) {
if (!strcmp (def, "-")) {
char *v = r_cmd_alias_get (core->rcmd, buf, 0);
char *n = r_cons_editor (NULL, v);
if (n) {
r_cmd_alias_set (core->rcmd, buf, n, 0);
free (n);
}
} else {
r_cmd_alias_set (core->rcmd, buf, def, 0);
}
} else {
r_cmd_alias_del (core->rcmd, buf);
}
}
/* Show command for alias */
} else if (desc && !q) {
*desc = 0;
char *v = r_cmd_alias_get (core->rcmd, buf, 0);
if (v) {
r_cons_println (v);
free (buf);
return 1;
} else {
eprintf ("unknown key '%s'\n", buf);
}
} else if (buf[1] == '*') {
/* Show aliases */
int i, count = 0;
char **keys = r_cmd_alias_keys (core->rcmd, &count);
for (i = 0; i < count; i++) {
char *v = r_cmd_alias_get (core->rcmd, keys[i], 0);
char *q = r_base64_encode_dyn (v, -1);
if (buf[2] == '*') {
r_cons_printf ("%s=%s\n", keys[i], v);
} else {
r_cons_printf ("%s=base64:%s\n", keys[i], q);
}
free (q);
}
} else if (!buf[1]) {
int i, count = 0;
char **keys = r_cmd_alias_keys (core->rcmd, &count);
for (i = 0; i < count; i++) {
r_cons_println (keys[i]);
}
} else {
/* Execute alias */
if (q) {
*q = 0;
}
char *v = r_cmd_alias_get (core->rcmd, buf, 0);
if (v) {
if (*v == '$') {
r_cons_strcat (v + 1);
r_cons_newline ();
} else if (q) {
char *out = r_str_newf ("%s %s", v, q + 1);
r_core_cmd0 (core, out);
free (out);
} else {
r_core_cmd0 (core, v);
}
} else {
eprintf ("unknown key '%s'\n", buf);
}
}
free (buf);
return 0;
}
static int getArg(char ch, int def) {
switch (ch) {
case '&':
case '-':
return ch;
}
return def;
}
// wtf dupe for local vs remote?
static void aliascmd(RCore *core, const char *str) {
switch (str[0]) {
case '\0': // "=$"
r_core_cmd0 (core, "$");
break;
case '-': // "=$-"
if (str[1]) {
r_cmd_alias_del (core->rcmd, str + 2);
} else {
r_cmd_alias_del (core->rcmd, NULL);
// r_cmd_alias_reset (core->rcmd);
}
break;
case '?': // "=$?"
eprintf ("Usage: =$[-][remotecmd] # remote command alias\n");
eprintf (" =$dr # makes 'dr' alias for =!dr\n");
eprintf (" =$-dr # unset 'dr' alias\n");
break;
default:
r_cmd_alias_set (core->rcmd, str, "", 1);
break;
}
}
static int cmd_rap(void *data, const char *input) {
RCore *core = (RCore *)data;
switch (*input) {
case '\0': // "="
r_core_rtr_list (core);
break;
case 'j': // "=j"
eprintf ("TODO: list connections in json\n");
break;
case '!': // "=!"
if (input[1] == '=') {
// swap core->cmdremote = core->cmdremote? 0: 1;
core->cmdremote = input[2]? 1: 0;
r_cons_println (r_str_bool (core->cmdremote));
} else {
char *res = r_io_system (core->io, input + 1);
if (res) {
r_cons_printf ("%s\n", res);
free (res);
}
}
break;
case '$': // "=$"
// XXX deprecate?
aliascmd (core, input + 1);
break;
case '+': // "=+"
r_core_rtr_add (core, input + 1);
break;
case '-': // "=-"
r_core_rtr_remove (core, input + 1);
break;
//case ':': r_core_rtr_cmds (core, input + 1); break;
case '<': // "=<"
r_core_rtr_pushout (core, input + 1);
break;
case '=': // "=="
r_core_rtr_session (core, input + 1);
break;
case 'g': // "=g"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_equalg);
} else {
r_core_rtr_gdb (core, getArg (input[1], 'g'), input + 1);
}
break;
case 'h': // "=h"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_equalh);
} else {
r_core_rtr_http (core, getArg (input[1], 'h'), 'h', input + 1);
}
break;
case 'H': // "=H"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_equalh);
} else {
const char *arg = r_str_trim_ro (input + 1);
r_core_rtr_http (core, getArg (input[1], 'H'), 'H', arg);
}
break;
case '?': // "=?"
r_core_cmd_help (core, help_msg_equal);
break;
default:
r_core_rtr_cmd (core, input);
break;
}
return 0;
}
static int cmd_rap_run(void *data, const char *input) {
RCore *core = (RCore *)data;
char *res = r_io_system (core->io, input);
if (res) {
int ret = atoi (res);
free (res);
return ret;
}
return false;
}
static int cmd_yank(void *data, const char *input) {
ut64 n;
RCore *core = (RCore *)data;
switch (input[0]) {
case ' ': // "y "
r_core_yank (core, core->offset, r_num_math (core->num, input + 1));
break;
case 'l': // "yl"
core->num->value = r_buf_size (core->yank_buf);
break;
case 'y': // "yy"
while (input[1] == ' ') {
input++;
}
n = input[1]? r_num_math (core->num, input + 1): core->offset;
r_core_yank_paste (core, n, 0);
break;
case 'x': // "yx"
r_core_yank_hexdump (core, r_num_math (core->num, input + 1));
break;
case 'z': // "yz"
r_core_yank_string (core, core->offset, r_num_math (core->num, input + 1));
break;
case 'w': // "yw" ... we have yf which makes more sense than 'w'
switch (input[1]) {
case ' ':
r_core_yank_set (core, 0, (const ut8*)input + 2, strlen (input + 2));
break;
case 'x':
if (input[2] == ' ') {
char *out = strdup (input + 3);
int len = r_hex_str2bin (input + 3, (ut8*)out);
if (len > 0) {
r_core_yank_set (core, core->offset, (const ut8*)out, len);
} else {
eprintf ("Invalid length\n");
}
free (out);
} else {
eprintf ("Usage: ywx [hexpairs]\n");
}
// r_core_yank_write_hex (core, input + 2);
break;
default:
eprintf ("Usage: ywx [hexpairs]\n");
break;
}
break;
case 'p': // "yp"
r_core_yank_cat (core, r_num_math (core->num, input + 1));
break;
case 's': // "ys"
r_core_yank_cat_string (core, r_num_math (core->num, input + 1));
break;
case 't': // "wt"
if (input[1] == 'f') { // "wtf"
ut64 tmpsz;
const char *file = r_str_trim_ro (input + 2);
const ut8 *tmp = r_buf_data (core->yank_buf, &tmpsz);
if (!r_file_dump (file, tmp, tmpsz, false)) {
eprintf ("Cannot dump to '%s'\n", file);
}
} else if (input[1] == ' ') {
r_core_yank_to (core, input + 1);
} else {
eprintf ("Usage: wt[f] [arg] ..\n");
}
break;
case 'f': // "yf"
switch (input[1]) {
case ' ': // "yf"
r_core_yank_file_ex (core, input + 1);
break;
case 'x': // "yfx"
r_core_yank_hexpair (core, input + 2);
break;
case 'a': // "yfa"
r_core_yank_file_all (core, input + 2);
break;
default:
eprintf ("Usage: yf[xa] [arg]\n");
eprintf ("yf [file] - copy blocksize from file into the clipboard\n");
eprintf ("yfa [path] - yank the whole file\n");
eprintf ("yfx [hexpair] - yank from hexpair string\n");
break;
}
break;
case '!': // "y!"
{
char *sig = r_core_cmd_str (core, "y*");
if (!sig || !*sig) {
free (sig);
sig = strdup ("wx 10203040");
}
char *data = r_core_editor (core, NULL, sig);
(void) strtok (data, ";\n");
r_core_cmdf (core, "y%s", data);
free (sig);
free (data);
}
break;
case '*': // "y*"
case 'j': // "yj"
case 'q': // "yq"
case '\0': // "y"
r_core_yank_dump (core, 0, input[0]);
break;
default:
r_core_cmd_help (core, help_msg_y);
break;
}
return true;
}
static int lang_run_file(RCore *core, RLang *lang, const char *file) {
r_core_sysenv_begin (core, NULL);
return r_lang_run_file (core->lang, file);
}
static char *langFromHashbang(RCore *core, const char *file) {
int fd = r_sandbox_open (file, O_RDONLY, 0);
if (fd != -1) {
char firstLine[128] = {0};
int len = r_sandbox_read (fd, (ut8*)firstLine, sizeof (firstLine) - 1);
firstLine[len] = 0;
if (!strncmp (firstLine, "#!/", 3)) {
// I CAN HAS A HASHBANG
char *nl = strchr (firstLine, '\n');
if (nl) {
*nl = 0;
}
nl = strchr (firstLine, ' ');
if (nl) {
*nl = 0;
}
return strdup (firstLine + 2);
}
r_sandbox_close (fd);
}
return NULL;
}
R_API bool r_core_run_script(RCore *core, const char *file) {
bool ret = false;
RListIter *iter;
RLangPlugin *p;
char *name;
r_list_foreach (core->scriptstack, iter, name) {
if (!strcmp (file, name)) {
eprintf ("WARNING: ignored nested source: %s\n", file);
return false;
}
}
r_list_push (core->scriptstack, strdup (file));
if (!strcmp (file, "-")) {
char *out = r_core_editor (core, NULL, NULL);
if (out) {
ret = r_core_cmd_lines (core, out);
free (out);
}
} else if (r_str_endswith (file, ".html")) {
const bool httpSandbox = r_config_get_i (core->config, "http.sandbox");
char *httpIndex = strdup (r_config_get (core->config, "http.index"));
r_config_set_i (core->config, "http.sandbox", 0);
char *absfile = r_file_abspath (file);
r_config_set (core->config, "http.index", absfile);
free (absfile);
r_core_cmdf (core, "=H");
r_config_set_i (core->config, "http.sandbox", httpSandbox);
r_config_set (core->config, "http.index", httpIndex);
free (httpIndex);
ret = true;
} else if (r_str_endswith (file, ".c")) {
r_core_cmd_strf (core, "#!c %s", file);
ret = true;
} else if (r_file_is_c (file)) {
const char *dir = r_config_get (core->config, "dir.types");
char *out = r_parse_c_file (core->anal, file, dir, NULL);
if (out) {
r_cons_strcat (out);
sdb_query_lines (core->anal->sdb_types, out);
free (out);
}
ret = out? true: false;
} else {
p = r_lang_get_by_extension (core->lang, file);
if (p) {
r_lang_use (core->lang, p->name);
ret = lang_run_file (core, core->lang, file);
} else {
// XXX this is an ugly hack, we need to use execve here and specify args properly
#if __WINDOWS__
#define cmdstr(x) r_str_newf (x" %s", file);
#else
#define cmdstr(x) r_str_newf (x" '%s'", file);
#endif
const char *p = r_str_lchr (file, '.');
if (p) {
const char *ext = p + 1;
/* TODO: handle this inside r_lang_pipe with new APIs */
if (!strcmp (ext, "js")) {
char *cmd = cmdstr ("node");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "exe")) {
#if __WINDOWS__
char *cmd = r_str_newf ("%s", file);
#else
char *cmd = cmdstr ("wine");
#endif
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "zig")) {
char *cmd = cmdstr ("zig run");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "d")) {
char *cmd = cmdstr ("dmd -run");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "lsp")) {
char *cmd = cmdstr ("newlisp -n");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "go")) {
char *cmd = cmdstr ("go run");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "es6")) {
char *cmd = cmdstr ("babel-node");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "rb")) {
char *cmd = cmdstr ("ruby");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "vala")) {
r_lang_use (core->lang, "vala");
lang_run_file (core, core->lang, file);
ret = 1;
} else if (!strcmp (ext, "sh")) {
char *shell = r_sys_getenv ("SHELL");
if (!shell) {
shell = strdup ("sh");
}
if (shell) {
r_lang_use (core->lang, "pipe");
char *cmd = r_str_newf ("%s '%s'", shell, file);
if (cmd) {
lang_run_file (core, core->lang, cmd);
free (cmd);
}
free (shell);
}
ret = 1;
} else if (!strcmp (ext, "pl")) {
char *cmd = cmdstr ("perl");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "py")) {
char *cmd = cmdstr ("python");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
}
} else {
char *abspath = r_file_path (file);
char *lang = langFromHashbang (core, file);
if (lang) {
r_lang_use (core->lang, "pipe");
char *cmd = r_str_newf ("%s '%s'", lang, file);
lang_run_file (core, core->lang, cmd);
free (lang);
free (cmd);
ret = 1;
}
free (abspath);
}
if (!ret) {
ret = r_core_cmd_file (core, file);
}
}
}
free (r_list_pop (core->scriptstack));
return ret;
}
static int cmd_ls(void *data, const char *input) { // "ls"
RCore *core = (RCore *)data;
const char *arg = strchr (input, ' ');
if (arg) {
arg = r_str_trim_ro (arg + 1);
}
switch (*input) {
case '?': // "l?"
eprintf ("Usage: l[es] # ls to list files, le[ss] to less a file\n");
break;
case 'e': // "le"
if (arg) {
r_core_cmdf (core, "cat %s~..", arg);
} else {
eprintf ("Usage: less [file]\n");
}
break;
default: // "ls"
if (!arg) {
arg = "";
}
if (r_fs_check (core->fs, arg)) {
r_core_cmdf (core, "md %s", arg);
} else {
char *res = r_syscmd_ls (arg);
if (res) {
r_cons_print (res);
free (res);
}
}
break;
}
return 0;
}
static int cmd_join(void *data, const char *input) { // "join"
RCore *core = (RCore *)data;
const char *tmp = strdup (input);
const char *arg1 = strchr (tmp, ' ');
if (!arg1) {
goto beach;
}
arg1 = r_str_trim_ro (arg1);
char *end = strchr (arg1, ' ');
if (!end) {
goto beach;
}
*end = '\0';
const char *arg2 = end+1;
if (!arg2) {
goto beach;
}
arg2 = r_str_trim_ro (arg2);
switch (*input) {
case '?': // "join?"
goto beach;
default: // "join"
if (!arg1) {
arg1 = "";
}
if (!arg2) {
arg2 = "";
}
if (!r_fs_check (core->fs, arg1) && !r_fs_check (core->fs, arg2)) {
char *res = r_syscmd_join (arg1, arg2);
if (res) {
r_cons_print (res);
free (res);
}
R_FREE (tmp);
}
break;
}
return 0;
beach:
eprintf ("Usage: join [file1] [file2] # join the contents of the two files\n");
return 0;
}
static int cmd_stdin(void *data, const char *input) {
RCore *core = (RCore *)data;
if (input[0] == '?') {
r_cons_printf ("Usage: '-' '.-' '. -' do the same\n");
return false;
}
return r_core_run_script (core, "-");
}
static int cmd_interpret(void *data, const char *input) {
char *str, *ptr, *eol, *rbuf, *filter, *inp;
const char *host, *port, *cmd;
RCore *core = (RCore *)data;
switch (*input) {
case '\0': // "."
r_core_cmd_repeat (core, 0);
break;
case ':': // ".:"
if ((ptr = strchr (input + 1, ' '))) {
/* .:port cmd */
/* .:host:port cmd */
cmd = ptr + 1;
*ptr = 0;
eol = strchr (input + 1, ':');
if (eol) {
*eol = 0;
host = input + 1;
port = eol + 1;
} else {
host = "localhost";
port = input + ((input[1] == ':')? 2: 1);
}
rbuf = r_core_rtr_cmds_query (core, host, port, cmd);
if (rbuf) {
r_cons_print (rbuf);
free (rbuf);
}
} else {
r_core_rtr_cmds (core, input + 1);
}
break;
case '.': // ".." same as \n
if (input[1] == '.') { // "..." run the last command repeated
// same as \n with e cmd.repeat=true
r_core_cmd_repeat (core, 1);
} else if (input[1]) {
char *str = r_core_cmd_str_pipe (core, r_str_trim_ro (input));
if (str) {
r_core_cmd (core, str, 0);
free (str);
}
} else {
eprintf ("Usage: .. ([file])\n");
}
break;
case '*': // ".*"
{
const char *a = r_str_trim_ro (input + 1);
char *s = strdup (a);
char *sp = strchr (s, ' ');
if (sp) {
*sp = 0;
}
if (R_STR_ISNOTEMPTY (s)) {
r_core_run_script (core, s);
}
free (s);
}
break;
case '-': // ".-"
if (input[1] == '?') {
r_cons_printf ("Usage: '-' '.-' '. -' do the same\n");
} else {
r_core_run_script (core, "-");
}
break;
case ' ': // ". "
{
const char *script_file = r_str_trim_ro (input + 1);
if (*script_file == '$') {
r_core_cmd0 (core, script_file);
} else {
if (!r_core_run_script (core, script_file)) {
eprintf ("Cannot find script '%s'\n", script_file);
core->num->value = 1;
} else {
core->num->value = 0;
}
}
}
break;
case '!': // ".!"
/* from command */
r_core_cmd_command (core, input + 1);
break;
case '(': // ".("
r_cmd_macro_call (&core->rcmd->macro, input + 1);
break;
case '?': // ".?"
r_core_cmd_help (core, help_msg_dot);
break;
default:
if (*input >= 0 && *input <= 9) {
eprintf ("|ERROR| No .[0..9] to avoid infinite loops\n");
break;
}
inp = strdup (input);
filter = strchr (inp, '~');
if (filter) {
*filter = 0;
}
int tmp_html = r_cons_singleton ()->is_html;
r_cons_singleton ()->is_html = 0;
ptr = str = r_core_cmd_str (core, inp);
r_cons_singleton ()->is_html = tmp_html;
if (filter) {
*filter = '~';
}
r_cons_break_push (NULL, NULL);
if (ptr) {
for (;;) {
if (r_cons_is_breaked ()) {
break;
}
eol = strchr (ptr, '\n');
if (eol) {
*eol = '\0';
}
if (*ptr) {
char *p = r_str_append (strdup (ptr), filter);
r_core_cmd0 (core, p);
free (p);
}
if (!eol) {
break;
}
ptr = eol + 1;
}
}
r_cons_break_pop ();
free (str);
free (inp);
break;
}
return 0;
}
static int callback_foreach_kv(void *user, const char *k, const char *v) {
r_cons_printf ("%s=%s\n", k, v);
return 1;
}
R_API int r_line_hist_sdb_up(RLine *line) {
if (!line->sdbshell_hist_iter || !line->sdbshell_hist_iter->n) {
return false;
}
line->sdbshell_hist_iter = line->sdbshell_hist_iter->n;
strncpy (line->buffer.data, line->sdbshell_hist_iter->data, R_LINE_BUFSIZE - 1);
line->buffer.index = line->buffer.length = strlen (line->buffer.data);
return true;
}
R_API int r_line_hist_sdb_down(RLine *line) {
if (!line->sdbshell_hist_iter || !line->sdbshell_hist_iter->p) {
return false;
}
line->sdbshell_hist_iter = line->sdbshell_hist_iter->p;
strncpy (line->buffer.data, line->sdbshell_hist_iter->data, R_LINE_BUFSIZE - 1);
line->buffer.index = line->buffer.length = strlen (line->buffer.data);
return true;
}
static int cmd_kuery(void *data, const char *input) {
char buf[1024], *out;
RCore *core = (RCore*)data;
const char *sp, *p = "[sdb]> ";
const int buflen = sizeof (buf) - 1;
Sdb *s = core->sdb;
char *cur_pos, *cur_cmd, *next_cmd = NULL;
char *temp_pos, *temp_cmd, *temp_storage = NULL;
switch (input[0]) {
case 'j':
out = sdb_querys (s, NULL, 0, "anal/**");
if (!out) {
r_cons_println ("No Output from sdb");
break;
}
r_cons_printf ("{\"anal\":{");
while (*out) {
cur_pos = strchr (out, '\n');
if (!cur_pos) {
break;
}
cur_cmd = r_str_ndup (out, cur_pos - out);
r_cons_printf ("\n\n\"%s\" : [", cur_cmd);
next_cmd = r_str_newf ("anal/%s/*", cur_cmd);
temp_storage = sdb_querys (s, NULL, 0, next_cmd);
if (!temp_storage) {
r_cons_println ("\nEMPTY\n");
r_cons_printf ("],\n\n");
out += cur_pos - out + 1;
continue;
}
while (*temp_storage) {
temp_pos = strchr (temp_storage, '\n');
if (!temp_pos) {
break;
}
temp_cmd = r_str_ndup (temp_storage, temp_pos - temp_storage);
r_cons_printf ("\"%s\",", temp_cmd);
temp_storage += temp_pos - temp_storage + 1;
}
r_cons_printf ("],\n\n");
out += cur_pos - out + 1;
}
r_cons_printf ("}}");
free (next_cmd);
free (temp_storage);
break;
case ' ':
out = sdb_querys (s, NULL, 0, input + 1);
if (out) {
r_cons_println (out);
}
free (out);
break;
//case 's': r_pair_save (s, input + 3); break;
//case 'l': r_pair_load (sdb, input + 3); break;
case '\0':
sdb_foreach (s, callback_foreach_kv, NULL);
break;
// TODO: add command to list all namespaces // sdb_ns_foreach ?
case 's': // "ks"
if (core->http_up) {
return false;
}
if (!r_cons_is_interactive ()) {
return false;
}
if (input[1] == ' ') {
char *n, *o, *p = strdup (input + 2);
// TODO: slash split here? or inside sdb_ns ?
for (n = o = p; n; o = n) {
n = strchr (o, '/'); // SDB_NS_SEPARATOR NAMESPACE
if (n) {
*n++ = 0;
}
s = sdb_ns (s, o, 1);
}
free (p);
}
if (!s) {
s = core->sdb;
}
RLine *line = core->cons->line;
if (!line->sdbshell_hist) {
line->sdbshell_hist = r_list_newf (free);
r_list_append (line->sdbshell_hist, r_str_new ("\0"));
}
RList *sdb_hist = line->sdbshell_hist;
r_line_set_hist_callback (line, &r_line_hist_sdb_up, &r_line_hist_sdb_down);
for (;;) {
r_line_set_prompt (p);
if (r_cons_fgets (buf, buflen, 0, NULL) < 1) {
break;
}
if (!*buf) {
break;
}
if (sdb_hist) {
if ((r_list_length (sdb_hist) == 1) || (r_list_length (sdb_hist) > 1 && strcmp (r_list_get_n (sdb_hist, 1), buf))) {
r_list_insert (sdb_hist, 1, strdup (buf));
}
line->sdbshell_hist_iter = sdb_hist->head;
}
out = sdb_querys (s, NULL, 0, buf);
if (out) {
r_cons_println (out);
r_cons_flush ();
}
}
r_line_set_hist_callback (core->cons->line, &r_line_hist_cmd_up, &r_line_hist_cmd_down);
break;
case 'o':
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1] == ' ') {
char *fn = strdup (input + 2);
if (!fn) {
eprintf("Unable to allocate memory\n");
return 0;
}
char *ns = strchr (fn, ' ');
if (ns) {
Sdb *db;
*ns++ = 0;
if (r_file_exists (fn)) {
db = sdb_ns_path (core->sdb, ns, 1);
if (db) {
Sdb *newdb = sdb_new (NULL, fn, 0);
if (newdb) {
sdb_drain (db, newdb);
} else {
eprintf ("Cannot open sdb '%s'\n", fn);
}
} else {
eprintf ("Cannot find sdb '%s'\n", ns);
}
} else {
eprintf ("Cannot open file\n");
}
} else {
eprintf ("Missing sdb namespace\n");
}
free (fn);
} else {
eprintf ("Usage: ko [file] [namespace]\n");
}
break;
case 'd':
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1] == ' ') {
char *fn = strdup (input + 2);
char *ns = strchr (fn, ' ');
if (ns) {
*ns++ = 0;
Sdb *db = sdb_ns_path (core->sdb, ns, 0);
if (db) {
sdb_file (db, fn);
sdb_sync (db);
} else {
eprintf ("Cannot find sdb '%s'\n", ns);
}
} else {
eprintf ("Missing sdb namespace\n");
}
free (fn);
} else {
eprintf ("Usage: kd [file] [namespace]\n");
}
break;
case '?':
r_core_cmd_help (core, help_msg_k);
break;
}
if (input[0] == '\0') {
/* nothing more to do, the command has been parsed. */
return 0;
}
sp = strchr (input + 1, ' ');
if (sp) {
char *inp = strdup (input);
inp [(size_t)(sp - input)] = 0;
s = sdb_ns (core->sdb, inp + 1, 1);
out = sdb_querys (s, NULL, 0, sp + 1);
if (out) {
r_cons_println (out);
free (out);
}
free (inp);
return 0;
}
return 0;
}
static int cmd_bsize(void *data, const char *input) {
ut64 n;
RFlagItem *flag;
RCore *core = (RCore *)data;
switch (input[0]) {
case 'm': // "bm"
n = r_num_math (core->num, input + 1);
if (n > 1) {
core->blocksize_max = n;
} else {
r_cons_printf ("0x%x\n", (ut32)core->blocksize_max);
}
break;
case '+': // "b+"
n = r_num_math (core->num, input + 1);
r_core_block_size (core, core->blocksize + n);
break;
case '-': // "b-"
n = r_num_math (core->num, input + 1);
r_core_block_size (core, core->blocksize - n);
break;
case 'f': // "bf"
if (input[1] == ' ') {
flag = r_flag_get (core->flags, input + 2);
if (flag) {
r_core_block_size (core, flag->size);
} else {
eprintf ("bf: cannot find flag named '%s'\n", input + 2);
}
} else {
eprintf ("Usage: bf [flagname]\n");
}
break;
case 'j': // "bj"
r_cons_printf ("{\"blocksize\":%d,\"blocksize_limit\":%d}\n", core->blocksize, core->blocksize_max);
break;
case '*': // "b*"
r_cons_printf ("b 0x%x\n", core->blocksize);
break;
case '\0': // "b"
r_cons_printf ("0x%x\n", core->blocksize);
break;
case ' ':
r_core_block_size (core, r_num_math (core->num, input));
break;
default:
case '?': // "b?"
r_core_cmd_help (core, help_msg_b);
break;
}
return 0;
}
static int __runMain(RMainCallback cb, const char *arg) {
char *a = r_str_trim_dup (arg);
int argc = 0;
char **args = r_str_argv (a, &argc);
int res = cb (argc, args);
free (args);
free (a);
return res;
}
static bool cmd_r2cmd(RCore *core, const char *_input) {
char *input = r_str_newf ("r%s", _input);
int rc = 0;
if (r_str_startswith (input, "rax2")) {
rc = __runMain (core->r_main_rax2, input);
} else if (r_str_startswith (input, "radare2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_radare2, input);
} else if (r_str_startswith (input, "rasm2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_rasm2, input);
} else if (r_str_startswith (input, "rabin2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_rabin2, input);
} else if (r_str_startswith (input, "ragg2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_ragg2, input);
} else if (r_str_startswith (input, "r2pm")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_r2pm, input);
} else if (r_str_startswith (input, "radiff2")) {
rc = __runMain (core->r_main_radiff2, input);
} else {
const char *r2cmds[] = {
"rax2", "r2pm", "rasm2", "rabin2", "rahash2", "rafind2", "rarun2", "ragg2", "radare2", "r2", NULL
};
int i;
for (i = 0; r2cmds[i]; i++) {
if (r_str_startswith (input, r2cmds[i])) {
free (input);
return true;
}
}
return false;
}
free (input);
core->num->value = rc;
return true;
}
static int cmd_resize(void *data, const char *input) {
RCore *core = (RCore *)data;
ut64 newsize = 0;
st64 delta = 0;
int grow, ret;
if (cmd_r2cmd (core, input)) {
return true;
}
ut64 oldsize = (core->file) ? r_io_fd_size (core->io, core->file->fd): 0;
switch (*input) {
case 'a': // "r..."
if (r_str_startswith (input, "adare2")) {
__runMain (core->r_main_radare2, input - 1);
}
return true;
case '2': // "r2" // XXX should be handled already in cmd_r2cmd()
// TODO: use argv[0] instead of 'radare2'
r_sys_cmdf ("radare%s", input);
return true;
case 'm': // "rm"
if (input[1] == ' ') {
const char *file = r_str_trim_ro (input + 2);
if (*file == '$') {
r_cmd_alias_del (core->rcmd, file);
} else {
r_file_rm (file);
}
} else {
eprintf ("Usage: rm [file] # removes a file\n");
}
return true;
case '\0':
if (core->file) {
if (oldsize != -1) {
r_cons_printf ("%"PFMT64d"\n", oldsize);
}
}
return true;
case 'h':
if (core->file) {
if (oldsize != -1) {
char humansz[8];
r_num_units (humansz, sizeof (humansz), oldsize);
r_cons_printf ("%s\n", humansz);
}
}
return true;
case '+': // "r+"
case '-': // "r-"
delta = (st64)r_num_math (core->num, input);
newsize = oldsize + delta;
break;
case ' ': // "r "
newsize = r_num_math (core->num, input + 1);
if (newsize == 0) {
if (input[1] == '0') {
eprintf ("Invalid size\n");
}
return false;
}
break;
case 'e':
write (1, Color_RESET_TERMINAL, strlen (Color_RESET_TERMINAL));
return true;
case '?': // "r?"
default:
r_core_cmd_help (core, help_msg_r);
return true;
}
grow = (newsize > oldsize);
if (grow) {
ret = r_io_resize (core->io, newsize);
if (ret < 1) {
eprintf ("r_io_resize: cannot resize\n");
}
}
if (delta && core->offset < newsize) {
r_io_shift (core->io, core->offset, grow?newsize:oldsize, delta);
}
if (!grow) {
ret = r_io_resize (core->io, newsize);
if (ret < 1) {
eprintf ("r_io_resize: cannot resize\n");
}
}
if (newsize < core->offset+core->blocksize || oldsize < core->offset + core->blocksize) {
r_core_block_read (core);
}
return true;
}
static int cmd_panels(void *data, const char *input) {
RCore *core = (RCore*) data;
if (core->vmode) {
return false;
}
if (*input == '?') {
eprintf ("Usage: v[*i]\n");
eprintf ("v.test # save curren layout with name test\n");
eprintf ("v test # load saved layout with name test\n");
eprintf ("vi ... # launch 'vim'\n");
return false;
}
if (*input == ' ') {
if (core->panels) {
r_load_panels_layout (core, input + 1);
}
r_config_set (core->config, "scr.layout", input + 1);
return true;
}
if (*input == '=') {
r_save_panels_layout (core, input + 1);
r_config_set (core->config, "scr.layout", input + 1);
return true;
}
if (*input == 'i') {
r_sys_cmdf ("v%s", input);
return false;
}
r_core_visual_panels_root (core, core->panels_root);
return true;
}
static int cmd_visual(void *data, const char *input) {
RCore *core = (RCore*) data;
if (core->http_up) {
return false;
}
if (!r_cons_is_interactive ()) {
return false;
}
return r_core_visual ((RCore *)data, input);
}
static int cmd_pipein(void *user, const char *input) {
char *buf = strdup (input);
int len = r_str_unescape (buf);
r_cons_readpush (buf, len);
free (buf);
return 0;
}
static int cmd_tasks(void *data, const char *input) {
RCore *core = (RCore*) data;
switch (input[0]) {
case '\0': // "&"
case 'j': // "&j"
r_core_task_list (core, *input);
break;
case 'b': { // "&b"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
int tid = r_num_math (core->num, input + 1);
if (tid) {
r_core_task_break (core, tid);
}
break;
}
case '&': { // "&&"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
int tid = r_num_math (core->num, input + 1);
r_core_task_join (core, core->current_task, tid ? tid : -1);
break;
}
case '=': { // "&="
// r_core_task_list (core, '=');
int tid = r_num_math (core->num, input + 1);
if (tid) {
RCoreTask *task = r_core_task_get_incref (core, tid);
if (task) {
if (task->res) {
r_cons_println (task->res);
}
r_core_task_decref (task);
} else {
eprintf ("Cannot find task\n");
}
}
break;
}
case '-': // "&-"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1] == '*') {
r_core_task_del_all_done (core);
} else {
r_core_task_del (core, r_num_math (core->num, input + 1));
}
break;
case '?': // "&?"
default:
helpCmdTasks (core);
break;
case ' ': // "& "
case '_': // "&_"
case 't': { // "&t"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
RCoreTask *task = r_core_task_new (core, true, input + 1, NULL, core);
if (!task) {
break;
}
task->transient = input[0] == 't';
r_core_task_enqueue (core, task);
break;
}
}
return 0;
}
static int cmd_pointer(void *data, const char *input) {
RCore *core = (RCore*) data;
int ret = true;
char *str, *eq;
input = r_str_trim_ro (input);
while (*input == ' ') {
input++;
}
if (!*input || *input == '?') {
r_core_cmd_help (core, help_msg_star);
return ret;
}
str = strdup (input);
eq = strchr (str, '=');
if (eq) {
*eq++ = 0;
if (!strncmp (eq, "0x", 2)) {
ret = r_core_cmdf (core, "wv %s@%s", eq, str);
} else {
ret = r_core_cmdf (core, "wx %s@%s", eq, str);
}
} else {
ret = r_core_cmdf (core, "?v [%s]", input);
}
free (str);
return ret;
}
static int cmd_env(void *data, const char *input) {
RCore *core = (RCore*)data;
int ret = true;
switch (*input) {
case '?':
cmd_help_percent (core);
break;
default:
ret = r_core_cmdf (core, "env %s", input);
}
return ret;
}
static struct autocomplete_flag_map_t {
const char* name;
const char* desc;
int type;
} autocomplete_flags [] = {
{ "$dflt", "default autocomplete flag", R_CORE_AUTOCMPLT_DFLT },
{ "$flag", "shows known flag hints", R_CORE_AUTOCMPLT_FLAG },
{ "$flsp", "shows known flag-spaces hints", R_CORE_AUTOCMPLT_FLSP },
{ "$zign", "shows known zignatures hints", R_CORE_AUTOCMPLT_ZIGN },
{ "$eval", "shows known evals hints", R_CORE_AUTOCMPLT_EVAL },
{ "$prjt", "shows known projects hints", R_CORE_AUTOCMPLT_PRJT },
{ "$mins", NULL, R_CORE_AUTOCMPLT_MINS },
{ "$brkp", "shows known breakpoints hints", R_CORE_AUTOCMPLT_BRKP },
{ "$macro", NULL, R_CORE_AUTOCMPLT_MACR },
{ "$file", "hints file paths", R_CORE_AUTOCMPLT_FILE },
{ "$thme", "shows known themes hints", R_CORE_AUTOCMPLT_THME },
{ "$optn", "allows the selection for multiple options", R_CORE_AUTOCMPLT_OPTN },
{ "$ms", "shows mount hints", R_CORE_AUTOCMPLT_MS},
{ "$sdb", "shows sdb hints", R_CORE_AUTOCMPLT_SDB},
{ NULL, NULL, 0 }
};
static inline void print_dict(RCoreAutocomplete* a, int sub) {
if (!a) {
return;
}
int i, j;
const char* name = "unknown";
for (i = 0; i < a->n_subcmds; ++i) {
RCoreAutocomplete* b = a->subcmds[i];
if (b->locked) {
continue;
}
for (j = 0; j < R_CORE_AUTOCMPLT_END; ++j) {
if (b->type == autocomplete_flags[j].type) {
name = autocomplete_flags[j].name;
break;
}
}
eprintf ("[%3d] %s: '%s'\n", sub, name, b->cmd);
print_dict (a->subcmds[i], sub + 1);
}
}
static int autocomplete_type(const char* strflag) {
int i;
for (i = 0; i < R_CORE_AUTOCMPLT_END; ++i) {
if (autocomplete_flags[i].desc && !strncmp (strflag, autocomplete_flags[i].name, 5)) {
return autocomplete_flags[i].type;
}
}
eprintf ("Invalid flag '%s'\n", strflag);
return R_CORE_AUTOCMPLT_END;
}
static void cmd_autocomplete(RCore *core, const char *input) {
RCoreAutocomplete* b = core->autocomplete;
input = r_str_trim_ro (input);
char arg[256];
if (!*input) {
print_dict (core->autocomplete, 0);
return;
}
if (*input == '?') {
r_core_cmd_help (core, help_msg_triple_exclamation);
int i;
r_cons_printf ("|Types:\n");
for (i = 0; i < R_CORE_AUTOCMPLT_END; ++i) {
if (autocomplete_flags[i].desc) {
r_cons_printf ("| %s %s\n",
autocomplete_flags[i].name,
autocomplete_flags[i].desc);
}
}
return;
}
if (*input == '-') {
const char *arg = input + 1;
if (!*input) {
eprintf ("Use !!!-* or !!!-<cmd>\n");
return;
}
r_core_autocomplete_remove (b, arg);
return;
}
while (b) {
const char* end = r_str_trim_wp (input);
if (!end) {
break;
}
if ((end - input) >= sizeof (arg)) {
// wtf?
eprintf ("Exceeded the max arg length (255).\n");
return;
}
if (end == input) {
break;
}
memcpy (arg, input, end - input);
arg[end - input] = 0;
RCoreAutocomplete* a = r_core_autocomplete_find (b, arg, true);
input = r_str_trim_ro (end);
if (input && *input && !a) {
if (b->type == R_CORE_AUTOCMPLT_DFLT && !(b = r_core_autocomplete_add (b, arg, R_CORE_AUTOCMPLT_DFLT, false))) {
eprintf ("ENOMEM\n");
return;
} else if (b->type != R_CORE_AUTOCMPLT_DFLT) {
eprintf ("Cannot add autocomplete to '%s'. type not $dflt\n", b->cmd);
return;
}
} else if ((!input || !*input) && !a) {
if (arg[0] == '$') {
int type = autocomplete_type (arg);
if (type != R_CORE_AUTOCMPLT_END && !b->locked && !b->n_subcmds) {
b->type = type;
} else if (b->locked || b->n_subcmds) {
if (!b->cmd) {
return;
}
eprintf ("Changing type of '%s' is forbidden.\n", b->cmd);
}
} else {
if (!r_core_autocomplete_add (b, arg, R_CORE_AUTOCMPLT_DFLT, false)) {
eprintf ("ENOMEM\n");
return;
}
}
return;
} else if ((!input || !*input) && a) {
// eprintf ("Cannot add '%s'. Already exists.\n", arg);
return;
} else {
b = a;
}
}
eprintf ("Invalid usage of !!!\n");
}
static int cmd_last(void *data, const char *input) {
switch (*input) {
case 0:
r_cons_last ();
break;
default:
eprintf ("Usage: _ print last output\n");
}
return 0;
}
static int cmd_system(void *data, const char *input) {
RCore *core = (RCore*)data;
ut64 n;
int ret = 0;
switch (*input) {
case '-': //!-
if (input[1]) {
r_line_hist_free();
r_line_hist_save (R2_HOME_HISTORY);
} else {
r_line_hist_free();
}
break;
case '=': //!=
if (input[1] == '?') {
r_cons_printf ("Usage: !=[!] - enable/disable remote commands\n");
} else {
if (!r_sandbox_enable (0)) {
core->cmdremote = input[1]? 1: 0;
r_cons_println (r_str_bool (core->cmdremote));
}
}
break;
case '!': //!!
if (input[1] == '!') { // !!! & !!!-
cmd_autocomplete (core, input + 2);
} else if (input[1] == '?') {
cmd_help_exclamation (core);
} else if (input[1] == '*') {
char *cmd = r_str_trim_dup (input + 1);
(void)r_core_cmdf (core, "\"#!pipe %s\"", cmd);
free (cmd);
} else {
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1]) {
int olen;
char *out = NULL;
char *cmd = r_core_sysenv_begin (core, input);
if (cmd) {
void *bed = r_cons_sleep_begin ();
ret = r_sys_cmd_str_full (cmd + 1, NULL, &out, &olen, NULL);
r_cons_sleep_end (bed);
r_core_sysenv_end (core, input);
r_cons_memcat (out, olen);
free (out);
free (cmd);
} //else eprintf ("Error setting up system environment\n");
} else {
eprintf ("History saved to "R2_HOME_HISTORY"\n");
r_line_hist_save (R2_HOME_HISTORY);
}
}
break;
case '\0':
r_line_hist_list ();
break;
case '?': //!?
cmd_help_exclamation (core);
break;
case '*':
// TODO: use the api
{
char *cmd = r_str_trim_dup (input + 1);
cmd = r_str_replace (cmd, " ", "\\ ", true);
cmd = r_str_replace (cmd, "\\ ", " ", false);
cmd = r_str_replace (cmd, "\"", "'", false);
ret = r_core_cmdf (core, "\"#!pipe %s\"", cmd);
free (cmd);
}
break;
default:
n = atoi (input);
if (*input == '0' || n > 0) {
const char *cmd = r_line_hist_get (n);
if (cmd) {
r_core_cmd0 (core, cmd);
}
//else eprintf ("Error setting up system environment\n");
} else {
char *cmd = r_core_sysenv_begin (core, input);
if (cmd) {
void *bed = r_cons_sleep_begin ();
ret = r_sys_cmd (cmd);
r_cons_sleep_end (bed);
r_core_sysenv_end (core, input);
free (cmd);
} else {
eprintf ("Error setting up system environment\n");
}
}
break;
}
return ret;
}
#if __WINDOWS__
#include <tchar.h>
static void r_w32_cmd_pipe(RCore *core, char *radare_cmd, char *shell_cmd) {
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
SECURITY_ATTRIBUTES sa;
HANDLE pipe[2] = {NULL, NULL};
int fd_out = -1, cons_out = -1;
char *_shell_cmd = NULL;
LPTSTR _shell_cmd_ = NULL;
DWORD mode;
GetConsoleMode (GetStdHandle (STD_OUTPUT_HANDLE), &mode);
sa.nLength = sizeof (SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe (&pipe[0], &pipe[1], &sa, 0)) {
r_sys_perror ("r_w32_cmd_pipe/CreatePipe");
goto err_r_w32_cmd_pipe;
}
if (!SetHandleInformation (pipe[1], HANDLE_FLAG_INHERIT, 0)) {
r_sys_perror ("r_w32_cmd_pipe/SetHandleInformation");
goto err_r_w32_cmd_pipe;
}
si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
si.hStdInput = pipe[0];
si.dwFlags |= STARTF_USESTDHANDLES;
si.cb = sizeof (si);
_shell_cmd = shell_cmd;
while (*_shell_cmd && isspace ((ut8)*_shell_cmd)) {
_shell_cmd++;
}
char *tmp = r_str_newf ("/Q /c \"%s\"", shell_cmd);
if (!tmp) {
goto err_r_w32_cmd_pipe;
}
_shell_cmd = tmp;
_shell_cmd_ = r_sys_conv_utf8_to_win (_shell_cmd);
free (tmp);
if (!_shell_cmd_) {
goto err_r_w32_cmd_pipe;
}
TCHAR *systemdir = calloc (MAX_PATH, sizeof (TCHAR));
if (!systemdir) {
goto err_r_w32_cmd_pipe;
}
int ret = GetSystemDirectory (systemdir, MAX_PATH);
if (!ret) {
r_sys_perror ("r_w32_cmd_pipe/systemdir");
goto err_r_w32_cmd_pipe;
}
_tcscat_s (systemdir, MAX_PATH, TEXT("\\cmd.exe"));
// exec windows process
if (!CreateProcess (systemdir, _shell_cmd_, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
r_sys_perror ("r_w32_cmd_pipe/CreateProcess");
goto err_r_w32_cmd_pipe;
}
fd_out = _open_osfhandle ((intptr_t)pipe[1], _O_WRONLY|_O_TEXT);
if (fd_out == -1) {
perror ("_open_osfhandle");
goto err_r_w32_cmd_pipe;
}
cons_out = dup (1);
dup2 (fd_out, 1);
// exec radare command
r_core_cmd (core, radare_cmd, 0);
r_cons_flush ();
close (1);
close (fd_out);
fd_out = -1;
WaitForSingleObject (pi.hProcess, INFINITE);
err_r_w32_cmd_pipe:
if (pi.hProcess) {
CloseHandle (pi.hProcess);
}
if (pi.hThread) {
CloseHandle (pi.hThread);
}
if (pipe[0]) {
CloseHandle (pipe[0]);
}
if (pipe[1]) {
CloseHandle (pipe[1]);
}
if (fd_out != -1) {
close (fd_out);
}
if (cons_out != -1) {
dup2 (cons_out, 1);
close (cons_out);
}
free (systemdir);
free (_shell_cmd_);
SetConsoleMode (GetStdHandle (STD_OUTPUT_HANDLE), mode);
}
#endif
R_API int r_core_cmd_pipe(RCore *core, char *radare_cmd, char *shell_cmd) {
#if __UNIX__
int stdout_fd, fds[2];
int child;
#endif
int si, olen, ret = -1, pipecolor = -1;
char *str, *out = NULL;
if (r_sandbox_enable (0)) {
eprintf ("Pipes are not allowed in sandbox mode\n");
return -1;
}
si = r_cons_is_interactive ();
r_config_set_i (core->config, "scr.interactive", 0);
if (!r_config_get_i (core->config, "scr.color.pipe")) {
pipecolor = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
if (*shell_cmd=='!') {
r_cons_grep_parsecmd (shell_cmd, "\"");
olen = 0;
out = NULL;
// TODO: implement foo
str = r_core_cmd_str (core, radare_cmd);
r_sys_cmd_str_full (shell_cmd + 1, str, &out, &olen, NULL);
free (str);
r_cons_memcat (out, olen);
free (out);
ret = 0;
}
#if __UNIX__
radare_cmd = (char*)r_str_trim_head (radare_cmd);
shell_cmd = (char*)r_str_trim_head (shell_cmd);
signal (SIGPIPE, SIG_IGN);
stdout_fd = dup (1);
if (stdout_fd != -1) {
if (pipe (fds) == 0) {
child = r_sys_fork ();
if (child == -1) {
eprintf ("Cannot fork\n");
close (stdout_fd);
} else if (child) {
dup2 (fds[1], 1);
close (fds[1]);
close (fds[0]);
r_core_cmd (core, radare_cmd, 0);
r_cons_flush ();
close (1);
wait (&ret);
dup2 (stdout_fd, 1);
close (stdout_fd);
} else {
close (fds[1]);
dup2 (fds[0], 0);
//dup2 (1, 2); // stderr goes to stdout
r_sandbox_system (shell_cmd, 0);
close (stdout_fd);
}
} else {
eprintf ("r_core_cmd_pipe: Could not pipe\n");
}
}
#elif __WINDOWS__
r_w32_cmd_pipe (core, radare_cmd, shell_cmd);
#else
#ifdef _MSC_VER
#pragma message ("r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM")
#else
#warning r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM
#endif
eprintf ("r_core_cmd_pipe: unimplemented for this platform\n");
#endif
if (pipecolor != -1) {
r_config_set_i (core->config, "scr.color", pipecolor);
}
r_config_set_i (core->config, "scr.interactive", si);
return ret;
}
static char *parse_tmp_evals(RCore *core, const char *str) {
char *s = strdup (str);
int i, argc = r_str_split (s, ',');
char *res = strdup ("");
if (!s || !res) {
free (s);
free (res);
return NULL;
}
for (i = 0; i < argc; i++) {
char *eq, *kv = (char *)r_str_word_get0 (s, i);
if (!kv) {
break;
}
eq = strchr (kv, '=');
if (eq) {
*eq = 0;
const char *ov = r_config_get (core->config, kv);
if (!ov) {
continue;
}
char *cmd = r_str_newf ("e %s=%s;", kv, ov);
if (!cmd) {
free (s);
free (res);
return NULL;
}
res = r_str_prepend (res, cmd);
free (cmd);
r_config_set (core->config, kv, eq + 1);
*eq = '=';
} else {
eprintf ("Missing '=' in e: expression (%s)\n", kv);
}
}
free (s);
return res;
}
static int r_core_cmd_subst(RCore *core, char *cmd) {
ut64 rep = strtoull (cmd, NULL, 10);
int ret = 0, orep;
char *cmt, *colon = NULL, *icmd = NULL;
bool tmpseek = false;
bool original_tmpseek = core->tmpseek;
if (r_str_startswith (cmd, "GET /cmd/")) {
memmove (cmd, cmd + 9, strlen (cmd + 9) + 1);
char *http = strstr (cmd, "HTTP");
if (http) {
*http = 0;
http--;
if (*http == ' ') {
*http = 0;
}
}
r_cons_printf ("HTTP/1.0 %d %s\r\n%s"
"Connection: close\r\nContent-Length: %d\r\n\r\n",
200, "OK", "", -1);
return r_core_cmd0 (core, cmd);
}
/* must store a local orig_offset because there can be
* nested call of this function */
ut64 orig_offset = core->offset;
icmd = strdup (cmd);
if (core->max_cmd_depth - core->cons->context->cmd_depth == 1) {
core->prompt_offset = core->offset;
}
cmd = r_str_trim_head_tail (icmd);
// lines starting with # are ignored (never reach cmd_hash()), except #! and #?
if (!*cmd) {
if (core->cmdrepeat > 0) {
r_core_cmd_repeat (core, true);
ret = r_core_cmd_nullcallback (core);
}
goto beach;
}
if (!icmd || (cmd[0] == '#' && cmd[1] != '!' && cmd[1] != '?')) {
goto beach;
}
cmt = *icmd ? (char *)r_str_firstbut (icmd, '#', "\""): NULL;
if (cmt && (cmt[1] == ' ' || cmt[1] == '\t')) {
*cmt = 0;
}
if (*cmd != '"') {
if (!strchr (cmd, '\'')) { // allow | awk '{foo;bar}' // ignore ; if there's a single quote
if ((colon = strchr (cmd, ';'))) {
*colon = 0;
}
}
} else {
colon = NULL;
}
if (rep > 0) {
while (IS_DIGIT (*cmd)) {
cmd++;
}
// do not repeat null cmd
if (!*cmd) {
goto beach;
}
}
if (rep < 1) {
rep = 1;
}
// XXX if output is a pipe then we don't want to be interactive
if (rep > 1 && r_sandbox_enable (0)) {
eprintf ("Command repeat sugar disabled in sandbox mode (%s)\n", cmd);
goto beach;
} else {
if (rep > INTERACTIVE_MAX_REP) {
if (r_cons_is_interactive ()) {
if (!r_cons_yesno ('n', "Are you sure to repeat this %"PFMT64d" times? (y/N)", rep)) {
goto beach;
}
}
}
}
// TODO: store in core->cmdtimes to speedup ?
const char *cmdrep = core->cmdtimes ? core->cmdtimes: "";
orep = rep;
r_cons_break_push (NULL, NULL);
int ocur_enabled = core->print && core->print->cur_enabled;
while (rep-- && *cmd) {
if (core->print) {
core->print->cur_enabled = false;
if (ocur_enabled && core->seltab >= 0) {
if (core->seltab == core->curtab) {
core->print->cur_enabled = true;
}
}
}
if (r_cons_is_breaked ()) {
break;
}
char *cr = strdup (cmdrep);
core->break_loop = false;
ret = r_core_cmd_subst_i (core, cmd, colon, (rep == orep - 1) ? &tmpseek : NULL);
if (ret && *cmd == 'q') {
free (cr);
goto beach;
}
if (core->break_loop) {
free (cr);
break;
}
if (cr && *cr && orep > 1) {
// XXX: do not flush here, we need r_cons_push () and r_cons_pop()
r_cons_flush ();
// XXX: we must import register flags in C
(void)r_core_cmd0 (core, ".dr*");
(void)r_core_cmd0 (core, cr);
}
free (cr);
}
r_cons_break_pop ();
if (tmpseek) {
r_core_seek (core, orig_offset, 1);
core->tmpseek = original_tmpseek;
}
if (core->print) {
core->print->cur_enabled = ocur_enabled;
}
if (colon && colon[1]) {
for (++colon; *colon == ';'; colon++) {
;
}
r_core_cmd_subst (core, colon);
} else {
if (!*icmd) {
r_core_cmd_nullcallback (core);
}
}
beach:
free (icmd);
return ret;
}
static char *find_eoq(char *p) {
for (; *p; p++) {
if (*p == '"') {
break;
}
if (*p == '\\' && p[1] == '"') {
p++;
}
}
return p;
}
static char* findSeparator(char *p) {
char *q = strchr (p, '+');
if (q) {
return q;
}
return strchr (p, '-');
}
static void tmpenvs_free(void *item) {
r_sys_setenv (item, NULL);
free (item);
}
static bool set_tmp_arch(RCore *core, char *arch, char **tmparch) {
if (!tmparch) {
eprintf ("tmparch should be set\n");
}
*tmparch = strdup (r_config_get (core->config, "asm.arch"));
r_config_set (core->config, "asm.arch", arch);
core->fixedarch = true;
return true;
}
static bool set_tmp_bits(RCore *core, int bits, char **tmpbits) {
if (!tmpbits) {
eprintf ("tmpbits should be set\n");
}
*tmpbits = strdup (r_config_get (core->config, "asm.bits"));
r_config_set_i (core->config, "asm.bits", bits);
core->fixedbits = true;
return true;
}
static int r_core_cmd_subst_i(RCore *core, char *cmd, char *colon, bool *tmpseek) {
RList *tmpenvs = r_list_newf (tmpenvs_free);
const char *quotestr = "`";
const char *tick = NULL;
char *ptr, *ptr2, *str;
char *arroba = NULL;
char *grep = NULL;
RIODesc *tmpdesc = NULL;
int pamode = !core->io->va;
int i, ret = 0, pipefd;
bool usemyblock = false;
int scr_html = -1;
int scr_color = -1;
bool eos = false;
bool haveQuote = false;
bool oldfixedarch = core->fixedarch;
bool oldfixedbits = core->fixedbits;
bool cmd_tmpseek = false;
ut64 tmpbsz = core->blocksize;
int cmd_ignbithints = -1;
if (!cmd) {
r_list_free (tmpenvs);
return 0;
}
cmd = r_str_trim_head_tail (cmd);
char *$0 = strstr (cmd, "$(");
if ($0) {
char *$1 = strchr ($0 + 2, ')');
if ($1) {
*$0 = '`';
*$1 = '`';
memmove ($0 + 1, $0 + 2, strlen ($0 + 2) + 1);
} else {
eprintf ("Unterminated $() block\n");
}
}
/* quoted / raw command */
switch (*cmd) {
case '.':
if (cmd[1] == '"') { /* interpret */
r_list_free (tmpenvs);
return r_cmd_call (core->rcmd, cmd);
}
break;
case '"':
for (; *cmd; ) {
int pipefd = -1;
ut64 oseek = UT64_MAX;
char *line, *p;
haveQuote = *cmd == '"';
if (haveQuote) {
cmd++;
p = *cmd ? find_eoq (cmd) : NULL;
if (!p || !*p) {
eprintf ("Missing \" in (%s).", cmd);
r_list_free (tmpenvs);
return false;
}
*p++ = 0;
if (!*p) {
eos = true;
}
} else {
char *sc = strchr (cmd, ';');
if (sc) {
*sc = 0;
}
r_core_cmd0 (core, cmd);
if (!sc) {
break;
}
cmd = sc + 1;
continue;
}
char op0 = 0;
if (*p) {
// workaround :D
if (p[0] == '@') {
p--;
}
while (p[1] == ';' || IS_WHITESPACE (p[1])) {
p++;
}
if (p[1] == '@' || (p[1] && p[2] == '@')) {
char *q = strchr (p + 1, '"');
if (q) {
op0 = *q;
*q = 0;
}
haveQuote = q != NULL;
oseek = core->offset;
r_core_seek (core, r_num_math (core->num, p + 2), 1);
if (q) {
*p = '"';
p = q;
} else {
p = strchr (p + 1, ';');
}
}
if (p && *p && p[1] == '>') {
str = p + 2;
while (*str == '>') {
str++;
}
str = (char *)r_str_trim_ro (str);
r_cons_flush ();
const bool append = p[2] == '>';
pipefd = r_cons_pipe_open (str, 1, append);
}
}
line = strdup (cmd);
line = r_str_replace (line, "\\\"", "\"", true);
if (p && *p && p[1] == '|') {
str = p + 2;
while (IS_WHITESPACE (*str)) {
str++;
}
r_core_cmd_pipe (core, cmd, str);
} else {
r_cmd_call (core->rcmd, line);
}
free (line);
if (oseek != UT64_MAX) {
r_core_seek (core, oseek, 1);
}
if (pipefd != -1) {
r_cons_flush ();
r_cons_pipe_close (pipefd);
}
if (!p) {
break;
}
if (eos) {
break;
}
if (haveQuote) {
if (*p == ';') {
cmd = p + 1;
} else {
if (*p == '"') {
cmd = p;
} else {
*p = op0;
cmd = p;
}
}
} else {
cmd = p + 1;
}
}
r_list_free (tmpenvs);
return true;
case '(':
if (cmd[1] != '*' && !strstr (cmd, ")()")) {
r_list_free (tmpenvs);
return r_cmd_call (core->rcmd, cmd);
}
break;
case '?':
if (cmd[1] == '>') {
r_core_cmd_help (core, help_msg_greater_sign);
r_list_free (tmpenvs);
return true;
}
}
// TODO must honor `
/* comments */
if (*cmd != '#') {
ptr = (char *)r_str_firstbut (cmd, '#', "`\""); // TODO: use quotestr here
if (ptr && (ptr[1] == ' ' || ptr[1] == '\t')) {
*ptr = '\0';
}
}
/* multiple commands */
// TODO: must honor " and ` boundaries
//ptr = strrchr (cmd, ';');
if (*cmd != '#') {
ptr = (char *)r_str_lastbut (cmd, ';', quotestr);
if (colon && ptr) {
int ret ;
*ptr = '\0';
if (r_core_cmd_subst (core, cmd) == -1) {
r_list_free (tmpenvs);
return -1;
}
cmd = ptr + 1;
ret = r_core_cmd_subst (core, cmd);
*ptr = ';';
r_list_free (tmpenvs);
return ret;
//r_cons_flush ();
}
}
// TODO must honor " and `
/* pipe console to shell process */
//ptr = strchr (cmd, '|');
ptr = (char *)r_str_lastbut (cmd, '|', quotestr);
if (ptr) {
if (ptr > cmd) {
char *ch = ptr - 1;
if (*ch == '\\') {
memmove (ch, ptr, strlen (ptr) + 1);
goto escape_pipe;
}
}
char *ptr2 = strchr (cmd, '`');
if (!ptr2 || (ptr2 && ptr2 > ptr)) {
if (!tick || (tick && tick > ptr)) {
*ptr = '\0';
cmd = r_str_trim_nc (cmd);
if (!strcmp (ptr + 1, "?")) { // "|?"
r_core_cmd_help (core, help_msg_vertical_bar);
r_list_free (tmpenvs);
return ret;
} else if (!strncmp (ptr + 1, "H", 1)) { // "|H"
scr_html = r_config_get_i (core->config, "scr.html");
r_config_set_i (core->config, "scr.html", true);
} else if (!strcmp (ptr + 1, "T")) { // "|T"
scr_color = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
core->cons->use_tts = true;
} else if (!strcmp (ptr + 1, ".")) { // "|."
ret = *cmd ? r_core_cmdf (core, ".%s", cmd) : 0;
r_list_free (tmpenvs);
return ret;
} else if (ptr[1]) { // "| grep .."
int value = core->num->value;
if (*cmd) {
r_core_cmd_pipe (core, cmd, ptr + 1);
} else {
char *res = r_io_system (core->io, ptr + 1);
if (res) {
r_cons_printf ("%s\n", res);
free (res);
}
}
core->num->value = value;
r_list_free (tmpenvs);
return 0;
} else { // "|"
scr_html = r_config_get_i (core->config, "scr.html");
r_config_set_i (core->config, "scr.html", 0);
scr_color = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
}
}
}
escape_pipe:
// TODO must honor " and `
/* bool conditions */
ptr = (char *)r_str_lastbut (cmd, '&', quotestr);
//ptr = strchr (cmd, '&');
while (ptr && *ptr && ptr[1] == '&') {
*ptr = '\0';
ret = r_cmd_call (core->rcmd, cmd);
if (ret == -1) {
eprintf ("command error(%s)\n", cmd);
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
r_list_free (tmpenvs);
return ret;
}
for (cmd = ptr + 2; cmd && *cmd == ' '; cmd++) {
;
}
ptr = strchr (cmd, '&');
}
/* Out Of Band Input */
R_FREE (core->oobi);
ptr = strstr (cmd, "?*");
if (ptr && (ptr == cmd || ptr[-1] != '~')) {
ptr[0] = 0;
if (*cmd != '#') {
int detail = 0;
if (cmd < ptr && ptr[-1] == '?') {
detail++;
if (cmd < ptr - 1 && ptr[-2] == '?') {
detail++;
}
}
r_cons_break_push (NULL, NULL);
recursive_help (core, detail, cmd);
r_cons_break_pop ();
r_cons_grep_parsecmd (ptr + 2, "`");
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
r_list_free (tmpenvs);
return 0;
}
}
#if 0
ptr = strchr (cmd, '<');
if (ptr) {
ptr[0] = '\0';
if (r_cons_singleton ()->is_interactive) {
if (ptr[1] == '<') {
/* this is a bit mess */
//const char *oprompt = strdup (r_line_singleton ()->prompt);
//oprompt = ">";
for (str = ptr + 2; str[0] == ' '; str++) {
//nothing to see here
}
eprintf ("==> Reading from stdin until '%s'\n", str);
free (core->oobi);
core->oobi = malloc (1);
if (core->oobi) {
core->oobi[0] = '\0';
}
core->oobi_len = 0;
for (;;) {
char buf[1024];
int ret;
write (1, "> ", 2);
fgets (buf, sizeof (buf) - 1, stdin); // XXX use r_line ??
if (feof (stdin)) {
break;
}
if (*buf) buf[strlen (buf) - 1]='\0';
ret = strlen (buf);
core->oobi_len += ret;
core->oobi = realloc (core->oobi, core->oobi_len + 1);
if (core->oobi) {
if (!strcmp (buf, str)) {
break;
}
strcat ((char *)core->oobi, buf);
}
}
//r_line_set_prompt (oprompt);
} else {
for (str = ptr + 1; *str == ' '; str++) {
//nothing to see here
}
if (!*str) {
goto next;
}
eprintf ("Slurping file '%s'\n", str);
free (core->oobi);
core->oobi = (ut8*)r_file_slurp (str, &core->oobi_len);
if (!core->oobi) {
eprintf ("cannot open file\n");
} else if (ptr == cmd) {
return r_core_cmd_buffer (core, (const char *)core->oobi);
}
}
} else {
eprintf ("Cannot slurp with << in non-interactive mode\n");
r_list_free (tmpenvs);
return 0;
}
}
next:
#endif
/* pipe console to file */
ptr = (char *)r_str_firstbut (cmd, '>', "\"");
// TODO honor `
if (ptr) {
if (ptr > cmd) {
char *ch = ptr - 1;
if (*ch == '\\') {
memmove (ch, ptr, strlen (ptr) + 1);
goto escape_redir;
}
}
if (ptr[0] && ptr[1] == '?') {
r_core_cmd_help (core, help_msg_greater_sign);
r_list_free (tmpenvs);
return true;
}
int fdn = 1;
int pipecolor = r_config_get_i (core->config, "scr.color.pipe");
int use_editor = false;
int ocolor = r_config_get_i (core->config, "scr.color");
*ptr = '\0';
str = r_str_trim_head_tail (ptr + 1 + (ptr[1] == '>'));
if (!*str) {
eprintf ("No output?\n");
goto next2;
}
/* r_cons_flush() handles interactive output (to the terminal)
* differently (e.g. asking about too long output). This conflicts
* with piping to a file. Disable it while piping. */
if (ptr > (cmd + 1) && IS_WHITECHAR (ptr[-2])) {
char *fdnum = ptr - 1;
if (*fdnum == 'H') { // "H>"
scr_html = r_config_get_i (core->config, "scr.html");
r_config_set_i (core->config, "scr.html", true);
pipecolor = true;
*fdnum = 0;
} else {
if (IS_DIGIT (*fdnum)) {
fdn = *fdnum - '0';
}
*fdnum = 0;
}
}
r_cons_set_interactive (false);
if (!strcmp (str, "-")) {
use_editor = true;
str = r_file_temp ("dumpedit");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
const bool appendResult = (ptr[1] == '>');
if (*str == '$') {
// pipe to alias variable
// register output of command as an alias
char *o = r_core_cmd_str (core, cmd);
if (appendResult) {
char *oldText = r_cmd_alias_get (core->rcmd, str, 1);
if (oldText) {
char *two = r_str_newf ("%s%s", oldText, o);
if (two) {
r_cmd_alias_set (core->rcmd, str, two, 1);
free (two);
}
} else {
char *n = r_str_newf ("$%s", o);
r_cmd_alias_set (core->rcmd, str, n, 1);
free (n);
}
} else {
char *n = r_str_newf ("$%s", o);
r_cmd_alias_set (core->rcmd, str, n, 1);
free (n);
}
ret = 0;
free (o);
} else if (fdn > 0) {
// pipe to file (or append)
pipefd = r_cons_pipe_open (str, fdn, appendResult);
if (pipefd != -1) {
if (!pipecolor) {
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
ret = r_core_cmd_subst (core, cmd);
r_cons_flush ();
r_cons_pipe_close (pipefd);
}
}
r_cons_set_last_interactive ();
if (!pipecolor) {
r_config_set_i (core->config, "scr.color", ocolor);
}
if (use_editor) {
const char *editor = r_config_get (core->config, "cfg.editor");
if (editor && *editor) {
r_sys_cmdf ("%s '%s'", editor, str);
r_file_rm (str);
} else {
eprintf ("No cfg.editor configured\n");
}
r_config_set_i (core->config, "scr.color", ocolor);
free (str);
}
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
core->cons->use_tts = false;
r_list_free (tmpenvs);
return ret;
}
escape_redir:
next2:
/* sub commands */
ptr = strchr (cmd, '`');
if (ptr) {
if (ptr > cmd) {
char *ch = ptr - 1;
if (*ch == '\\') {
memmove (ch, ptr, strlen (ptr) + 1);
goto escape_backtick;
}
}
bool empty = false;
int oneline = 1;
if (ptr[1] == '`') {
memmove (ptr, ptr + 1, strlen (ptr));
oneline = 0;
empty = true;
}
ptr2 = strchr (ptr + 1, '`');
if (empty) {
/* do nothing */
} else if (!ptr2) {
eprintf ("parse: Missing backtick in expression.\n");
goto fail;
} else {
int value = core->num->value;
*ptr = '\0';
*ptr2 = '\0';
if (ptr[1] == '!') {
str = r_core_cmd_str_pipe (core, ptr + 1);
} else {
// Color disabled when doing backticks ?e `pi 1`
int ocolor = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", 0);
core->cmd_in_backticks = true;
str = r_core_cmd_str (core, ptr + 1);
core->cmd_in_backticks = false;
r_config_set_i (core->config, "scr.color", ocolor);
}
if (!str) {
goto fail;
}
// ignore contents if first char is pipe or comment
if (*str == '|' || *str == '*') {
eprintf ("r_core_cmd_subst_i: invalid backticked command\n");
free (str);
goto fail;
}
if (oneline && str) {
for (i = 0; str[i]; i++) {
if (str[i] == '\n') {
str[i] = ' ';
}
}
}
str = r_str_append (str, ptr2 + 1);
cmd = r_str_append (strdup (cmd), str);
core->num->value = value;
ret = r_core_cmd_subst (core, cmd);
free (cmd);
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
free (str);
r_list_free (tmpenvs);
return ret;
}
}
escape_backtick:
// TODO must honor " and `
if (*cmd != '"' && *cmd) {
const char *s = strstr (cmd, "~?");
if (s) {
bool showHelp = false;
if (cmd == s) {
// ~?
// ~??
showHelp = true;
} else {
// pd~?
// pd~??
if (!strcmp (s, "~??")) {
showHelp = true;
}
}
if (showHelp) {
r_cons_grep_help ();
r_list_free (tmpenvs);
return true;
}
}
}
if (*cmd != '.') {
grep = r_cons_grep_strip (cmd, quotestr);
}
/* temporary seek commands */
// if (*cmd != '(' && *cmd != '"') {
if (*cmd != '"') {
ptr = strchr (cmd, '@');
if (ptr == cmd + 1 && *cmd == '?') {
ptr = NULL;
}
} else {
ptr = NULL;
}
cmd_tmpseek = core->tmpseek = ptr ? true: false;
int rc = 0;
if (ptr) {
char *f, *ptr2 = strchr (ptr + 1, '!');
ut64 addr = core->offset;
bool addr_is_set = false;
char *tmpbits = NULL;
const char *offstr = NULL;
bool is_bits_set = false;
bool is_arch_set = false;
char *tmpeval = NULL;
char *tmpasm = NULL;
bool flgspc_changed = false;
int tmpfd = -1;
int sz, len;
ut8 *buf;
*ptr++ = '\0';
repeat_arroba:
arroba = (ptr[0] && ptr[1] && ptr[2])?
strchr (ptr + 2, '@'): NULL;
if (arroba) {
*arroba = 0;
}
for (; *ptr == ' '; ptr++) {
//nothing to see here
}
if (*ptr && ptr[1] == ':') {
/* do nothing here */
} else {
ptr--;
}
ptr = r_str_trim_tail (ptr);
if (ptr[1] == '?') {
r_core_cmd_help (core, help_msg_at);
} else if (ptr[1] == '%') { // "@%"
char *k = strdup (ptr + 2);
char *v = strchr (k, '=');
if (v) {
*v++ = 0;
r_sys_setenv (k, v);
r_list_append (tmpenvs, k);
} else {
free (k);
}
} else if (ptr[1] == '.') { // "@."
if (ptr[2] == '.') { // "@.."
if (ptr[3] == '.') { // "@..."
ut64 addr = r_num_tail (core->num, core->offset, ptr + 4);
r_core_block_size (core, R_ABS ((st64)addr - (st64)core->offset));
goto fuji;
} else {
addr = r_num_tail (core->num, core->offset, ptr + 3);
r_core_seek (core, addr, 1);
cmd_tmpseek = core->tmpseek = true;
goto fuji;
}
} else {
// WAT DU
eprintf ("TODO: what do you expect for @. import offset from file maybe?\n");
}
} else if (ptr[0] && ptr[1] == ':' && ptr[2]) {
switch (ptr[0]) {
case 'F': // "@F:" // temporary flag space
flgspc_changed = r_flag_space_push (core->flags, ptr + 2);
break;
case 'B': // "@B:#" // seek to the last instruction in current bb
{
int index = (int)r_num_math (core->num, ptr + 2);
RAnalBlock *bb = r_anal_bb_from_offset (core->anal, core->offset);
if (bb) {
// handle negative indices
if (index < 0) {
index = bb->ninstr + index;
}
if (index >= 0 && index < bb->ninstr) {
ut16 inst_off = r_anal_bb_offset_inst (bb, index);
r_core_seek (core, bb->addr + inst_off, 1);
cmd_tmpseek = core->tmpseek = true;
} else {
eprintf ("The current basic block has %d instructions\n", bb->ninstr);
}
} else {
eprintf ("Can't find a basic block for 0x%08"PFMT64x"\n", core->offset);
}
break;
}
break;
case 'f': // "@f:" // slurp file in block
f = r_file_slurp (ptr + 2, &sz);
if (f) {
{
RBuffer *b = r_buf_new_with_bytes ((const ut8*)f, sz);
RIODesc *d = r_io_open_buffer (core->io, b, R_PERM_RWX, 0);
if (d) {
if (tmpdesc) {
r_io_desc_close (tmpdesc);
}
tmpdesc = d;
if (pamode) {
r_config_set_i (core->config, "io.va", 1);
}
r_io_map_new (core->io, d->fd, d->perm, 0, core->offset, r_buf_size (b));
}
}
#if 0
buf = malloc (sz);
if (buf) {
free (core->block);
core->block = buf;
core->blocksize = sz;
memcpy (core->block, f, sz);
usemyblock = true;
} else {
eprintf ("cannot alloc %d", sz);
}
free (f);
#endif
} else {
eprintf ("cannot open '%s'\n", ptr + 3);
}
break;
case 'r': // "@r:" // regname
if (ptr[1] == ':') {
ut64 regval;
char *mander = strdup (ptr + 2);
char *sep = findSeparator (mander);
if (sep) {
char ch = *sep;
*sep = 0;
regval = r_debug_reg_get (core->dbg, mander);
*sep = ch;
char *numexpr = r_str_newf ("0x%"PFMT64x"%s", regval, sep);
regval = r_num_math (core->num, numexpr);
free (numexpr);
} else {
regval = r_debug_reg_get (core->dbg, ptr + 2);
}
r_core_seek (core, regval, 1);
cmd_tmpseek = core->tmpseek = true;
free (mander);
}
break;
case 'b': // "@b:" // bits
is_bits_set = set_tmp_bits (core, r_num_math (core->num, ptr + 2), &tmpbits);
cmd_ignbithints = r_config_get_i (core->config, "anal.ignbithints");
r_config_set_i (core->config, "anal.ignbithints", 1);
break;
case 'i': // "@i:"
{
ut64 addr = r_num_math (core->num, ptr + 2);
if (addr) {
r_core_cmdf (core, "so %s", ptr + 2);
// r_core_seek (core, core->offset, 1);
cmd_tmpseek = core->tmpseek = true;
}
}
break;
case 'e': // "@e:"
{
char *cmd = parse_tmp_evals (core, ptr + 2);
if (!tmpeval) {
tmpeval = cmd;
} else {
tmpeval = r_str_prepend (tmpeval, cmd);
free (cmd);
}
}
break;
case 'x': // "@x:" // hexpairs
if (ptr[1] == ':') {
buf = malloc (strlen (ptr + 2) + 1);
if (buf) {
len = r_hex_str2bin (ptr + 2, buf);
r_core_block_size (core, R_ABS (len));
if (len > 0) {
RBuffer *b = r_buf_new_with_bytes (buf, len);
RIODesc *d = r_io_open_buffer (core->io, b, R_PERM_RWX, 0);
if (d) {
if (tmpdesc) {
r_io_desc_close (tmpdesc);
}
tmpdesc = d;
if (pamode) {
r_config_set_i (core->config, "io.va", 1);
}
r_io_map_new (core->io, d->fd, d->perm, 0, core->offset, r_buf_size (b));
r_core_block_size (core, len);
r_core_block_read (core);
}
} else {
eprintf ("Error: Invalid hexpairs for @x:\n");
}
free (buf);
} else {
eprintf ("cannot allocate\n");
}
} else {
eprintf ("Invalid @x: syntax\n");
}
break;
case 'k': // "@k"
{
char *out = sdb_querys (core->sdb, NULL, 0, ptr + ((ptr[1])? 2: 1));
if (out) {
r_core_seek (core, r_num_math (core->num, out), 1);
free (out);
usemyblock = true;
}
}
break;
case 'o': // "@o:3"
if (ptr[1] == ':') {
tmpfd = core->io->desc ? core->io->desc->fd : -1;
r_io_use_fd (core->io, atoi (ptr + 2));
}
break;
case 'a': // "@a:"
if (ptr[1] == ':') {
char *q = strchr (ptr + 2, ':');
if (q) {
*q++ = 0;
int bits = r_num_math (core->num, q);
is_bits_set = set_tmp_bits (core, bits, &tmpbits);
}
is_arch_set = set_tmp_arch (core, ptr + 2, &tmpasm);
} else {
eprintf ("Usage: pd 10 @a:arm:32\n");
}
break;
case 's': // "@s:" // wtf syntax
{
len = strlen (ptr + 2);
r_core_block_size (core, len);
const ut8 *buf = (const ut8*)r_str_trim_ro (ptr + 2);
if (len > 0) {
RBuffer *b = r_buf_new_with_bytes (buf, len);
RIODesc *d = r_io_open_buffer (core->io, b, R_PERM_RWX, 0);
if (!core->io->va) {
r_config_set_i (core->config, "io.va", 1);
}
if (d) {
if (tmpdesc) {
r_io_desc_close (tmpdesc);
}
tmpdesc = d;
if (pamode) {
r_config_set_i (core->config, "io.va", 1);
}
r_io_map_new (core->io, d->fd, d->perm, 0, core->offset, r_buf_size (b));
r_core_block_size (core, len);
// r_core_block_read (core);
}
}
}
break;
default:
goto ignore;
}
*ptr = '@';
/* trim whitespaces before the @ */
/* Fixes pd @x:9090 */
char *trim = ptr - 2;
while (trim > cmd) {
if (!IS_WHITESPACE (*trim)) {
break;
}
*trim = 0;
trim--;
}
goto next_arroba;
}
ignore:
ptr = r_str_trim_head (ptr + 1) - 1;
cmd = r_str_trim_nc (cmd);
if (ptr2) {
if (strlen (ptr + 1) == 13 && strlen (ptr2 + 1) == 6 &&
!memcmp (ptr + 1, "0x", 2) &&
!memcmp (ptr2 + 1, "0x", 2)) {
/* 0xXXXX:0xYYYY */
} else if (strlen (ptr + 1) == 9 && strlen (ptr2 + 1) == 4) {
/* XXXX:YYYY */
} else {
*ptr2 = '\0';
if (!ptr2[1]) {
goto fail;
}
r_core_block_size (
core, r_num_math (core->num, ptr2 + 1));
}
}
offstr = r_str_trim_head (ptr + 1);
addr = r_num_math (core->num, offstr);
addr_is_set = true;
if (isalpha ((ut8)ptr[1]) && !addr) {
if (!r_flag_get (core->flags, ptr + 1)) {
eprintf ("Invalid address (%s)\n", ptr + 1);
goto fail;
}
} else {
char ch = *offstr;
if (ch == '-' || ch == '+') {
addr = core->offset + addr;
}
}
// remap thhe tmpdesc if any
if (addr) {
RIODesc *d = tmpdesc;
if (d) {
r_io_map_new (core->io, d->fd, d->perm, 0, addr, r_io_desc_size (d));
}
}
next_arroba:
if (arroba) {
ptr = arroba + 1;
*arroba = '@';
arroba = NULL;
goto repeat_arroba;
}
core->fixedblock = !!tmpdesc;
if (core->fixedblock) {
r_core_block_read (core);
}
if (ptr[1] == '@') {
if (ptr[2] == '@') {
char *rule = ptr + 3;
while (*rule && *rule == ' ') {
rule++;
}
ret = r_core_cmd_foreach3 (core, cmd, rule);
} else {
ret = r_core_cmd_foreach (core, cmd, ptr + 2);
}
} else {
bool tmpseek = false;
const char *fromvars[] = { "anal.from", "diff.from", "graph.from",
"io.buffer.from", "lines.from", "search.from", "zoom.from", NULL };
const char *tovars[] = { "anal.to", "diff.to", "graph.to",
"io.buffer.to", "lines.to", "search.to", "zoom.to", NULL };
ut64 curfrom[R_ARRAY_SIZE (fromvars) - 1], curto[R_ARRAY_SIZE (tovars) - 1];
// "@(A B)"
if (ptr[1] == '(') {
char *range = ptr + 3;
char *p = strchr (range, ' ');
if (!p) {
eprintf ("Usage: / ABCD @..0x1000 0x3000\n");
free (tmpeval);
free (tmpasm);
free (tmpbits);
goto fail;
}
*p = '\x00';
ut64 from = r_num_math (core->num, range);
ut64 to = r_num_math (core->num, p + 1);
// save current ranges
for (i = 0; fromvars[i]; i++) {
curfrom[i] = r_config_get_i (core->config, fromvars[i]);
}
for (i = 0; tovars[i]; i++) {
curto[i] = r_config_get_i (core->config, tovars[i]);
}
// set new ranges
for (i = 0; fromvars[i]; i++) {
r_config_set_i (core->config, fromvars[i], from);
}
for (i = 0; tovars[i]; i++) {
r_config_set_i (core->config, tovars[i], to);
}
tmpseek = true;
}
if (usemyblock) {
if (addr_is_set) {
core->offset = addr;
}
ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd));
} else {
if (addr_is_set) {
if (ptr[1]) {
r_core_seek (core, addr, 1);
r_core_block_read (core);
}
}
ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd));
}
if (tmpseek) {
// restore ranges
for (i = 0; fromvars[i]; i++) {
r_config_set_i (core->config, fromvars[i], curfrom[i]);
}
for (i = 0; tovars[i]; i++) {
r_config_set_i (core->config, tovars[i], curto[i]);
}
}
}
if (ptr2) {
*ptr2 = '!';
r_core_block_size (core, tmpbsz);
}
if (is_arch_set) {
core->fixedarch = oldfixedarch;
r_config_set (core->config, "asm.arch", tmpasm);
R_FREE (tmpasm);
}
if (tmpfd != -1) {
// TODO: reuse tmpfd instead of
r_io_use_fd (core->io, tmpfd);
}
if (tmpdesc) {
if (pamode) {
r_config_set_i (core->config, "io.va", 0);
}
r_io_desc_close (tmpdesc);
tmpdesc = NULL;
}
if (is_bits_set) {
r_config_set (core->config, "asm.bits", tmpbits);
core->fixedbits = oldfixedbits;
}
if (tmpbsz != core->blocksize) {
r_core_block_size (core, tmpbsz);
}
if (tmpeval) {
r_core_cmd0 (core, tmpeval);
R_FREE (tmpeval);
}
if (flgspc_changed) {
r_flag_space_pop (core->flags);
}
*ptr = '@';
rc = ret;
goto beach;
}
fuji:
rc = cmd? r_cmd_call (core->rcmd, r_str_trim_head (cmd)): false;
beach:
r_cons_grep_process (grep);
if (scr_html != -1) {
r_cons_flush ();
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
r_list_free (tmpenvs);
if (tmpdesc) {
r_io_desc_close (tmpdesc);
tmpdesc = NULL;
}
core->fixedarch = oldfixedarch;
core->fixedbits = oldfixedbits;
if (tmpseek) {
*tmpseek = cmd_tmpseek;
}
if (cmd_ignbithints != -1) {
r_config_set_i (core->config, "anal.ignbithints", cmd_ignbithints);
}
return rc;
fail:
rc = -1;
goto beach;
}
static int foreach_comment(void *user, const char *k, const char *v) {
RAnalMetaUserItem *ui = user;
RCore *core = ui->anal->user;
const char *cmd = ui->user;
if (!strncmp (k, "meta.C.", 7)) {
char *cmt = (char *)sdb_decode (v, 0);
if (cmt) {
r_core_cmdf (core, "s %s", k + 7);
r_core_cmd0 (core, cmd);
free (cmt);
}
}
return 1;
}
struct exec_command_t {
RCore *core;
const char *cmd;
};
static bool exec_command_on_flag(RFlagItem *flg, void *u) {
struct exec_command_t *user = (struct exec_command_t *)u;
r_core_block_size (user->core, flg->size);
r_core_seek (user->core, flg->offset, 1);
r_core_cmd0 (user->core, user->cmd);
return true;
}
static void foreach_pairs(RCore *core, const char *cmd, const char *each) {
const char *arg;
int pair = 0;
for (arg = each ; ; ) {
char *next = strchr (arg, ' ');
if (next) {
*next = 0;
}
if (arg && *arg) {
ut64 n = r_num_get (NULL, arg);
if (pair%2) {
r_core_block_size (core, n);
r_core_cmd0 (core, cmd);
} else {
r_core_seek (core, n, 1);
}
pair++;
}
if (!next) {
break;
}
arg = next + 1;
}
}
R_API int r_core_cmd_foreach3(RCore *core, const char *cmd, char *each) { // "@@@"
RDebug *dbg = core->dbg;
RList *list, *head;
RListIter *iter;
int i;
const char *filter = NULL;
if (each[1] == ':') {
filter = each + 2;
}
switch (each[0]) {
case '=':
foreach_pairs (core, cmd, each + 1);
break;
case '?':
r_core_cmd_help (core, help_msg_at_at_at);
break;
case 'c':
if (filter) {
char *arg = r_core_cmd_str (core, filter);
foreach_pairs (core, cmd, arg);
free (arg);
} else {
eprintf ("Usage: @@@c:command # same as @@@=`command`\n");
}
break;
case 'C':
r_meta_list_cb (core->anal, R_META_TYPE_COMMENT, 0, foreach_comment, (void*)cmd, UT64_MAX);
break;
case 'm':
{
int fd = r_io_fd_get_current (core->io);
// only iterate maps of current fd
RList *maps = r_io_map_get_for_fd (core->io, fd);
RIOMap *map;
if (maps) {
RListIter *iter;
r_list_foreach (maps, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_core_block_size (core, map->itv.size);
r_core_cmd0 (core, cmd);
}
r_list_free (maps);
}
}
break;
case 'M':
if (dbg && dbg->h && dbg->maps) {
RDebugMap *map;
r_list_foreach (dbg->maps, iter, map) {
r_core_seek (core, map->addr, 1);
//r_core_block_size (core, map->size);
r_core_cmd0 (core, cmd);
}
}
break;
case 't':
// iterate over all threads
if (dbg && dbg->h && dbg->h->threads) {
int origpid = dbg->pid;
RDebugPid *p;
list = dbg->h->threads (dbg, dbg->pid);
if (!list) {
return false;
}
r_list_foreach (list, iter, p) {
r_core_cmdf (core, "dp %d", p->pid);
r_cons_printf ("PID %d\n", p->pid);
r_core_cmd0 (core, cmd);
}
r_core_cmdf (core, "dp %d", origpid);
r_list_free (list);
}
break;
case 'r':
// registers
{
ut64 offorig = core->offset;
for (i = 0; i < 128; i++) {
RRegItem *item;
ut64 value;
head = r_reg_get_list (dbg->reg, i);
if (!head) {
continue;
}
r_list_foreach (head, iter, item) {
if (item->size != core->anal->bits) {
continue;
}
value = r_reg_get_value (dbg->reg, item);
r_core_seek (core, value, 1);
r_cons_printf ("%s: ", item->name);
r_core_cmd0 (core, cmd);
}
}
r_core_seek (core, offorig, 1);
}
break;
case 'i': // @@@i
// imports
{
RBinImport *imp;
ut64 offorig = core->offset;
list = r_bin_get_imports (core->bin);
r_list_foreach (list, iter, imp) {
char *impflag = r_str_newf ("sym.imp.%s", imp->name);
ut64 addr = r_num_math (core->num, impflag);
free (impflag);
if (addr && addr != UT64_MAX) {
r_core_seek (core, addr, 1);
r_core_cmd0 (core, cmd);
}
}
r_core_seek (core, offorig, 1);
}
break;
case 'S': // "@@@S"
{
RBinObject *obj = r_bin_cur_object (core->bin);
if (obj) {
ut64 offorig = core->offset;
ut64 bszorig = core->blocksize;
RBinSection *sec;
RListIter *iter;
r_list_foreach (obj->sections, iter, sec) {
r_core_seek (core, sec->vaddr, 1);
r_core_block_size (core, sec->vsize);
r_core_cmd0 (core, cmd);
}
r_core_block_size (core, bszorig);
r_core_seek (core, offorig, 1);
}
}
#if ATTIC
if (each[1] == 'S') {
RListIter *it;
RBinSection *sec;
RBinObject *obj = r_bin_cur_object (core->bin);
int cbsz = core->blocksize;
r_list_foreach (obj->sections, it, sec){
ut64 addr = sec->vaddr;
ut64 size = sec->vsize;
// TODO:
//if (R_BIN_SCN_EXECUTABLE & sec->perm) {
// continue;
//}
r_core_seek_size (core, addr, size);
r_core_cmd (core, cmd, 0);
}
r_core_block_size (core, cbsz);
}
#endif
break;
case 's':
if (each[1] == 't') { // strings
list = r_bin_get_strings (core->bin);
RBinString *s;
if (list) {
ut64 offorig = core->offset;
ut64 obs = core->blocksize;
r_list_foreach (list, iter, s) {
r_core_block_size (core, s->size);
r_core_seek (core, s->vaddr, 1);
r_core_cmd0 (core, cmd);
}
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
} else {
// symbols
RBinSymbol *sym;
ut64 offorig = core->offset;
ut64 obs = core->blocksize;
list = r_bin_get_symbols (core->bin);
r_cons_break_push (NULL, NULL);
r_list_foreach (list, iter, sym) {
if (r_cons_is_breaked ()) {
break;
}
r_core_block_size (core, sym->size);
r_core_seek (core, sym->vaddr, 1);
r_core_cmd0 (core, cmd);
}
r_cons_break_pop ();
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
break;
case 'f': // flags
{
// TODO: honor ^C
char *glob = filter? r_str_trim_dup (filter): NULL;
ut64 off = core->offset;
ut64 obs = core->blocksize;
struct exec_command_t u = { .core = core, .cmd = cmd };
r_flag_foreach_glob (core->flags, glob, exec_command_on_flag, &u);
r_core_seek (core, off, 0);
r_core_block_size (core, obs);
free (glob);
}
break;
case 'F': // functions
{
ut64 obs = core->blocksize;
ut64 offorig = core->offset;
RAnalFunction *fcn;
list = core->anal->fcns;
r_cons_break_push (NULL, NULL);
r_list_foreach (list, iter, fcn) {
if (r_cons_is_breaked ()) {
break;
}
if (!filter || r_str_glob (fcn->name, filter)) {
r_core_seek (core, fcn->addr, 1);
r_core_block_size (core, r_anal_fcn_size (fcn));
r_core_cmd0 (core, cmd);
}
}
r_cons_break_pop ();
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
break;
case 'b':
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
ut64 offorig = core->offset;
ut64 obs = core->blocksize;
if (fcn) {
RListIter *iter;
RAnalBlock *bb;
r_list_foreach (fcn->bbs, iter, bb) {
r_core_seek (core, bb->addr, 1);
r_core_block_size (core, bb->size);
r_core_cmd0 (core, cmd);
}
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
}
break;
}
return 0;
}
static void foreachOffset(RCore *core, const char *_cmd, const char *each) {
char *cmd = strdup (_cmd);
char *nextLine = NULL;
ut64 addr;
/* foreach list of items */
while (each) {
// skip spaces
while (*each == ' ') {
each++;
}
// stahp if empty string
if (!*each) {
break;
}
// find newline
char *nl = strchr (each, '\n');
if (nl) {
*nl = 0;
nextLine = nl + 1;
} else {
nextLine = NULL;
}
// chop comment in line
nl = strchr (each, '#');
if (nl) {
*nl = 0;
}
// space separated numbers
while (each && *each) {
// find spaces
while (*each == ' ') {
each++;
}
char *str = strchr (each, ' ');
if (str) {
*str = '\0';
addr = r_num_math (core->num, each);
*str = ' ';
each = str + 1;
} else {
if (!*each) {
break;
}
addr = r_num_math (core->num, each);
each = NULL;
}
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd, 0);
r_cons_flush ();
}
each = nextLine;
}
free (cmd);
}
struct duplicate_flag_t {
RList *ret;
const char *word;
};
static bool duplicate_flag(RFlagItem *flag, void *u) {
struct duplicate_flag_t *user = (struct duplicate_flag_t *)u;
/* filter per flag spaces */
if (r_str_glob (flag->name, user->word)) {
RFlagItem *cloned_item = r_flag_item_clone (flag);
if (!cloned_item) {
return false;
}
r_list_append (user->ret, cloned_item);
}
return true;
}
R_API int r_core_cmd_foreach(RCore *core, const char *cmd, char *each) {
int i, j;
char ch;
char *word = NULL;
char *str, *ostr = NULL;
RListIter *iter;
RFlagItem *flag;
ut64 oseek, addr;
for (; *cmd == ' '; cmd++) {
;
}
oseek = core->offset;
ostr = str = strdup (each);
r_cons_break_push (NULL, NULL); //pop on return
switch (each[0]) {
case '/': // "@@/"
{
char *cmdhit = strdup (r_config_get (core->config, "cmd.hit"));
r_config_set (core->config, "cmd.hit", cmd);
r_core_cmd0 (core, each);
r_config_set (core->config, "cmd.hit", cmdhit);
free (cmdhit);
}
free (ostr);
return 0;
case '?': // "@@?"
r_core_cmd_help (core, help_msg_at_at);
break;
case 'b': // "@@b" - function basic blocks
{
RListIter *iter;
RAnalBlock *bb;
RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0);
int bs = core->blocksize;
if (fcn) {
r_list_sort (fcn->bbs, bb_cmp);
r_list_foreach (fcn->bbs, iter, bb) {
r_core_block_size (core, bb->size);
r_core_seek (core, bb->addr, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
}
r_core_block_size (core, bs);
goto out_finish;
}
break;
case 's': // "@@s" - sequence
{
char *str = each + 1;
if (*str == ':' || *str == ' ') {
str++;
}
int count = r_str_split (str, ' ');
if (count == 3) {
ut64 cur;
ut64 from = r_num_math (core->num, r_str_word_get0 (str, 0));
ut64 to = r_num_math (core->num, r_str_word_get0 (str, 1));
ut64 step = r_num_math (core->num, r_str_word_get0 (str, 2));
for (cur = from; cur < to; cur += step) {
(void)r_core_seek (core, cur, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
} else {
eprintf ("Usage: cmd @@s:from to step\n");
}
goto out_finish;
}
break;
case 'i': // "@@i" - function instructions
{
RListIter *iter;
RAnalBlock *bb;
int i;
RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0);
if (fcn) {
r_list_sort (fcn->bbs, bb_cmp);
r_list_foreach (fcn->bbs, iter, bb) {
for (i = 0; i < bb->op_pos_size; i++) {
ut64 addr = bb->addr + bb->op_pos[i];
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
}
}
goto out_finish;
}
break;
case 'f': // "@@f"
if (each[1] == ':') {
RAnalFunction *fcn;
RListIter *iter;
if (core->anal) {
r_list_foreach (core->anal->fcns, iter, fcn) {
if (each[2] && strstr (fcn->name, each + 2)) {
r_core_seek (core, fcn->addr, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
}
}
goto out_finish;
} else {
RAnalFunction *fcn;
RListIter *iter;
if (core->anal) {
RConsGrep grep = core->cons->context->grep;
r_list_foreach (core->anal->fcns, iter, fcn) {
char *buf;
r_core_seek (core, fcn->addr, 1);
r_cons_push ();
r_core_cmd (core, cmd, 0);
buf = (char *)r_cons_get_buffer ();
if (buf) {
buf = strdup (buf);
}
r_cons_pop ();
r_cons_strcat (buf);
free (buf);
if (r_cons_is_breaked ()) {
break;
}
}
core->cons->context->grep = grep;
}
goto out_finish;
}
break;
case 't': // "@@t"
{
RDebugPid *p;
int pid = core->dbg->pid;
if (core->dbg->h && core->dbg->h->pids) {
RList *list = core->dbg->h->pids (core->dbg, R_MAX (0, pid));
r_list_foreach (list, iter, p) {
r_cons_printf ("# PID %d\n", p->pid);
r_debug_select (core->dbg, p->pid, p->pid);
r_core_cmd (core, cmd, 0);
r_cons_newline ();
}
r_list_free (list);
}
r_debug_select (core->dbg, pid, pid);
goto out_finish;
}
break;
case 'c': // "@@c:"
if (each[1] == ':') {
char *arg = r_core_cmd_str (core, each + 2);
if (arg) {
foreachOffset (core, cmd, arg);
free (arg);
}
}
break;
case '=': // "@@="
foreachOffset (core, cmd, str + 1);
break;
case 'd': // "@@d"
if (each[1] == 'b' && each[2] == 't') {
ut64 oseek = core->offset;
RDebugFrame *frame;
RListIter *iter;
RList *list;
list = r_debug_frames (core->dbg, UT64_MAX);
i = 0;
r_list_foreach (list, iter, frame) {
switch (each[3]) {
case 'b':
r_core_seek (core, frame->bp, 1);
break;
case 's':
r_core_seek (core, frame->sp, 1);
break;
default:
case 'a':
r_core_seek (core, frame->addr, 1);
break;
}
r_core_cmd (core, cmd, 0);
r_cons_newline ();
i++;
}
r_core_seek (core, oseek, 0);
r_list_free (list);
} else {
eprintf("Invalid for-each statement. Use @@=dbt[abs]\n");
}
break;
case 'k': // "@@k"
/* foreach list of items */
{
char *out = sdb_querys (core->sdb, NULL, 0, str + ((str[1])? 2: 1));
if (out) {
each = out;
do {
while (*each == ' ') {
each++;
}
if (!*each) {
break;
}
str = strchr (each, ' ');
if (str) {
*str = '\0';
addr = r_num_math (core->num, each);
*str = ' ';
} else {
addr = r_num_math (core->num, each);
}
//eprintf ("; 0x%08"PFMT64x":\n", addr);
each = str + 1;
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd, 0);
r_cons_flush ();
} while (str != NULL);
free (out);
}
}
break;
case '.': // "@@."
if (each[1] == '(') {
char cmd2[1024];
// XXX what's this 999 ?
i = 0;
for (core->rcmd->macro.counter = 0; i < 999; core->rcmd->macro.counter++) {
if (r_cons_is_breaked ()) {
break;
}
r_cmd_macro_call (&core->rcmd->macro, each + 2);
if (!core->rcmd->macro.brk_value) {
break;
}
addr = core->rcmd->macro._brk_value;
sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr);
eprintf ("0x%08"PFMT64x" (%s)\n", addr, cmd2);
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd2, 0);
i++;
}
} else {
char buf[1024];
char cmd2[1024];
FILE *fd = r_sandbox_fopen (each + 1, "r");
if (fd) {
core->rcmd->macro.counter = 0;
while (!feof (fd)) {
buf[0] = '\0';
if (!fgets (buf, sizeof (buf), fd)) {
break;
}
addr = r_num_math (core->num, buf);
eprintf ("0x%08"PFMT64x": %s\n", addr, cmd);
sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr);
r_core_seek (core, addr, 1); // XXX
r_core_cmd (core, cmd2, 0);
core->rcmd->macro.counter++;
}
fclose (fd);
} else {
eprintf ("cannot open file '%s' to read offsets\n", each + 1);
}
}
break;
default:
core->rcmd->macro.counter = 0;
for (; *each == ' '; each++) {
;
}
i = 0;
while (str[i]) {
j = i;
for (; str[j] && str[j] == ' '; j++) {
; // skip spaces
}
for (i = j; str[i] && str[i] != ' '; i++) {
; // find EOS
}
ch = str[i];
str[i] = '\0';
word = strdup (str + j);
if (!word) {
break;
}
str[i] = ch;
{
const RSpace *flagspace = r_flag_space_cur (core->flags);
RList *match_flag_items = r_list_newf ((RListFree)r_flag_item_free);
if (!match_flag_items) {
break;
}
/* duplicate flags that match word, to be sure
the command is going to be executed on flags
values at the moment the command is called
(without side effects) */
struct duplicate_flag_t u = {
.ret = match_flag_items,
.word = word,
};
r_flag_foreach_space (core->flags, flagspace, duplicate_flag, &u);
/* for all flags that match */
r_list_foreach (match_flag_items, iter, flag) {
if (r_cons_is_breaked ()) {
break;
}
char *buf = NULL;
const char *tmp = NULL;
r_core_seek (core, flag->offset, 1);
r_cons_push ();
r_core_cmd (core, cmd, 0);
tmp = r_cons_get_buffer ();
buf = tmp? strdup (tmp): NULL;
r_cons_pop ();
r_cons_strcat (buf);
free (buf);
}
r_list_free (match_flag_items);
core->rcmd->macro.counter++ ;
R_FREE (word);
}
}
}
r_cons_break_pop ();
// XXX: use r_core_seek here
core->offset = oseek;
free (word);
free (ostr);
return true;
out_finish:
free (ostr);
r_cons_break_pop ();
return false;
}
R_API void run_pending_anal(RCore *core) {
// allow incall events in the run_pending step
core->ev->incall = false;
if (core && core->anal && core->anal->cmdtail) {
char *res = core->anal->cmdtail;
core->anal->cmdtail = NULL;
r_core_cmd_lines (core, res);
free (res);
}
}
R_API int r_core_cmd(RCore *core, const char *cstr, int log) {
char *cmd, *ocmd, *ptr, *rcmd;
int ret = false, i;
if (core->cmdfilter) {
const char *invalid_chars = ";|>`@";
for (i = 0; invalid_chars[i]; i++) {
if (strchr (cstr, invalid_chars[i])) {
ret = true;
goto beach;
}
}
if (strncmp (cstr, core->cmdfilter, strlen (core->cmdfilter))) {
ret = true;
goto beach;
}
}
if (core->cmdremote) {
if (*cstr != '=' && *cstr != 'q' && strncmp (cstr, "!=", 2)) {
char *res = r_io_system (core->io, cstr);
if (res) {
r_cons_printf ("%s\n", res);
free (res);
}
goto beach; // false
}
}
if (!cstr || (*cstr == '|' && cstr[1] != '?')) {
// raw comment syntax
goto beach; // false;
}
if (!strncmp (cstr, "/*", 2)) {
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
goto beach; // false
}
core->incomment = true;
} else if (!strncmp (cstr, "*/", 2)) {
core->incomment = false;
goto beach; // false
}
if (core->incomment) {
goto beach; // false
}
if (log && (*cstr && (*cstr != '.' || !strncmp (cstr, ".(", 2)))) {
free (core->lastcmd);
core->lastcmd = strdup (cstr);
}
ocmd = cmd = malloc (strlen (cstr) + 4096);
if (!ocmd) {
goto beach;
}
r_str_cpy (cmd, cstr);
if (log) {
r_line_hist_add (cstr);
}
if (core->cons->context->cmd_depth < 1) {
eprintf ("r_core_cmd: That was too deep (%s)...\n", cmd);
free (ocmd);
R_FREE (core->oobi);
core->oobi_len = 0;
goto beach;
}
core->cons->context->cmd_depth--;
for (rcmd = cmd;;) {
ptr = strchr (rcmd, '\n');
if (ptr) {
*ptr = '\0';
}
ret = r_core_cmd_subst (core, rcmd);
if (ret == -1) {
eprintf ("|ERROR| Invalid command '%s' (0x%02x)\n", rcmd, *rcmd);
break;
}
if (!ptr) {
break;
}
rcmd = ptr + 1;
}
/* run pending analysis commands */
run_pending_anal (core);
core->cons->context->cmd_depth++;
free (ocmd);
R_FREE (core->oobi);
core->oobi_len = 0;
return ret;
beach:
if (r_list_empty (core->tasks)) {
r_th_lock_leave (core->lock);
} else {
RListIter *iter;
RCoreTask *task;
r_list_foreach (core->tasks, iter, task) {
r_th_pause (task->thread, false);
}
}
/* run pending analysis commands */
run_pending_anal (core);
return ret;
}
R_API int r_core_cmd_lines(RCore *core, const char *lines) {
int r, ret = true;
char *nl, *data, *odata;
if (!lines || !*lines) {
return true;
}
data = odata = strdup (lines);
if (!odata) {
return false;
}
nl = strchr (odata, '\n');
if (nl) {
r_cons_break_push (NULL, NULL);
do {
if (r_cons_is_breaked ()) {
free (odata);
r_cons_break_pop ();
return ret;
}
*nl = '\0';
r = r_core_cmd (core, data, 0);
if (r < 0) { //== -1) {
data = nl + 1;
ret = -1; //r; //false;
break;
}
r_cons_flush ();
if (data[0] == 'q') {
if (data[1] == '!') {
ret = -1;
} else {
eprintf ("'q': quit ignored. Use 'q!'\n");
}
data = nl + 1;
break;
}
data = nl + 1;
} while ((nl = strchr (data, '\n')));
r_cons_break_pop ();
}
if (ret >= 0 && data && *data) {
r_core_cmd (core, data, 0);
}
free (odata);
return ret;
}
R_API int r_core_cmd_file(RCore *core, const char *file) {
char *data = r_file_abspath (file);
if (!data) {
return false;
}
char *odata = r_file_slurp (data, NULL);
free (data);
if (!odata) {
return false;
}
if (!r_core_cmd_lines (core, odata)) {
eprintf ("Failed to run script '%s'\n", file);
free (odata);
return false;
}
free (odata);
return true;
}
R_API int r_core_cmd_command(RCore *core, const char *command) {
int ret, len;
char *buf, *rcmd, *ptr;
char *cmd = r_core_sysenv_begin (core, command);
rcmd = ptr = buf = r_sys_cmd_str (cmd, 0, &len);
if (!buf) {
free (cmd);
return -1;
}
ret = r_core_cmd (core, rcmd, 0);
r_core_sysenv_end (core, command);
free (buf);
return ret;
}
//TODO: Fix disasm loop is mandatory
R_API char *r_core_disassemble_instr(RCore *core, ut64 addr, int l) {
char *cmd, *ret = NULL;
cmd = r_str_newf ("pd %i @ 0x%08"PFMT64x, l, addr);
if (cmd) {
ret = r_core_cmd_str (core, cmd);
free (cmd);
}
return ret;
}
R_API char *r_core_disassemble_bytes(RCore *core, ut64 addr, int b) {
char *cmd, *ret = NULL;
cmd = r_str_newf ("pD %i @ 0x%08"PFMT64x, b, addr);
if (cmd) {
ret = r_core_cmd_str (core, cmd);
free (cmd);
}
return ret;
}
R_API int r_core_cmd_buffer(RCore *core, const char *buf) {
char *ptr, *optr, *str = strdup (buf);
if (!str) {
return false;
}
optr = str;
ptr = strchr (str, '\n');
while (ptr) {
*ptr = '\0';
r_core_cmd (core, optr, 0);
optr = ptr + 1;
ptr = strchr (str, '\n');
}
r_core_cmd (core, optr, 0);
free (str);
return true;
}
R_API int r_core_cmdf(RCore *core, const char *fmt, ...) {
char string[4096];
int ret;
va_list ap;
va_start (ap, fmt);
vsnprintf (string, sizeof (string), fmt, ap);
ret = r_core_cmd (core, string, 0);
va_end (ap);
return ret;
}
R_API int r_core_cmd0(RCore *core, const char *cmd) {
return r_core_cmd (core, cmd, 0);
}
R_API int r_core_flush(RCore *core, const char *cmd) {
int ret = r_core_cmd (core, cmd, 0);
r_cons_flush ();
return ret;
}
R_API char *r_core_cmd_str_pipe(RCore *core, const char *cmd) {
char *s, *tmp = NULL;
if (r_sandbox_enable (0)) {
char *p = (*cmd != '"')? strchr (cmd, '|'): NULL;
if (p) {
// This code works but its pretty ugly as its a workaround to
// make the webserver work as expected, this was broken some
// weeks. let's use this hackaround for now
char *c = strdup (cmd);
c[p - cmd] = 0;
if (!strcmp (p + 1, "H")) {
char *res = r_core_cmd_str (core, c);
free (c);
char *hres = r_cons_html_filter (res, NULL);
free (res);
return hres;
} else {
int sh = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", 0);
char *ret = r_core_cmd_str (core, c);
r_config_set_i (core->config, "scr.color", sh);
free (c);
return ret;
}
}
return r_core_cmd_str (core, cmd);
}
r_cons_reset ();
r_sandbox_disable (1);
if (r_file_mkstemp ("cmd", &tmp) != -1) {
int pipefd = r_cons_pipe_open (tmp, 1, 0);
if (pipefd == -1) {
r_file_rm (tmp);
r_sandbox_disable (0);
free (tmp);
return r_core_cmd_str (core, cmd);
}
char *_cmd = strdup (cmd);
r_core_cmd_subst (core, _cmd);
r_cons_flush ();
r_cons_pipe_close (pipefd);
s = r_file_slurp (tmp, NULL);
if (s) {
r_file_rm (tmp);
r_sandbox_disable (0);
free (tmp);
free (_cmd);
return s;
}
eprintf ("slurp %s fails\n", tmp);
r_file_rm (tmp);
free (tmp);
free (_cmd);
r_sandbox_disable (0);
return r_core_cmd_str (core, cmd);
}
r_sandbox_disable (0);
return NULL;
}
R_API char *r_core_cmd_strf(RCore *core, const char *fmt, ...) {
char string[4096];
char *ret;
va_list ap;
va_start (ap, fmt);
vsnprintf (string, sizeof (string), fmt, ap);
ret = r_core_cmd_str (core, string);
va_end (ap);
return ret;
}
/* return: pointer to a buffer with the output of the command */
R_API char *r_core_cmd_str(RCore *core, const char *cmd) {
const char *static_str;
char *retstr = NULL;
r_cons_push ();
if (r_core_cmd (core, cmd, 0) == -1) {
//eprintf ("Invalid command: %s\n", cmd);
return NULL;
}
r_cons_filter ();
static_str = r_cons_get_buffer ();
retstr = strdup (static_str? static_str: "");
r_cons_pop ();
r_cons_echo (NULL);
return retstr;
}
R_API void r_core_cmd_repeat(RCore *core, int next) {
// Fix for backtickbug px`~`
if (!core->lastcmd || core->cons->context->cmd_depth < 1) {
return;
}
switch (*core->lastcmd) {
case '.':
if (core->lastcmd[1] == '(') { // macro call
r_core_cmd0 (core, core->lastcmd);
}
break;
case 'd': // debug
r_core_cmd0 (core, core->lastcmd);
switch (core->lastcmd[1]) {
case 's':
case 'c':
r_core_cmd0 (core, "sr PC;pd 1");
}
break;
case 'p': // print
case 'x':
case '$':
if (!strncmp (core->lastcmd, "pd", 2)) {
if (core->lastcmd[2]== ' ') {
r_core_cmdf (core, "so %s", core->lastcmd + 3);
} else {
r_core_cmd0 (core, "so `pi~?`");
}
} else {
if (next) {
r_core_seek (core, core->offset + core->blocksize, 1);
} else {
if (core->blocksize > core->offset) {
r_core_seek (core, 0, 1);
} else {
r_core_seek (core, core->offset - core->blocksize, 1);
}
}
}
r_core_cmd0 (core, core->lastcmd);
break;
}
}
/* run cmd in the main task synchronously */
R_API int r_core_cmd_task_sync(RCore *core, const char *cmd, bool log) {
RCoreTask *task = core->main_task;
char *s = strdup (cmd);
if (!s) {
return 0;
}
task->cmd = s;
task->cmd_log = log;
task->state = R_CORE_TASK_STATE_BEFORE_START;
int res = r_core_task_run_sync (core, task);
free (s);
return res;
}
static int cmd_ox(void *data, const char *input) {
return r_core_cmdf ((RCore*)data, "s 0%s", input);
}
static int compare_cmd_descriptor_name(const void *a, const void *b) {
return strcmp (((RCmdDescriptor *)a)->cmd, ((RCmdDescriptor *)b)->cmd);
}
static void cmd_descriptor_init(RCore *core) {
const ut8 *p;
RListIter *iter;
RCmdDescriptor *x, *y;
int n = core->cmd_descriptors->length;
r_list_sort (core->cmd_descriptors, compare_cmd_descriptor_name);
r_list_foreach (core->cmd_descriptors, iter, y) {
if (--n < 0) {
break;
}
x = &core->root_cmd_descriptor;
for (p = (const ut8 *)y->cmd; *p; p++) {
if (!x->sub[*p]) {
if (p[1]) {
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor);
r_list_append (core->cmd_descriptors, d);
x->sub[*p] = d;
} else {
x->sub[*p] = y;
}
} else if (!p[1]) {
eprintf ("Command '%s' is duplicated, please check\n", y->cmd);
}
x = x->sub[*p];
}
}
}
static int core_cmd0_wrapper(void *core, const char *cmd) {
return r_core_cmd0 ((RCore *)core, cmd);
}
R_API void r_core_cmd_init(RCore *core) {
struct {
const char *cmd;
const char *description;
r_cmd_callback (cb);
void (*descriptor_init)(RCore *core);
} cmds[] = {
{"!", "run system command", cmd_system},
{"_", "print last output", cmd_last},
{"#", "calculate hash", cmd_hash},
{"$", "alias", cmd_alias},
{"%", "short version of 'env' command", cmd_env},
{"&", "tasks", cmd_tasks},
{"(", "macro", cmd_macro, cmd_macro_init},
{"*", "pointer read/write", cmd_pointer},
{"-", "open cfg.editor and run script", cmd_stdin},
{".", "interpret", cmd_interpret},
{"/", "search kw, pattern aes", cmd_search, cmd_search_init},
{"=", "io pipe", cmd_rap},
{"?", "help message", cmd_help, cmd_help_init},
{"\\", "alias for =!", cmd_rap_run},
{"'", "alias for =!", cmd_rap_run},
{"0x", "alias for s 0x", cmd_ox},
{"analysis", "analysis", cmd_anal, cmd_anal_init},
{"bsize", "change block size", cmd_bsize},
{"cmp", "compare memory", cmd_cmp, cmd_cmp_init},
{"Code", "code metadata", cmd_meta, cmd_meta_init},
{"debug", "debugger operations", cmd_debug, cmd_debug_init},
{"eval", "evaluate configuration variable", cmd_eval, cmd_eval_init},
{"flag", "get/set flags", cmd_flag, cmd_flag_init},
{"g", "egg manipulation", cmd_egg, cmd_egg_init},
{"info", "get file info", cmd_info, cmd_info_init},
{"kuery", "perform sdb query", cmd_kuery},
{"l", "list files and directories", cmd_ls},
{"join", "join the contents of the two files", cmd_join},
{"head", "show the top n number of line in file", cmd_head},
{"L", "manage dynamically loaded plugins", cmd_plugins},
{"mount", "mount filesystem", cmd_mount, cmd_mount_init},
{"open", "open or map file", cmd_open, cmd_open_init},
{"print", "print current block", cmd_print, cmd_print_init},
{"Project", "project", cmd_project, cmd_project_init},
{"quit", "exit program session", cmd_quit, cmd_quit_init},
{"Q", "alias for q!", cmd_Quit},
{":", "long commands starting with :", cmd_colon},
{"resize", "change file size", cmd_resize},
{"seek", "seek to an offset", cmd_seek, cmd_seek_init},
{"t", "type information (cparse)", cmd_type, cmd_type_init},
{"Text", "Text log utility", cmd_log, cmd_log_init},
{"u", "uname/undo", cmd_uname},
{"<", "pipe into RCons.readChar", cmd_pipein},
{"Visual", "enter visual mode", cmd_visual},
{"visualPanels", "enter visual mode", cmd_panels},
{"write", "write bytes", cmd_write, cmd_write_init},
{"x", "alias for px", cmd_hexdump},
{"yank", "yank bytes", cmd_yank},
{"zign", "zignatures", cmd_zign, cmd_zign_init},
};
core->rcmd = r_cmd_new ();
core->rcmd->macro.user = core;
core->rcmd->macro.num = core->num;
core->rcmd->macro.cmd = core_cmd0_wrapper;
core->rcmd->nullcallback = r_core_cmd_nullcallback;
core->rcmd->macro.cb_printf = (PrintfCallback)r_cons_printf;
r_cmd_set_data (core->rcmd, core);
core->cmd_descriptors = r_list_newf (free);
int i;
for (i = 0; i < R_ARRAY_SIZE (cmds); i++) {
r_cmd_add (core->rcmd, cmds[i].cmd, cmds[i].description, cmds[i].cb);
if (cmds[i].descriptor_init) {
cmds[i].descriptor_init (core);
}
}
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, $, dollar);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, %, percent);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, *, star);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, ., dot);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, =, equal);
DEFINE_CMD_DESCRIPTOR (core, b);
DEFINE_CMD_DESCRIPTOR (core, k);
DEFINE_CMD_DESCRIPTOR (core, r);
DEFINE_CMD_DESCRIPTOR (core, u);
DEFINE_CMD_DESCRIPTOR (core, y);
cmd_descriptor_init (core);
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/good_1104_0 |
crossvul-cpp_data_bad_1104_0 | /* radare - LGPL - Copyright 2009-2019 - nibble, pancake */
#if 0
* Use RList
* Support callback for null command (why?)
* Show help of commands
- long commands not yet tested at all
- added interface to export command list into an autocompletable
argc, argv for dietline
* r_cmd must provide a nesting char table indexing for commands
- this is already partially done
- this is pretty similar to r_db
- every module can register their own commands
- commands can be listed like in a tree
#endif
#define INTERACTIVE_MAX_REP 1024
#include <r_core.h>
#include <r_anal.h>
#include <r_cons.h>
#include <r_cmd.h>
#include <stdint.h>
#include <sys/types.h>
#include <ctype.h>
#include <stdarg.h>
#if __UNIX__
#include <sys/utsname.h>
#endif
R_API void r_save_panels_layout(RCore *core, const char *_name);
R_API void r_load_panels_layout(RCore *core, const char *_name);
#define DEFINE_CMD_DESCRIPTOR(core, cmd_) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##cmd_; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
#define DEFINE_CMD_DESCRIPTOR_WITH_DETAIL(core, cmd_) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##cmd_; \
d->help_detail = help_detail_##cmd_; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
#define DEFINE_CMD_DESCRIPTOR_WITH_DETAIL2(core, cmd_) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##cmd_; \
d->help_detail = help_detail_##cmd_; \
d->help_detail2 = help_detail2_##cmd_; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
#define DEFINE_CMD_DESCRIPTOR_SPECIAL(core, cmd_, named_cmd) \
{ \
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor); \
if (d) { \
d->cmd = #cmd_; \
d->help_msg = help_msg_##named_cmd; \
r_list_append ((core)->cmd_descriptors, d); \
} \
}
static int r_core_cmd_subst_i(RCore *core, char *cmd, char* colon, bool *tmpseek);
static void cmd_debug_reg(RCore *core, const char *str);
#include "cmd_quit.c"
#include "cmd_hash.c"
#include "cmd_debug.c"
#include "cmd_log.c"
#include "cmd_flag.c"
#include "cmd_zign.c"
#include "cmd_project.c"
#include "cmd_write.c"
#include "cmd_cmp.c"
#include "cmd_eval.c"
#include "cmd_anal.c"
#include "cmd_open.c"
#include "cmd_meta.c"
#include "cmd_type.c"
#include "cmd_egg.c"
#include "cmd_info.c"
#include "cmd_macro.c"
#include "cmd_magic.c"
#include "cmd_mount.c"
#include "cmd_seek.c"
#include "cmd_search.c" // defines incDigitBuffer... used by cmd_print
#include "cmd_print.c"
#include "cmd_help.c"
#include "cmd_colon.c"
static const char *help_msg_dollar[] = {
"Usage:", "$alias[=cmd] [args...]", "Alias commands and strings (See ?$? for help on $variables)",
"$", "", "list all defined aliases",
"$*", "", "list all the aliases as r2 commands in base64",
"$**", "", "same as above, but using plain text",
"$", "dis=base64:AAA==", "alias this base64 encoded text to be printed when $dis is called",
"$", "dis=$hello world", "alias this text to be printed when $dis is called",
"$", "dis=-", "open cfg.editor to set the new value for dis alias",
"$", "dis=af;pdf", "create command - analyze to show function",
"$", "test=#!pipe node /tmp/test.js", "create command - rlangpipe script",
"$", "dis=", "undefine alias",
"$", "dis", "execute the previously defined alias",
"$", "dis?", "show commands aliased by $dis",
NULL
};
static const char *help_msg_star[] = {
"Usage:", "*<addr>[=[0x]value]", "Pointer read/write data/values",
"*", "entry0=cc", "write trap in entrypoint",
"*", "entry0+10=0x804800", "write value in delta address",
"*", "entry0", "read byte at given address",
"TODO: last command should honor asm.bits", "", "",
NULL
};
static const char *help_msg_dot[] = {
"Usage:", ".[r2cmd] | [file] | [!command] | [(macro)]", "# define macro or interpret r2, r_lang,\n"
" cparse, d, es6, exe, go, js, lsp, pl, py, rb, sh, vala or zig file",
".", "", "repeat last command backward",
".", "r2cmd", "interpret the output of the command as r2 commands",
"..", " [file]", "run the output of the execution of a script as r2 commands",
"...", "", "repeat last command forward (same as \\n)",
".:", "8080", "listen for commands on given tcp port",
".--", "", "terminate tcp server for remote commands",
".", " foo.r2", "interpret script",
".-", "", "open cfg.editor and interpret tmp file",
".*", " file ...", "same as #!pipe open cfg.editor and interpret tmp file",
".!", "rabin -ri $FILE", "interpret output of command",
".", "(foo 1 2 3)", "run macro 'foo' with args 1, 2, 3",
"./", " ELF", "interpret output of command /m ELF as r. commands",
NULL
};
static const char *help_msg_equal[] = {
"Usage:", " =[:!+-=ghH] [...]", " # connect with other instances of r2",
"\nremote commands:", "", "",
"=", "", "list all open connections",
"=<", "[fd] cmd", "send output of local command to remote fd", // XXX may not be a special char
"=", "[fd] cmd", "exec cmd at remote 'fd' (last open is default one)",
"=!", " cmd", "run command via r_io_system",
"=+", " [proto://]host:port", "connect to remote host:port (*rap://, raps://, tcp://, udp://, http://)",
"=-", "[fd]", "remove all hosts or host 'fd'",
"==", "[fd]", "open remote session with host 'fd', 'q' to quit",
"=!=", "", "disable remote cmd mode",
"!=!", "", "enable remote cmd mode",
"\nservers:","","",
".:", "9000", "start the tcp server (echo x|nc ::1 9090 or curl ::1:9090/cmd/x)",
"=:", "port", "start the rap server (o rap://9999)",
"=g", "[?]", "start the gdbserver",
"=h", "[?]", "start the http webserver",
"=H", "[?]", "start the http webserver (and launch the web browser)",
"\nother:","","",
"=&", ":port", "start rap server in background (same as '&_=h')",
"=", ":host:port cmd", "run 'cmd' command on remote server",
"\nexamples:","","",
"=+", "tcp://localhost:9090/", "connect to: r2 -c.:9090 ./bin",
// "=+", "udp://localhost:9090/", "connect to: r2 -c.:9090 ./bin",
"=+", "rap://localhost:9090/", "connect to: r2 rap://:9090",
"=+", "http://localhost:9090/cmd/", "connect to: r2 -c'=h 9090' bin",
"o ", "rap://:9090/", "start the rap server on tcp port 9090",
NULL
};
#if 0
static const char *help_msg_equalh[] = {
"Usage:", "=h[---*&] [port]", " # manage http connections",
"=h", " port", "listen for http connections (r2 -qc=H /bin/ls)",
"=h-", "", "stop background webserver",
"=h--", "", "stop foreground webserver",
"=h*", "", "restart current webserver",
"=h&", " port", "start http server in background",
NULL
};
#endif
static const char *help_msg_equalh[] = {
"Usage:", " =[hH] [...]", " # http server",
"http server:", "", "",
"=h", " port", "listen for http connections (r2 -qc=H /bin/ls)",
"=h-", "", "stop background webserver",
"=h--", "", "stop foreground webserver",
"=h*", "", "restart current webserver",
"=h&", " port", "start http server in background",
"=H", " port", "launch browser and listen for http",
"=H&", " port", "launch browser and listen for http in background",
NULL
};
static const char *help_msg_equalg[] = {
"Usage:", " =[g] [...]", " # gdb server",
"gdbserver:", "", "",
"=g", " port file [args]", "listen on 'port' debugging 'file' using gdbserver",
"=g!", " port file [args]", "same as above, but debug protocol messages (like gdbserver --remote-debug)",
NULL
};
static const char *help_msg_b[] = {
"Usage:", "b[f] [arg]\n", "Get/Set block size",
"b", " 33", "set block size to 33",
"b", " eip+4", "numeric argument can be an expression",
"b", "", "display current block size",
"b", "+3", "increase blocksize by 3",
"b", "-16", "decrease blocksize by 16",
"b*", "", "display current block size in r2 command",
"bf", " foo", "set block size to flag size",
"bj", "", "display block size information in JSON",
"bm", " 1M", "set max block size",
NULL
};
static const char *help_msg_k[] = {
"Usage:", "k[s] [key[=value]]", "Sdb Query",
"k", " anal/**", "list namespaces under anal",
"k", " anal/meta/*", "list kv from anal > meta namespaces",
"k", " anal/meta/meta.0x80404", "get value for meta.0x80404 key",
"k", " foo", "show value",
"k", " foo=bar", "set value",
"k", "", "list keys",
"kd", " [file.sdb] [ns]", "dump namespace to disk",
"kj", "", "List all namespaces and sdb databases in JSON format",
"ko", " [file.sdb] [ns]", "open file into namespace",
"ks", " [ns]", "enter the sdb query shell",
//"kl", " ha.sdb", "load keyvalue from ha.sdb",
//"ks", " ha.sdb", "save keyvalue to ha.sdb",
NULL,
};
static const char *help_msg_r[] = {
"Usage:", "r[+-][ size]", "Resize file",
"r", "", "display file size",
"r", " size", "expand or truncate file to given size",
"r-", "num", "remove num bytes, move following data down",
"r+", "num", "insert num bytes, move following data up",
"rm" ," [file]", "remove file",
"rh" ,"", "show size in human format",
"r2" ," [file]", "launch r2 (same for rax2, rasm2, ...)",
"reset" ,"", "reset console settings (clear --hard)",
NULL
};
static const char *help_msg_u[] = {
"Usage:", "u", "uname or undo write/seek",
"u", "", "show system uname",
"uw", "", "alias for wc (requires: e io.cache=true)",
"us", "", "alias for s- (seek history)",
"uc", "", "undo core commands (uc?, ucl, uc*, ..)",
NULL
};
static const char *help_msg_y[] = {
"Usage:", "y[ptxy] [len] [[@]addr]", " # See wd? for memcpy, same as 'yf'.",
"y!", "", "open cfg.editor to edit the clipboard",
"y", " 16 0x200", "copy 16 bytes into clipboard from 0x200",
"y", " 16 @ 0x200", "copy 16 bytes into clipboard from 0x200",
"y", " 16", "copy 16 bytes into clipboard",
"y", "", "show yank buffer information (srcoff len bytes)",
"y*", "", "print in r2 commands what's been yanked",
"yf", " 64 0x200", "copy file 64 bytes from 0x200 from file",
"yfa", " file copy", "copy all bytes from file (opens w/ io)",
"yfx", " 10203040", "yank from hexpairs (same as ywx)",
"yj", "", "print in JSON commands what's been yanked",
"yp", "", "print contents of clipboard",
"yq", "", "print contents of clipboard in hexpairs",
"ys", "", "print contents of clipboard as string",
"yt", " 64 0x200", "copy 64 bytes from current seek to 0x200",
"ytf", " file", "dump the clipboard to given file",
"yw", " hello world", "yank from string",
"ywx", " 10203040", "yank from hexpairs (same as yfx)",
"yx", "", "print contents of clipboard in hexadecimal",
"yy", " 0x3344", "paste clipboard",
"yz", " [len]", "copy nul-terminated string (up to blocksize) into clipboard",
NULL
};
static const char *help_msg_triple_exclamation[] = {
"Usage:", "!!![-*][cmd] [arg|$type...]", " # user-defined autocompletion for commands",
"!!!", "", "list all autocompletions",
"!!!?", "", "show this help",
"!!!", "-*", "remove all user-defined autocompletions",
"!!!", "-\\*", "remove autocompletions matching this glob expression",
"!!!", "-foo", "remove autocompletion named 'foo'",
"!!!", "foo", "add 'foo' for autocompletion",
"!!!", "bar $flag", "add 'bar' for autocompletion with $flag as argument",
NULL
};
static const char *help_msg_vertical_bar[] = {
"Usage:", "[cmd] | [program|H|T|.|]", "",
"", "[cmd] |?", "show this help",
"", "[cmd] |", "disable scr.html and scr.color",
"", "[cmd] |H", "enable scr.html, respect scr.color",
"", "[cmd] |T", "use scr.tts to speak out the stdout",
"", "[cmd] | [program]", "pipe output of command to program",
"", "[cmd] |.", "alias for .[cmd]",
NULL
};
R_API void r_core_cmd_help(const RCore *core, const char *help[]) {
r_cons_cmd_help (help, core->print->flags & R_PRINT_FLAGS_COLOR);
}
static void recursive_help_go(RCore *core, int detail, RCmdDescriptor *desc) {
int i;
if (desc->help_msg) {
r_core_cmd_help (core, desc->help_msg);
}
if (detail >= 1) {
if (desc->help_detail) {
r_core_cmd_help (core, desc->help_detail);
}
if (detail >= 2 && desc->help_detail2) {
r_core_cmd_help (core, desc->help_detail2);
}
}
for (i = 32; i < R_ARRAY_SIZE (desc->sub); i++) {
if (desc->sub[i]) {
recursive_help_go (core, detail, desc->sub[i]);
}
}
}
static void recursive_help(RCore *core, int detail, const char *cmd_prefix) {
const ut8 *p;
RCmdDescriptor *desc = &core->root_cmd_descriptor;
for (p = (const ut8 *)cmd_prefix; *p && *p < R_ARRAY_SIZE (desc->sub); p++) {
if (!(desc = desc->sub[*p])) {
return;
}
}
recursive_help_go (core, detail, desc);
}
static int r_core_cmd_nullcallback(void *data) {
RCore *core = (RCore*) data;
if (core->cons->context->breaked) {
core->cons->context->breaked = false;
return 0;
}
if (!core->cmdrepeat) {
return 0;
}
r_core_cmd_repeat (core, true);
return 1;
}
static int cmd_uniq(void *data, const char *input) { // "uniq"
RCore *core = (RCore *)data;
const char *arg = strchr (input, ' ');
if (arg) {
arg = r_str_trim_ro (arg + 1);
}
switch (*input) {
case '?': // "uniq?"
eprintf ("Usage: uniq # uniq to list unique strings in file\n");
break;
default: // "uniq"
if (!arg) {
arg = "";
}
if (r_fs_check (core->fs, arg)) {
r_core_cmdf (core, "md %s", arg);
} else {
char *res = r_syscmd_uniq (arg);
if (res) {
r_cons_print (res);
free (res);
}
}
break;
}
return 0;
}
static int cmd_head (void *data, const char *_input) { // "head"
RCore *core = (RCore *)data;
int lines = 5;
char *input = strdup (_input);
char *arg = strchr (input, ' ');
char *tmp, *count;
if (arg) {
arg = (char *)r_str_trim_ro (arg + 1); // contains "count filename"
count = strchr (arg, ' ');
if (count) {
*count = 0; // split the count and file name
tmp = (char *)r_str_trim_ro (count + 1);
lines = atoi (arg);
arg = tmp;
}
}
switch (*input) {
case '?': // "head?"
eprintf ("Usage: head [file] # to list first n lines in file\n");
break;
default: // "head"
if (!arg) {
arg = "";
}
if (r_fs_check (core->fs, arg)) {
r_core_cmdf (core, "md %s", arg);
} else {
char *res = r_syscmd_head (arg, lines);
if (res) {
r_cons_print (res);
free (res);
}
}
break;
}
free (input);
return 0;
}
static int cmd_uname(void *data, const char *input) {
RCore *core = (RCore *)data;
switch (input[0]) {
case '?': // "u?"
r_core_cmd_help (data, help_msg_u);
return 1;
case 'c': // "uc"
switch (input[1]) {
case ' ': {
char *cmd = strdup (input + 2);
char *rcmd = strchr (cmd, ',');
if (rcmd) {
*rcmd++ = 0;
RCoreUndo *undo = r_core_undo_new (core->offset, cmd, rcmd);
r_core_undo_push (core, undo);
} else {
eprintf ("Usage: uc [cmd] [revert-cmd]");
}
free (cmd);
}
break;
case '?':
eprintf ("Usage: uc [cmd],[revert-cmd]\n");
eprintf (" uc. - list all reverts in current\n");
eprintf (" uc* - list all core undos\n");
eprintf (" uc - list all core undos\n");
eprintf (" uc- - undo last action\n");
break;
case '.': {
RCoreUndoCondition cond = {
.addr = core->offset,
.minstamp = 0,
.glob = NULL
};
r_core_undo_print (core, 1, &cond);
} break;
case '*':
r_core_undo_print (core, 1, NULL);
break;
case '-': // "uc-"
r_core_undo_pop (core);
break;
default:
r_core_undo_print (core, 0, NULL);
break;
}
return 1;
case 's': // "us"
r_core_cmdf (data, "s-%s", input + 1);
return 1;
case 'w': // "uw"
r_core_cmdf (data, "wc%s", input + 1);
return 1;
case 'n': // "un"
if (input[1] == 'i' && input[2] == 'q') {
cmd_uniq (core, input);
}
return 1;
}
#if __UNIX__
struct utsname un;
uname (&un);
r_cons_printf ("%s %s %s %s\n", un.sysname,
un.nodename, un.release, un.machine);
#elif __WINDOWS__
r_cons_printf ("windows\n");
#else
r_cons_printf ("unknown\n");
#endif
return 0;
}
static int cmd_alias(void *data, const char *input) {
RCore *core = (RCore *)data;
if (*input == '?') {
r_core_cmd_help (core, help_msg_dollar);
return 0;
}
int i = strlen (input);
char *buf = malloc (i + 2);
if (!buf) {
return 0;
}
*buf = '$'; // prefix aliases with a dollar
memcpy (buf + 1, input, i + 1);
char *q = strchr (buf, ' ');
char *def = strchr (buf, '=');
char *desc = strchr (buf, '?');
/* create alias */
if ((def && q && (def < q)) || (def && !q)) {
*def++ = 0;
size_t len = strlen (def);
/* Remove quotes */
if (len > 0 && (def[0] == '\'') && (def[len - 1] == '\'')) {
def[len - 1] = 0x00;
def++;
}
if (!q || (q && q > def)) {
if (*def) {
if (!strcmp (def, "-")) {
char *v = r_cmd_alias_get (core->rcmd, buf, 0);
char *n = r_cons_editor (NULL, v);
if (n) {
r_cmd_alias_set (core->rcmd, buf, n, 0);
free (n);
}
} else {
r_cmd_alias_set (core->rcmd, buf, def, 0);
}
} else {
r_cmd_alias_del (core->rcmd, buf);
}
}
/* Show command for alias */
} else if (desc && !q) {
*desc = 0;
char *v = r_cmd_alias_get (core->rcmd, buf, 0);
if (v) {
r_cons_println (v);
free (buf);
return 1;
} else {
eprintf ("unknown key '%s'\n", buf);
}
} else if (buf[1] == '*') {
/* Show aliases */
int i, count = 0;
char **keys = r_cmd_alias_keys (core->rcmd, &count);
for (i = 0; i < count; i++) {
char *v = r_cmd_alias_get (core->rcmd, keys[i], 0);
char *q = r_base64_encode_dyn (v, -1);
if (buf[2] == '*') {
r_cons_printf ("%s=%s\n", keys[i], v);
} else {
r_cons_printf ("%s=base64:%s\n", keys[i], q);
}
free (q);
}
} else if (!buf[1]) {
int i, count = 0;
char **keys = r_cmd_alias_keys (core->rcmd, &count);
for (i = 0; i < count; i++) {
r_cons_println (keys[i]);
}
} else {
/* Execute alias */
if (q) {
*q = 0;
}
char *v = r_cmd_alias_get (core->rcmd, buf, 0);
if (v) {
if (*v == '$') {
r_cons_strcat (v + 1);
r_cons_newline ();
} else if (q) {
char *out = r_str_newf ("%s %s", v, q + 1);
r_core_cmd0 (core, out);
free (out);
} else {
r_core_cmd0 (core, v);
}
} else {
eprintf ("unknown key '%s'\n", buf);
}
}
free (buf);
return 0;
}
static int getArg(char ch, int def) {
switch (ch) {
case '&':
case '-':
return ch;
}
return def;
}
// wtf dupe for local vs remote?
static void aliascmd(RCore *core, const char *str) {
switch (str[0]) {
case '\0': // "=$"
r_core_cmd0 (core, "$");
break;
case '-': // "=$-"
if (str[1]) {
r_cmd_alias_del (core->rcmd, str + 2);
} else {
r_cmd_alias_del (core->rcmd, NULL);
// r_cmd_alias_reset (core->rcmd);
}
break;
case '?': // "=$?"
eprintf ("Usage: =$[-][remotecmd] # remote command alias\n");
eprintf (" =$dr # makes 'dr' alias for =!dr\n");
eprintf (" =$-dr # unset 'dr' alias\n");
break;
default:
r_cmd_alias_set (core->rcmd, str, "", 1);
break;
}
}
static int cmd_rap(void *data, const char *input) {
RCore *core = (RCore *)data;
switch (*input) {
case '\0': // "="
r_core_rtr_list (core);
break;
case 'j': // "=j"
eprintf ("TODO: list connections in json\n");
break;
case '!': // "=!"
if (input[1] == '=') {
// swap core->cmdremote = core->cmdremote? 0: 1;
core->cmdremote = input[2]? 1: 0;
r_cons_println (r_str_bool (core->cmdremote));
} else {
char *res = r_io_system (core->io, input + 1);
if (res) {
r_cons_printf ("%s\n", res);
free (res);
}
}
break;
case '$': // "=$"
// XXX deprecate?
aliascmd (core, input + 1);
break;
case '+': // "=+"
r_core_rtr_add (core, input + 1);
break;
case '-': // "=-"
r_core_rtr_remove (core, input + 1);
break;
//case ':': r_core_rtr_cmds (core, input + 1); break;
case '<': // "=<"
r_core_rtr_pushout (core, input + 1);
break;
case '=': // "=="
r_core_rtr_session (core, input + 1);
break;
case 'g': // "=g"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_equalg);
} else {
r_core_rtr_gdb (core, getArg (input[1], 'g'), input + 1);
}
break;
case 'h': // "=h"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_equalh);
} else {
r_core_rtr_http (core, getArg (input[1], 'h'), 'h', input + 1);
}
break;
case 'H': // "=H"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_equalh);
} else {
const char *arg = r_str_trim_ro (input + 1);
r_core_rtr_http (core, getArg (input[1], 'H'), 'H', arg);
}
break;
case '?': // "=?"
r_core_cmd_help (core, help_msg_equal);
break;
default:
r_core_rtr_cmd (core, input);
break;
}
return 0;
}
static int cmd_rap_run(void *data, const char *input) {
RCore *core = (RCore *)data;
char *res = r_io_system (core->io, input);
if (res) {
int ret = atoi (res);
free (res);
return ret;
}
return false;
}
static int cmd_yank(void *data, const char *input) {
ut64 n;
RCore *core = (RCore *)data;
switch (input[0]) {
case ' ': // "y "
r_core_yank (core, core->offset, r_num_math (core->num, input + 1));
break;
case 'l': // "yl"
core->num->value = r_buf_size (core->yank_buf);
break;
case 'y': // "yy"
while (input[1] == ' ') {
input++;
}
n = input[1]? r_num_math (core->num, input + 1): core->offset;
r_core_yank_paste (core, n, 0);
break;
case 'x': // "yx"
r_core_yank_hexdump (core, r_num_math (core->num, input + 1));
break;
case 'z': // "yz"
r_core_yank_string (core, core->offset, r_num_math (core->num, input + 1));
break;
case 'w': // "yw" ... we have yf which makes more sense than 'w'
switch (input[1]) {
case ' ':
r_core_yank_set (core, 0, (const ut8*)input + 2, strlen (input + 2));
break;
case 'x':
if (input[2] == ' ') {
char *out = strdup (input + 3);
int len = r_hex_str2bin (input + 3, (ut8*)out);
if (len > 0) {
r_core_yank_set (core, core->offset, (const ut8*)out, len);
} else {
eprintf ("Invalid length\n");
}
free (out);
} else {
eprintf ("Usage: ywx [hexpairs]\n");
}
// r_core_yank_write_hex (core, input + 2);
break;
default:
eprintf ("Usage: ywx [hexpairs]\n");
break;
}
break;
case 'p': // "yp"
r_core_yank_cat (core, r_num_math (core->num, input + 1));
break;
case 's': // "ys"
r_core_yank_cat_string (core, r_num_math (core->num, input + 1));
break;
case 't': // "wt"
if (input[1] == 'f') { // "wtf"
ut64 tmpsz;
const char *file = r_str_trim_ro (input + 2);
const ut8 *tmp = r_buf_data (core->yank_buf, &tmpsz);
if (!r_file_dump (file, tmp, tmpsz, false)) {
eprintf ("Cannot dump to '%s'\n", file);
}
} else if (input[1] == ' ') {
r_core_yank_to (core, input + 1);
} else {
eprintf ("Usage: wt[f] [arg] ..\n");
}
break;
case 'f': // "yf"
switch (input[1]) {
case ' ': // "yf"
r_core_yank_file_ex (core, input + 1);
break;
case 'x': // "yfx"
r_core_yank_hexpair (core, input + 2);
break;
case 'a': // "yfa"
r_core_yank_file_all (core, input + 2);
break;
default:
eprintf ("Usage: yf[xa] [arg]\n");
eprintf ("yf [file] - copy blocksize from file into the clipboard\n");
eprintf ("yfa [path] - yank the whole file\n");
eprintf ("yfx [hexpair] - yank from hexpair string\n");
break;
}
break;
case '!': // "y!"
{
char *sig = r_core_cmd_str (core, "y*");
if (!sig || !*sig) {
free (sig);
sig = strdup ("wx 10203040");
}
char *data = r_core_editor (core, NULL, sig);
(void) strtok (data, ";\n");
r_core_cmdf (core, "y%s", data);
free (sig);
free (data);
}
break;
case '*': // "y*"
case 'j': // "yj"
case 'q': // "yq"
case '\0': // "y"
r_core_yank_dump (core, 0, input[0]);
break;
default:
r_core_cmd_help (core, help_msg_y);
break;
}
return true;
}
static int lang_run_file(RCore *core, RLang *lang, const char *file) {
r_core_sysenv_begin (core, NULL);
return r_lang_run_file (core->lang, file);
}
static char *langFromHashbang(RCore *core, const char *file) {
int fd = r_sandbox_open (file, O_RDONLY, 0);
if (fd != -1) {
char firstLine[128] = {0};
int len = r_sandbox_read (fd, (ut8*)firstLine, sizeof (firstLine) - 1);
firstLine[len] = 0;
if (!strncmp (firstLine, "#!/", 3)) {
// I CAN HAS A HASHBANG
char *nl = strchr (firstLine, '\n');
if (nl) {
*nl = 0;
}
nl = strchr (firstLine, ' ');
if (nl) {
*nl = 0;
}
return strdup (firstLine + 2);
}
r_sandbox_close (fd);
}
return NULL;
}
R_API bool r_core_run_script(RCore *core, const char *file) {
bool ret = false;
RListIter *iter;
RLangPlugin *p;
char *name;
r_list_foreach (core->scriptstack, iter, name) {
if (!strcmp (file, name)) {
eprintf ("WARNING: ignored nested source: %s\n", file);
return false;
}
}
r_list_push (core->scriptstack, strdup (file));
if (!strcmp (file, "-")) {
char *out = r_core_editor (core, NULL, NULL);
if (out) {
ret = r_core_cmd_lines (core, out);
free (out);
}
} else if (r_str_endswith (file, ".html")) {
const bool httpSandbox = r_config_get_i (core->config, "http.sandbox");
char *httpIndex = strdup (r_config_get (core->config, "http.index"));
r_config_set_i (core->config, "http.sandbox", 0);
char *absfile = r_file_abspath (file);
r_config_set (core->config, "http.index", absfile);
free (absfile);
r_core_cmdf (core, "=H");
r_config_set_i (core->config, "http.sandbox", httpSandbox);
r_config_set (core->config, "http.index", httpIndex);
free (httpIndex);
ret = true;
} else if (r_str_endswith (file, ".c")) {
r_core_cmd_strf (core, "#!c %s", file);
ret = true;
} else if (r_file_is_c (file)) {
const char *dir = r_config_get (core->config, "dir.types");
char *out = r_parse_c_file (core->anal, file, dir, NULL);
if (out) {
r_cons_strcat (out);
sdb_query_lines (core->anal->sdb_types, out);
free (out);
}
ret = out? true: false;
} else {
p = r_lang_get_by_extension (core->lang, file);
if (p) {
r_lang_use (core->lang, p->name);
ret = lang_run_file (core, core->lang, file);
} else {
// XXX this is an ugly hack, we need to use execve here and specify args properly
#if __WINDOWS__
#define cmdstr(x) r_str_newf (x" %s", file);
#else
#define cmdstr(x) r_str_newf (x" '%s'", file);
#endif
const char *p = r_str_lchr (file, '.');
if (p) {
const char *ext = p + 1;
/* TODO: handle this inside r_lang_pipe with new APIs */
if (!strcmp (ext, "js")) {
char *cmd = cmdstr ("node");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "exe")) {
#if __WINDOWS__
char *cmd = r_str_newf ("%s", file);
#else
char *cmd = cmdstr ("wine");
#endif
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "zig")) {
char *cmd = cmdstr ("zig run");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "d")) {
char *cmd = cmdstr ("dmd -run");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "lsp")) {
char *cmd = cmdstr ("newlisp -n");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "go")) {
char *cmd = cmdstr ("go run");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "es6")) {
char *cmd = cmdstr ("babel-node");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "rb")) {
char *cmd = cmdstr ("ruby");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "vala")) {
r_lang_use (core->lang, "vala");
lang_run_file (core, core->lang, file);
ret = 1;
} else if (!strcmp (ext, "sh")) {
char *shell = r_sys_getenv ("SHELL");
if (!shell) {
shell = strdup ("sh");
}
if (shell) {
r_lang_use (core->lang, "pipe");
char *cmd = r_str_newf ("%s '%s'", shell, file);
if (cmd) {
lang_run_file (core, core->lang, cmd);
free (cmd);
}
free (shell);
}
ret = 1;
} else if (!strcmp (ext, "pl")) {
char *cmd = cmdstr ("perl");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
} else if (!strcmp (ext, "py")) {
char *cmd = cmdstr ("python");
r_lang_use (core->lang, "pipe");
lang_run_file (core, core->lang, cmd);
free (cmd);
ret = 1;
}
} else {
char *abspath = r_file_path (file);
char *lang = langFromHashbang (core, file);
if (lang) {
r_lang_use (core->lang, "pipe");
char *cmd = r_str_newf ("%s '%s'", lang, file);
lang_run_file (core, core->lang, cmd);
free (lang);
free (cmd);
ret = 1;
}
free (abspath);
}
if (!ret) {
ret = r_core_cmd_file (core, file);
}
}
}
free (r_list_pop (core->scriptstack));
return ret;
}
static int cmd_ls(void *data, const char *input) { // "ls"
RCore *core = (RCore *)data;
const char *arg = strchr (input, ' ');
if (arg) {
arg = r_str_trim_ro (arg + 1);
}
switch (*input) {
case '?': // "l?"
eprintf ("Usage: l[es] # ls to list files, le[ss] to less a file\n");
break;
case 'e': // "le"
if (arg) {
r_core_cmdf (core, "cat %s~..", arg);
} else {
eprintf ("Usage: less [file]\n");
}
break;
default: // "ls"
if (!arg) {
arg = "";
}
if (r_fs_check (core->fs, arg)) {
r_core_cmdf (core, "md %s", arg);
} else {
char *res = r_syscmd_ls (arg);
if (res) {
r_cons_print (res);
free (res);
}
}
break;
}
return 0;
}
static int cmd_join(void *data, const char *input) { // "join"
RCore *core = (RCore *)data;
const char *tmp = strdup (input);
const char *arg1 = strchr (tmp, ' ');
if (!arg1) {
goto beach;
}
arg1 = r_str_trim_ro (arg1);
char *end = strchr (arg1, ' ');
if (!end) {
goto beach;
}
*end = '\0';
const char *arg2 = end+1;
if (!arg2) {
goto beach;
}
arg2 = r_str_trim_ro (arg2);
switch (*input) {
case '?': // "join?"
goto beach;
default: // "join"
if (!arg1) {
arg1 = "";
}
if (!arg2) {
arg2 = "";
}
if (!r_fs_check (core->fs, arg1) && !r_fs_check (core->fs, arg2)) {
char *res = r_syscmd_join (arg1, arg2);
if (res) {
r_cons_print (res);
free (res);
}
R_FREE (tmp);
}
break;
}
return 0;
beach:
eprintf ("Usage: join [file1] [file2] # join the contents of the two files\n");
return 0;
}
static int cmd_stdin(void *data, const char *input) {
RCore *core = (RCore *)data;
if (input[0] == '?') {
r_cons_printf ("Usage: '-' '.-' '. -' do the same\n");
return false;
}
return r_core_run_script (core, "-");
}
static int cmd_interpret(void *data, const char *input) {
char *str, *ptr, *eol, *rbuf, *filter, *inp;
const char *host, *port, *cmd;
RCore *core = (RCore *)data;
switch (*input) {
case '\0': // "."
r_core_cmd_repeat (core, 0);
break;
case ':': // ".:"
if ((ptr = strchr (input + 1, ' '))) {
/* .:port cmd */
/* .:host:port cmd */
cmd = ptr + 1;
*ptr = 0;
eol = strchr (input + 1, ':');
if (eol) {
*eol = 0;
host = input + 1;
port = eol + 1;
} else {
host = "localhost";
port = input + ((input[1] == ':')? 2: 1);
}
rbuf = r_core_rtr_cmds_query (core, host, port, cmd);
if (rbuf) {
r_cons_print (rbuf);
free (rbuf);
}
} else {
r_core_rtr_cmds (core, input + 1);
}
break;
case '.': // ".." same as \n
if (input[1] == '.') { // "..." run the last command repeated
// same as \n with e cmd.repeat=true
r_core_cmd_repeat (core, 1);
} else if (input[1]) {
char *str = r_core_cmd_str_pipe (core, r_str_trim_ro (input));
if (str) {
r_core_cmd (core, str, 0);
free (str);
}
} else {
eprintf ("Usage: .. ([file])\n");
}
break;
case '*': // ".*"
{
const char *a = r_str_trim_ro (input + 1);
char *s = strdup (a);
char *sp = strchr (s, ' ');
if (sp) {
*sp = 0;
}
if (R_STR_ISNOTEMPTY (s)) {
r_core_run_script (core, s);
}
free (s);
}
break;
case '-': // ".-"
if (input[1] == '?') {
r_cons_printf ("Usage: '-' '.-' '. -' do the same\n");
} else {
r_core_run_script (core, "-");
}
break;
case ' ': // ". "
{
const char *script_file = r_str_trim_ro (input + 1);
if (*script_file == '$') {
r_core_cmd0 (core, script_file);
} else {
if (!r_core_run_script (core, script_file)) {
eprintf ("Cannot find script '%s'\n", script_file);
core->num->value = 1;
} else {
core->num->value = 0;
}
}
}
break;
case '!': // ".!"
/* from command */
r_core_cmd_command (core, input + 1);
break;
case '(': // ".("
r_cmd_macro_call (&core->rcmd->macro, input + 1);
break;
case '?': // ".?"
r_core_cmd_help (core, help_msg_dot);
break;
default:
if (*input >= 0 && *input <= 9) {
eprintf ("|ERROR| No .[0..9] to avoid infinite loops\n");
break;
}
inp = strdup (input);
filter = strchr (inp, '~');
if (filter) {
*filter = 0;
}
int tmp_html = r_cons_singleton ()->is_html;
r_cons_singleton ()->is_html = 0;
ptr = str = r_core_cmd_str (core, inp);
r_cons_singleton ()->is_html = tmp_html;
if (filter) {
*filter = '~';
}
r_cons_break_push (NULL, NULL);
if (ptr) {
for (;;) {
if (r_cons_is_breaked ()) {
break;
}
eol = strchr (ptr, '\n');
if (eol) {
*eol = '\0';
}
if (*ptr) {
char *p = r_str_append (strdup (ptr), filter);
r_core_cmd0 (core, p);
free (p);
}
if (!eol) {
break;
}
ptr = eol + 1;
}
}
r_cons_break_pop ();
free (str);
free (inp);
break;
}
return 0;
}
static int callback_foreach_kv(void *user, const char *k, const char *v) {
r_cons_printf ("%s=%s\n", k, v);
return 1;
}
R_API int r_line_hist_sdb_up(RLine *line) {
if (!line->sdbshell_hist_iter || !line->sdbshell_hist_iter->n) {
return false;
}
line->sdbshell_hist_iter = line->sdbshell_hist_iter->n;
strncpy (line->buffer.data, line->sdbshell_hist_iter->data, R_LINE_BUFSIZE - 1);
line->buffer.index = line->buffer.length = strlen (line->buffer.data);
return true;
}
R_API int r_line_hist_sdb_down(RLine *line) {
if (!line->sdbshell_hist_iter || !line->sdbshell_hist_iter->p) {
return false;
}
line->sdbshell_hist_iter = line->sdbshell_hist_iter->p;
strncpy (line->buffer.data, line->sdbshell_hist_iter->data, R_LINE_BUFSIZE - 1);
line->buffer.index = line->buffer.length = strlen (line->buffer.data);
return true;
}
static int cmd_kuery(void *data, const char *input) {
char buf[1024], *out;
RCore *core = (RCore*)data;
const char *sp, *p = "[sdb]> ";
const int buflen = sizeof (buf) - 1;
Sdb *s = core->sdb;
char *cur_pos, *cur_cmd, *next_cmd = NULL;
char *temp_pos, *temp_cmd, *temp_storage = NULL;
switch (input[0]) {
case 'j':
out = sdb_querys (s, NULL, 0, "anal/**");
if (!out) {
r_cons_println ("No Output from sdb");
break;
}
r_cons_printf ("{\"anal\":{");
while (*out) {
cur_pos = strchr (out, '\n');
if (!cur_pos) {
break;
}
cur_cmd = r_str_ndup (out, cur_pos - out);
r_cons_printf ("\n\n\"%s\" : [", cur_cmd);
next_cmd = r_str_newf ("anal/%s/*", cur_cmd);
temp_storage = sdb_querys (s, NULL, 0, next_cmd);
if (!temp_storage) {
r_cons_println ("\nEMPTY\n");
r_cons_printf ("],\n\n");
out += cur_pos - out + 1;
continue;
}
while (*temp_storage) {
temp_pos = strchr (temp_storage, '\n');
if (!temp_pos) {
break;
}
temp_cmd = r_str_ndup (temp_storage, temp_pos - temp_storage);
r_cons_printf ("\"%s\",", temp_cmd);
temp_storage += temp_pos - temp_storage + 1;
}
r_cons_printf ("],\n\n");
out += cur_pos - out + 1;
}
r_cons_printf ("}}");
free (next_cmd);
free (temp_storage);
break;
case ' ':
out = sdb_querys (s, NULL, 0, input + 1);
if (out) {
r_cons_println (out);
}
free (out);
break;
//case 's': r_pair_save (s, input + 3); break;
//case 'l': r_pair_load (sdb, input + 3); break;
case '\0':
sdb_foreach (s, callback_foreach_kv, NULL);
break;
// TODO: add command to list all namespaces // sdb_ns_foreach ?
case 's': // "ks"
if (core->http_up) {
return false;
}
if (!r_cons_is_interactive ()) {
return false;
}
if (input[1] == ' ') {
char *n, *o, *p = strdup (input + 2);
// TODO: slash split here? or inside sdb_ns ?
for (n = o = p; n; o = n) {
n = strchr (o, '/'); // SDB_NS_SEPARATOR NAMESPACE
if (n) {
*n++ = 0;
}
s = sdb_ns (s, o, 1);
}
free (p);
}
if (!s) {
s = core->sdb;
}
RLine *line = core->cons->line;
if (!line->sdbshell_hist) {
line->sdbshell_hist = r_list_newf (free);
r_list_append (line->sdbshell_hist, r_str_new ("\0"));
}
RList *sdb_hist = line->sdbshell_hist;
r_line_set_hist_callback (line, &r_line_hist_sdb_up, &r_line_hist_sdb_down);
for (;;) {
r_line_set_prompt (p);
if (r_cons_fgets (buf, buflen, 0, NULL) < 1) {
break;
}
if (!*buf) {
break;
}
if (sdb_hist) {
if ((r_list_length (sdb_hist) == 1) || (r_list_length (sdb_hist) > 1 && strcmp (r_list_get_n (sdb_hist, 1), buf))) {
r_list_insert (sdb_hist, 1, strdup (buf));
}
line->sdbshell_hist_iter = sdb_hist->head;
}
out = sdb_querys (s, NULL, 0, buf);
if (out) {
r_cons_println (out);
r_cons_flush ();
}
}
r_line_set_hist_callback (core->cons->line, &r_line_hist_cmd_up, &r_line_hist_cmd_down);
break;
case 'o':
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1] == ' ') {
char *fn = strdup (input + 2);
if (!fn) {
eprintf("Unable to allocate memory\n");
return 0;
}
char *ns = strchr (fn, ' ');
if (ns) {
Sdb *db;
*ns++ = 0;
if (r_file_exists (fn)) {
db = sdb_ns_path (core->sdb, ns, 1);
if (db) {
Sdb *newdb = sdb_new (NULL, fn, 0);
if (newdb) {
sdb_drain (db, newdb);
} else {
eprintf ("Cannot open sdb '%s'\n", fn);
}
} else {
eprintf ("Cannot find sdb '%s'\n", ns);
}
} else {
eprintf ("Cannot open file\n");
}
} else {
eprintf ("Missing sdb namespace\n");
}
free (fn);
} else {
eprintf ("Usage: ko [file] [namespace]\n");
}
break;
case 'd':
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1] == ' ') {
char *fn = strdup (input + 2);
char *ns = strchr (fn, ' ');
if (ns) {
*ns++ = 0;
Sdb *db = sdb_ns_path (core->sdb, ns, 0);
if (db) {
sdb_file (db, fn);
sdb_sync (db);
} else {
eprintf ("Cannot find sdb '%s'\n", ns);
}
} else {
eprintf ("Missing sdb namespace\n");
}
free (fn);
} else {
eprintf ("Usage: kd [file] [namespace]\n");
}
break;
case '?':
r_core_cmd_help (core, help_msg_k);
break;
}
if (input[0] == '\0') {
/* nothing more to do, the command has been parsed. */
return 0;
}
sp = strchr (input + 1, ' ');
if (sp) {
char *inp = strdup (input);
inp [(size_t)(sp - input)] = 0;
s = sdb_ns (core->sdb, inp + 1, 1);
out = sdb_querys (s, NULL, 0, sp + 1);
if (out) {
r_cons_println (out);
free (out);
}
free (inp);
return 0;
}
return 0;
}
static int cmd_bsize(void *data, const char *input) {
ut64 n;
RFlagItem *flag;
RCore *core = (RCore *)data;
switch (input[0]) {
case 'm': // "bm"
n = r_num_math (core->num, input + 1);
if (n > 1) {
core->blocksize_max = n;
} else {
r_cons_printf ("0x%x\n", (ut32)core->blocksize_max);
}
break;
case '+': // "b+"
n = r_num_math (core->num, input + 1);
r_core_block_size (core, core->blocksize + n);
break;
case '-': // "b-"
n = r_num_math (core->num, input + 1);
r_core_block_size (core, core->blocksize - n);
break;
case 'f': // "bf"
if (input[1] == ' ') {
flag = r_flag_get (core->flags, input + 2);
if (flag) {
r_core_block_size (core, flag->size);
} else {
eprintf ("bf: cannot find flag named '%s'\n", input + 2);
}
} else {
eprintf ("Usage: bf [flagname]\n");
}
break;
case 'j': // "bj"
r_cons_printf ("{\"blocksize\":%d,\"blocksize_limit\":%d}\n", core->blocksize, core->blocksize_max);
break;
case '*': // "b*"
r_cons_printf ("b 0x%x\n", core->blocksize);
break;
case '\0': // "b"
r_cons_printf ("0x%x\n", core->blocksize);
break;
case ' ':
r_core_block_size (core, r_num_math (core->num, input));
break;
default:
case '?': // "b?"
r_core_cmd_help (core, help_msg_b);
break;
}
return 0;
}
static int __runMain(RMainCallback cb, const char *arg) {
char *a = r_str_trim_dup (arg);
int argc = 0;
char **args = r_str_argv (a, &argc);
int res = cb (argc, args);
free (args);
free (a);
return res;
}
static bool cmd_r2cmd(RCore *core, const char *_input) {
char *input = r_str_newf ("r%s", _input);
int rc = 0;
if (r_str_startswith (input, "rax2")) {
rc = __runMain (core->r_main_rax2, input);
} else if (r_str_startswith (input, "radare2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_radare2, input);
} else if (r_str_startswith (input, "rasm2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_rasm2, input);
} else if (r_str_startswith (input, "rabin2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_rabin2, input);
} else if (r_str_startswith (input, "ragg2")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_ragg2, input);
} else if (r_str_startswith (input, "r2pm")) {
r_sys_cmdf ("%s", input);
// rc = __runMain (core->r_main_r2pm, input);
} else if (r_str_startswith (input, "radiff2")) {
rc = __runMain (core->r_main_radiff2, input);
} else {
const char *r2cmds[] = {
"rax2", "r2pm", "rasm2", "rabin2", "rahash2", "rafind2", "rarun2", "ragg2", "radare2", "r2", NULL
};
int i;
for (i = 0; r2cmds[i]; i++) {
if (r_str_startswith (input, r2cmds[i])) {
free (input);
return true;
}
}
return false;
}
free (input);
core->num->value = rc;
return true;
}
static int cmd_resize(void *data, const char *input) {
RCore *core = (RCore *)data;
ut64 newsize = 0;
st64 delta = 0;
int grow, ret;
if (cmd_r2cmd (core, input)) {
return true;
}
ut64 oldsize = (core->file) ? r_io_fd_size (core->io, core->file->fd): 0;
switch (*input) {
case 'a': // "r..."
if (r_str_startswith (input, "adare2")) {
__runMain (core->r_main_radare2, input - 1);
}
return true;
case '2': // "r2" // XXX should be handled already in cmd_r2cmd()
// TODO: use argv[0] instead of 'radare2'
r_sys_cmdf ("radare%s", input);
return true;
case 'm': // "rm"
if (input[1] == ' ') {
const char *file = r_str_trim_ro (input + 2);
if (*file == '$') {
r_cmd_alias_del (core->rcmd, file);
} else {
r_file_rm (file);
}
} else {
eprintf ("Usage: rm [file] # removes a file\n");
}
return true;
case '\0':
if (core->file) {
if (oldsize != -1) {
r_cons_printf ("%"PFMT64d"\n", oldsize);
}
}
return true;
case 'h':
if (core->file) {
if (oldsize != -1) {
char humansz[8];
r_num_units (humansz, sizeof (humansz), oldsize);
r_cons_printf ("%s\n", humansz);
}
}
return true;
case '+': // "r+"
case '-': // "r-"
delta = (st64)r_num_math (core->num, input);
newsize = oldsize + delta;
break;
case ' ': // "r "
newsize = r_num_math (core->num, input + 1);
if (newsize == 0) {
if (input[1] == '0') {
eprintf ("Invalid size\n");
}
return false;
}
break;
case 'e':
write (1, Color_RESET_TERMINAL, strlen (Color_RESET_TERMINAL));
return true;
case '?': // "r?"
default:
r_core_cmd_help (core, help_msg_r);
return true;
}
grow = (newsize > oldsize);
if (grow) {
ret = r_io_resize (core->io, newsize);
if (ret < 1) {
eprintf ("r_io_resize: cannot resize\n");
}
}
if (delta && core->offset < newsize) {
r_io_shift (core->io, core->offset, grow?newsize:oldsize, delta);
}
if (!grow) {
ret = r_io_resize (core->io, newsize);
if (ret < 1) {
eprintf ("r_io_resize: cannot resize\n");
}
}
if (newsize < core->offset+core->blocksize || oldsize < core->offset + core->blocksize) {
r_core_block_read (core);
}
return true;
}
static int cmd_panels(void *data, const char *input) {
RCore *core = (RCore*) data;
if (core->vmode) {
return false;
}
if (*input == '?') {
eprintf ("Usage: v[*i]\n");
eprintf ("v.test # save curren layout with name test\n");
eprintf ("v test # load saved layout with name test\n");
eprintf ("vi ... # launch 'vim'\n");
return false;
}
if (*input == ' ') {
if (core->panels) {
r_load_panels_layout (core, input + 1);
}
r_config_set (core->config, "scr.layout", input + 1);
return true;
}
if (*input == '=') {
r_save_panels_layout (core, input + 1);
r_config_set (core->config, "scr.layout", input + 1);
return true;
}
if (*input == 'i') {
r_sys_cmdf ("v%s", input);
return false;
}
r_core_visual_panels_root (core, core->panels_root);
return true;
}
static int cmd_visual(void *data, const char *input) {
RCore *core = (RCore*) data;
if (core->http_up) {
return false;
}
if (!r_cons_is_interactive ()) {
return false;
}
return r_core_visual ((RCore *)data, input);
}
static int cmd_pipein(void *user, const char *input) {
char *buf = strdup (input);
int len = r_str_unescape (buf);
r_cons_readpush (buf, len);
free (buf);
return 0;
}
static int cmd_tasks(void *data, const char *input) {
RCore *core = (RCore*) data;
switch (input[0]) {
case '\0': // "&"
case 'j': // "&j"
r_core_task_list (core, *input);
break;
case 'b': { // "&b"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
int tid = r_num_math (core->num, input + 1);
if (tid) {
r_core_task_break (core, tid);
}
break;
}
case '&': { // "&&"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
int tid = r_num_math (core->num, input + 1);
r_core_task_join (core, core->current_task, tid ? tid : -1);
break;
}
case '=': { // "&="
// r_core_task_list (core, '=');
int tid = r_num_math (core->num, input + 1);
if (tid) {
RCoreTask *task = r_core_task_get_incref (core, tid);
if (task) {
if (task->res) {
r_cons_println (task->res);
}
r_core_task_decref (task);
} else {
eprintf ("Cannot find task\n");
}
}
break;
}
case '-': // "&-"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1] == '*') {
r_core_task_del_all_done (core);
} else {
r_core_task_del (core, r_num_math (core->num, input + 1));
}
break;
case '?': // "&?"
default:
helpCmdTasks (core);
break;
case ' ': // "& "
case '_': // "&_"
case 't': { // "&t"
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
RCoreTask *task = r_core_task_new (core, true, input + 1, NULL, core);
if (!task) {
break;
}
task->transient = input[0] == 't';
r_core_task_enqueue (core, task);
break;
}
}
return 0;
}
static int cmd_pointer(void *data, const char *input) {
RCore *core = (RCore*) data;
int ret = true;
char *str, *eq;
input = r_str_trim_ro (input);
while (*input == ' ') {
input++;
}
if (!*input || *input == '?') {
r_core_cmd_help (core, help_msg_star);
return ret;
}
str = strdup (input);
eq = strchr (str, '=');
if (eq) {
*eq++ = 0;
if (!strncmp (eq, "0x", 2)) {
ret = r_core_cmdf (core, "wv %s@%s", eq, str);
} else {
ret = r_core_cmdf (core, "wx %s@%s", eq, str);
}
} else {
ret = r_core_cmdf (core, "?v [%s]", input);
}
free (str);
return ret;
}
static int cmd_env(void *data, const char *input) {
RCore *core = (RCore*)data;
int ret = true;
switch (*input) {
case '?':
cmd_help_percent (core);
break;
default:
ret = r_core_cmdf (core, "env %s", input);
}
return ret;
}
static struct autocomplete_flag_map_t {
const char* name;
const char* desc;
int type;
} autocomplete_flags [] = {
{ "$dflt", "default autocomplete flag", R_CORE_AUTOCMPLT_DFLT },
{ "$flag", "shows known flag hints", R_CORE_AUTOCMPLT_FLAG },
{ "$flsp", "shows known flag-spaces hints", R_CORE_AUTOCMPLT_FLSP },
{ "$zign", "shows known zignatures hints", R_CORE_AUTOCMPLT_ZIGN },
{ "$eval", "shows known evals hints", R_CORE_AUTOCMPLT_EVAL },
{ "$prjt", "shows known projects hints", R_CORE_AUTOCMPLT_PRJT },
{ "$mins", NULL, R_CORE_AUTOCMPLT_MINS },
{ "$brkp", "shows known breakpoints hints", R_CORE_AUTOCMPLT_BRKP },
{ "$macro", NULL, R_CORE_AUTOCMPLT_MACR },
{ "$file", "hints file paths", R_CORE_AUTOCMPLT_FILE },
{ "$thme", "shows known themes hints", R_CORE_AUTOCMPLT_THME },
{ "$optn", "allows the selection for multiple options", R_CORE_AUTOCMPLT_OPTN },
{ "$ms", "shows mount hints", R_CORE_AUTOCMPLT_MS},
{ "$sdb", "shows sdb hints", R_CORE_AUTOCMPLT_SDB},
{ NULL, NULL, 0 }
};
static inline void print_dict(RCoreAutocomplete* a, int sub) {
if (!a) {
return;
}
int i, j;
const char* name = "unknown";
for (i = 0; i < a->n_subcmds; ++i) {
RCoreAutocomplete* b = a->subcmds[i];
if (b->locked) {
continue;
}
for (j = 0; j < R_CORE_AUTOCMPLT_END; ++j) {
if (b->type == autocomplete_flags[j].type) {
name = autocomplete_flags[j].name;
break;
}
}
eprintf ("[%3d] %s: '%s'\n", sub, name, b->cmd);
print_dict (a->subcmds[i], sub + 1);
}
}
static int autocomplete_type(const char* strflag) {
int i;
for (i = 0; i < R_CORE_AUTOCMPLT_END; ++i) {
if (autocomplete_flags[i].desc && !strncmp (strflag, autocomplete_flags[i].name, 5)) {
return autocomplete_flags[i].type;
}
}
eprintf ("Invalid flag '%s'\n", strflag);
return R_CORE_AUTOCMPLT_END;
}
static void cmd_autocomplete(RCore *core, const char *input) {
RCoreAutocomplete* b = core->autocomplete;
input = r_str_trim_ro (input);
char arg[256];
if (!*input) {
print_dict (core->autocomplete, 0);
return;
}
if (*input == '?') {
r_core_cmd_help (core, help_msg_triple_exclamation);
int i;
r_cons_printf ("|Types:\n");
for (i = 0; i < R_CORE_AUTOCMPLT_END; ++i) {
if (autocomplete_flags[i].desc) {
r_cons_printf ("| %s %s\n",
autocomplete_flags[i].name,
autocomplete_flags[i].desc);
}
}
return;
}
if (*input == '-') {
const char *arg = input + 1;
if (!*input) {
eprintf ("Use !!!-* or !!!-<cmd>\n");
return;
}
r_core_autocomplete_remove (b, arg);
return;
}
while (b) {
const char* end = r_str_trim_wp (input);
if (!end) {
break;
}
if ((end - input) >= sizeof (arg)) {
// wtf?
eprintf ("Exceeded the max arg length (255).\n");
return;
}
if (end == input) {
break;
}
memcpy (arg, input, end - input);
arg[end - input] = 0;
RCoreAutocomplete* a = r_core_autocomplete_find (b, arg, true);
input = r_str_trim_ro (end);
if (input && *input && !a) {
if (b->type == R_CORE_AUTOCMPLT_DFLT && !(b = r_core_autocomplete_add (b, arg, R_CORE_AUTOCMPLT_DFLT, false))) {
eprintf ("ENOMEM\n");
return;
} else if (b->type != R_CORE_AUTOCMPLT_DFLT) {
eprintf ("Cannot add autocomplete to '%s'. type not $dflt\n", b->cmd);
return;
}
} else if ((!input || !*input) && !a) {
if (arg[0] == '$') {
int type = autocomplete_type (arg);
if (type != R_CORE_AUTOCMPLT_END && !b->locked && !b->n_subcmds) {
b->type = type;
} else if (b->locked || b->n_subcmds) {
if (!b->cmd) {
return;
}
eprintf ("Changing type of '%s' is forbidden.\n", b->cmd);
}
} else {
if (!r_core_autocomplete_add (b, arg, R_CORE_AUTOCMPLT_DFLT, false)) {
eprintf ("ENOMEM\n");
return;
}
}
return;
} else if ((!input || !*input) && a) {
// eprintf ("Cannot add '%s'. Already exists.\n", arg);
return;
} else {
b = a;
}
}
eprintf ("Invalid usage of !!!\n");
}
static int cmd_last(void *data, const char *input) {
switch (*input) {
case 0:
r_cons_last ();
break;
default:
eprintf ("Usage: _ print last output\n");
}
return 0;
}
static int cmd_system(void *data, const char *input) {
RCore *core = (RCore*)data;
ut64 n;
int ret = 0;
switch (*input) {
case '-': //!-
if (input[1]) {
r_line_hist_free();
r_line_hist_save (R2_HOME_HISTORY);
} else {
r_line_hist_free();
}
break;
case '=': //!=
if (input[1] == '?') {
r_cons_printf ("Usage: !=[!] - enable/disable remote commands\n");
} else {
if (!r_sandbox_enable (0)) {
core->cmdremote = input[1]? 1: 0;
r_cons_println (r_str_bool (core->cmdremote));
}
}
break;
case '!': //!!
if (input[1] == '!') { // !!! & !!!-
cmd_autocomplete (core, input + 2);
} else if (input[1] == '?') {
cmd_help_exclamation (core);
} else if (input[1] == '*') {
char *cmd = r_str_trim_dup (input + 1);
(void)r_core_cmdf (core, "\"#!pipe %s\"", cmd);
free (cmd);
} else {
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
return 0;
}
if (input[1]) {
int olen;
char *out = NULL;
char *cmd = r_core_sysenv_begin (core, input);
if (cmd) {
void *bed = r_cons_sleep_begin ();
ret = r_sys_cmd_str_full (cmd + 1, NULL, &out, &olen, NULL);
r_cons_sleep_end (bed);
r_core_sysenv_end (core, input);
r_cons_memcat (out, olen);
free (out);
free (cmd);
} //else eprintf ("Error setting up system environment\n");
} else {
eprintf ("History saved to "R2_HOME_HISTORY"\n");
r_line_hist_save (R2_HOME_HISTORY);
}
}
break;
case '\0':
r_line_hist_list ();
break;
case '?': //!?
cmd_help_exclamation (core);
break;
case '*':
// TODO: use the api
{
char *cmd = r_str_trim_dup (input + 1);
cmd = r_str_replace (cmd, " ", "\\ ", true);
cmd = r_str_replace (cmd, "\\ ", " ", false);
cmd = r_str_replace (cmd, "\"", "'", false);
ret = r_core_cmdf (core, "\"#!pipe %s\"", cmd);
free (cmd);
}
break;
default:
n = atoi (input);
if (*input == '0' || n > 0) {
const char *cmd = r_line_hist_get (n);
if (cmd) {
r_core_cmd0 (core, cmd);
}
//else eprintf ("Error setting up system environment\n");
} else {
char *cmd = r_core_sysenv_begin (core, input);
if (cmd) {
void *bed = r_cons_sleep_begin ();
ret = r_sys_cmd (cmd);
r_cons_sleep_end (bed);
r_core_sysenv_end (core, input);
free (cmd);
} else {
eprintf ("Error setting up system environment\n");
}
}
break;
}
return ret;
}
#if __WINDOWS__
#include <tchar.h>
static void r_w32_cmd_pipe(RCore *core, char *radare_cmd, char *shell_cmd) {
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
SECURITY_ATTRIBUTES sa;
HANDLE pipe[2] = {NULL, NULL};
int fd_out = -1, cons_out = -1;
char *_shell_cmd = NULL;
LPTSTR _shell_cmd_ = NULL;
DWORD mode;
GetConsoleMode (GetStdHandle (STD_OUTPUT_HANDLE), &mode);
sa.nLength = sizeof (SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe (&pipe[0], &pipe[1], &sa, 0)) {
r_sys_perror ("r_w32_cmd_pipe/CreatePipe");
goto err_r_w32_cmd_pipe;
}
if (!SetHandleInformation (pipe[1], HANDLE_FLAG_INHERIT, 0)) {
r_sys_perror ("r_w32_cmd_pipe/SetHandleInformation");
goto err_r_w32_cmd_pipe;
}
si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
si.hStdInput = pipe[0];
si.dwFlags |= STARTF_USESTDHANDLES;
si.cb = sizeof (si);
_shell_cmd = shell_cmd;
while (*_shell_cmd && isspace ((ut8)*_shell_cmd)) {
_shell_cmd++;
}
char *tmp = r_str_newf ("/Q /c \"%s\"", shell_cmd);
if (!tmp) {
goto err_r_w32_cmd_pipe;
}
_shell_cmd = tmp;
_shell_cmd_ = r_sys_conv_utf8_to_win (_shell_cmd);
free (tmp);
if (!_shell_cmd_) {
goto err_r_w32_cmd_pipe;
}
TCHAR *systemdir = calloc (MAX_PATH, sizeof (TCHAR));
if (!systemdir) {
goto err_r_w32_cmd_pipe;
}
int ret = GetSystemDirectory (systemdir, MAX_PATH);
if (!ret) {
r_sys_perror ("r_w32_cmd_pipe/systemdir");
goto err_r_w32_cmd_pipe;
}
_tcscat_s (systemdir, MAX_PATH, TEXT("\\cmd.exe"));
// exec windows process
if (!CreateProcess (systemdir, _shell_cmd_, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
r_sys_perror ("r_w32_cmd_pipe/CreateProcess");
goto err_r_w32_cmd_pipe;
}
fd_out = _open_osfhandle ((intptr_t)pipe[1], _O_WRONLY|_O_TEXT);
if (fd_out == -1) {
perror ("_open_osfhandle");
goto err_r_w32_cmd_pipe;
}
cons_out = dup (1);
dup2 (fd_out, 1);
// exec radare command
r_core_cmd (core, radare_cmd, 0);
r_cons_flush ();
close (1);
close (fd_out);
fd_out = -1;
WaitForSingleObject (pi.hProcess, INFINITE);
err_r_w32_cmd_pipe:
if (pi.hProcess) {
CloseHandle (pi.hProcess);
}
if (pi.hThread) {
CloseHandle (pi.hThread);
}
if (pipe[0]) {
CloseHandle (pipe[0]);
}
if (pipe[1]) {
CloseHandle (pipe[1]);
}
if (fd_out != -1) {
close (fd_out);
}
if (cons_out != -1) {
dup2 (cons_out, 1);
close (cons_out);
}
free (systemdir);
free (_shell_cmd_);
SetConsoleMode (GetStdHandle (STD_OUTPUT_HANDLE), mode);
}
#endif
R_API int r_core_cmd_pipe(RCore *core, char *radare_cmd, char *shell_cmd) {
#if __UNIX__
int stdout_fd, fds[2];
int child;
#endif
int si, olen, ret = -1, pipecolor = -1;
char *str, *out = NULL;
if (r_sandbox_enable (0)) {
eprintf ("Pipes are not allowed in sandbox mode\n");
return -1;
}
si = r_cons_is_interactive ();
r_config_set_i (core->config, "scr.interactive", 0);
if (!r_config_get_i (core->config, "scr.color.pipe")) {
pipecolor = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
if (*shell_cmd=='!') {
r_cons_grep_parsecmd (shell_cmd, "\"");
olen = 0;
out = NULL;
// TODO: implement foo
str = r_core_cmd_str (core, radare_cmd);
r_sys_cmd_str_full (shell_cmd + 1, str, &out, &olen, NULL);
free (str);
r_cons_memcat (out, olen);
free (out);
ret = 0;
}
#if __UNIX__
radare_cmd = (char*)r_str_trim_head (radare_cmd);
shell_cmd = (char*)r_str_trim_head (shell_cmd);
signal (SIGPIPE, SIG_IGN);
stdout_fd = dup (1);
if (stdout_fd != -1) {
if (pipe (fds) == 0) {
child = r_sys_fork ();
if (child == -1) {
eprintf ("Cannot fork\n");
close (stdout_fd);
} else if (child) {
dup2 (fds[1], 1);
close (fds[1]);
close (fds[0]);
r_core_cmd (core, radare_cmd, 0);
r_cons_flush ();
close (1);
wait (&ret);
dup2 (stdout_fd, 1);
close (stdout_fd);
} else {
close (fds[1]);
dup2 (fds[0], 0);
//dup2 (1, 2); // stderr goes to stdout
r_sandbox_system (shell_cmd, 0);
close (stdout_fd);
}
} else {
eprintf ("r_core_cmd_pipe: Could not pipe\n");
}
}
#elif __WINDOWS__
r_w32_cmd_pipe (core, radare_cmd, shell_cmd);
#else
#ifdef _MSC_VER
#pragma message ("r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM")
#else
#warning r_core_cmd_pipe UNIMPLEMENTED FOR THIS PLATFORM
#endif
eprintf ("r_core_cmd_pipe: unimplemented for this platform\n");
#endif
if (pipecolor != -1) {
r_config_set_i (core->config, "scr.color", pipecolor);
}
r_config_set_i (core->config, "scr.interactive", si);
return ret;
}
static char *parse_tmp_evals(RCore *core, const char *str) {
char *s = strdup (str);
int i, argc = r_str_split (s, ',');
char *res = strdup ("");
if (!s || !res) {
free (s);
free (res);
return NULL;
}
for (i = 0; i < argc; i++) {
char *eq, *kv = (char *)r_str_word_get0 (s, i);
if (!kv) {
break;
}
eq = strchr (kv, '=');
if (eq) {
*eq = 0;
const char *ov = r_config_get (core->config, kv);
if (!ov) {
continue;
}
char *cmd = r_str_newf ("e %s=%s;", kv, ov);
if (!cmd) {
free (s);
free (res);
return NULL;
}
res = r_str_prepend (res, cmd);
free (cmd);
r_config_set (core->config, kv, eq + 1);
*eq = '=';
} else {
eprintf ("Missing '=' in e: expression (%s)\n", kv);
}
}
free (s);
return res;
}
static int r_core_cmd_subst(RCore *core, char *cmd) {
ut64 rep = strtoull (cmd, NULL, 10);
int ret = 0, orep;
char *cmt, *colon = NULL, *icmd = NULL;
bool tmpseek = false;
bool original_tmpseek = core->tmpseek;
if (r_str_startswith (cmd, "GET /cmd/")) {
memmove (cmd, cmd + 9, strlen (cmd + 9) + 1);
char *http = strstr (cmd, "HTTP");
if (http) {
*http = 0;
http--;
if (*http == ' ') {
*http = 0;
}
}
r_cons_printf ("HTTP/1.0 %d %s\r\n%s"
"Connection: close\r\nContent-Length: %d\r\n\r\n",
200, "OK", "", -1);
return r_core_cmd0 (core, cmd);
}
/* must store a local orig_offset because there can be
* nested call of this function */
ut64 orig_offset = core->offset;
icmd = strdup (cmd);
if (core->max_cmd_depth - core->cons->context->cmd_depth == 1) {
core->prompt_offset = core->offset;
}
cmd = r_str_trim_head_tail (icmd);
// lines starting with # are ignored (never reach cmd_hash()), except #! and #?
if (!*cmd) {
if (core->cmdrepeat > 0) {
r_core_cmd_repeat (core, true);
ret = r_core_cmd_nullcallback (core);
}
goto beach;
}
if (!icmd || (cmd[0] == '#' && cmd[1] != '!' && cmd[1] != '?')) {
goto beach;
}
cmt = *icmd ? (char *)r_str_firstbut (icmd, '#', "\""): NULL;
if (cmt && (cmt[1] == ' ' || cmt[1] == '\t')) {
*cmt = 0;
}
if (*cmd != '"') {
if (!strchr (cmd, '\'')) { // allow | awk '{foo;bar}' // ignore ; if there's a single quote
if ((colon = strchr (cmd, ';'))) {
*colon = 0;
}
}
} else {
colon = NULL;
}
if (rep > 0) {
while (IS_DIGIT (*cmd)) {
cmd++;
}
// do not repeat null cmd
if (!*cmd) {
goto beach;
}
}
if (rep < 1) {
rep = 1;
}
// XXX if output is a pipe then we don't want to be interactive
if (rep > 1 && r_sandbox_enable (0)) {
eprintf ("Command repeat sugar disabled in sandbox mode (%s)\n", cmd);
goto beach;
} else {
if (rep > INTERACTIVE_MAX_REP) {
if (r_cons_is_interactive ()) {
if (!r_cons_yesno ('n', "Are you sure to repeat this %"PFMT64d" times? (y/N)", rep)) {
goto beach;
}
}
}
}
// TODO: store in core->cmdtimes to speedup ?
const char *cmdrep = core->cmdtimes ? core->cmdtimes: "";
orep = rep;
r_cons_break_push (NULL, NULL);
int ocur_enabled = core->print && core->print->cur_enabled;
while (rep-- && *cmd) {
if (core->print) {
core->print->cur_enabled = false;
if (ocur_enabled && core->seltab >= 0) {
if (core->seltab == core->curtab) {
core->print->cur_enabled = true;
}
}
}
if (r_cons_is_breaked ()) {
break;
}
char *cr = strdup (cmdrep);
core->break_loop = false;
ret = r_core_cmd_subst_i (core, cmd, colon, (rep == orep - 1) ? &tmpseek : NULL);
if (ret && *cmd == 'q') {
free (cr);
goto beach;
}
if (core->break_loop) {
free (cr);
break;
}
if (cr && *cr && orep > 1) {
// XXX: do not flush here, we need r_cons_push () and r_cons_pop()
r_cons_flush ();
// XXX: we must import register flags in C
(void)r_core_cmd0 (core, ".dr*");
(void)r_core_cmd0 (core, cr);
}
free (cr);
}
r_cons_break_pop ();
if (tmpseek) {
r_core_seek (core, orig_offset, 1);
core->tmpseek = original_tmpseek;
}
if (core->print) {
core->print->cur_enabled = ocur_enabled;
}
if (colon && colon[1]) {
for (++colon; *colon == ';'; colon++) {
;
}
r_core_cmd_subst (core, colon);
} else {
if (!*icmd) {
r_core_cmd_nullcallback (core);
}
}
beach:
free (icmd);
return ret;
}
static char *find_eoq(char *p) {
for (; *p; p++) {
if (*p == '"') {
break;
}
if (*p == '\\' && p[1] == '"') {
p++;
}
}
return p;
}
static char* findSeparator(char *p) {
char *q = strchr (p, '+');
if (q) {
return q;
}
return strchr (p, '-');
}
static void tmpenvs_free(void *item) {
r_sys_setenv (item, NULL);
free (item);
}
static bool set_tmp_arch(RCore *core, char *arch, char **tmparch) {
if (!tmparch) {
eprintf ("tmparch should be set\n");
}
*tmparch = strdup (r_config_get (core->config, "asm.arch"));
r_config_set (core->config, "asm.arch", arch);
core->fixedarch = true;
return true;
}
static bool set_tmp_bits(RCore *core, int bits, char **tmpbits) {
if (!tmpbits) {
eprintf ("tmpbits should be set\n");
}
*tmpbits = strdup (r_config_get (core->config, "asm.bits"));
r_config_set_i (core->config, "asm.bits", bits);
core->fixedbits = true;
return true;
}
static int r_core_cmd_subst_i(RCore *core, char *cmd, char *colon, bool *tmpseek) {
RList *tmpenvs = r_list_newf (tmpenvs_free);
const char *quotestr = "`";
const char *tick = NULL;
char *ptr, *ptr2, *str;
char *arroba = NULL;
char *grep = NULL;
RIODesc *tmpdesc = NULL;
int pamode = !core->io->va;
int i, ret = 0, pipefd;
bool usemyblock = false;
int scr_html = -1;
int scr_color = -1;
bool eos = false;
bool haveQuote = false;
bool oldfixedarch = core->fixedarch;
bool oldfixedbits = core->fixedbits;
bool cmd_tmpseek = false;
ut64 tmpbsz = core->blocksize;
int cmd_ignbithints = -1;
if (!cmd) {
r_list_free (tmpenvs);
return 0;
}
cmd = r_str_trim_head_tail (cmd);
char *$0 = strstr (cmd, "$(");
if ($0) {
char *$1 = strchr ($0 + 2, ')');
if ($1) {
*$0 = '`';
*$1 = '`';
memmove ($0 + 1, $0 + 2, strlen ($0 + 2) + 1);
} else {
eprintf ("Unterminated $() block\n");
}
}
/* quoted / raw command */
switch (*cmd) {
case '.':
if (cmd[1] == '"') { /* interpret */
r_list_free (tmpenvs);
return r_cmd_call (core->rcmd, cmd);
}
break;
case '"':
for (; *cmd; ) {
int pipefd = -1;
ut64 oseek = UT64_MAX;
char *line, *p;
haveQuote = *cmd == '"';
if (haveQuote) {
cmd++;
p = *cmd ? find_eoq (cmd) : NULL;
if (!p || !*p) {
eprintf ("Missing \" in (%s).", cmd);
r_list_free (tmpenvs);
return false;
}
*p++ = 0;
if (!*p) {
eos = true;
}
} else {
char *sc = strchr (cmd, ';');
if (sc) {
*sc = 0;
}
r_core_cmd0 (core, cmd);
if (!sc) {
break;
}
cmd = sc + 1;
continue;
}
if (*p) {
// workaround :D
if (p[0] == '@') {
p--;
}
while (p[1] == ';' || IS_WHITESPACE (p[1])) {
p++;
}
if (p[1] == '@' || (p[1] && p[2] == '@')) {
char *q = strchr (p + 1, '"');
if (q) {
*q = 0;
}
haveQuote = q != NULL;
oseek = core->offset;
r_core_seek (core, r_num_math (core->num, p + 2), 1);
if (q) {
*p = '"';
p = q;
} else {
p = strchr (p + 1, ';');
}
}
if (p && *p && p[1] == '>') {
str = p + 2;
while (*str == '>') {
str++;
}
str = (char *)r_str_trim_ro (str);
r_cons_flush ();
const bool append = p[2] == '>';
pipefd = r_cons_pipe_open (str, 1, append);
}
}
line = strdup (cmd);
line = r_str_replace (line, "\\\"", "\"", true);
if (p && *p && p[1] == '|') {
str = p + 2;
while (IS_WHITESPACE (*str)) {
str++;
}
r_core_cmd_pipe (core, cmd, str);
} else {
r_cmd_call (core->rcmd, line);
}
free (line);
if (oseek != UT64_MAX) {
r_core_seek (core, oseek, 1);
}
if (pipefd != -1) {
r_cons_flush ();
r_cons_pipe_close (pipefd);
}
if (!p) {
break;
}
if (eos) {
break;
}
if (haveQuote) {
if (*p == ';') {
cmd = p + 1;
} else {
if (*p == '"') {
cmd = p + 1;
} else {
*p = '"';
cmd = p;
}
}
} else {
cmd = p + 1;
}
}
r_list_free (tmpenvs);
return true;
case '(':
if (cmd[1] != '*' && !strstr (cmd, ")()")) {
r_list_free (tmpenvs);
return r_cmd_call (core->rcmd, cmd);
}
break;
case '?':
if (cmd[1] == '>') {
r_core_cmd_help (core, help_msg_greater_sign);
r_list_free (tmpenvs);
return true;
}
}
// TODO must honor `
/* comments */
if (*cmd != '#') {
ptr = (char *)r_str_firstbut (cmd, '#', "`\""); // TODO: use quotestr here
if (ptr && (ptr[1] == ' ' || ptr[1] == '\t')) {
*ptr = '\0';
}
}
/* multiple commands */
// TODO: must honor " and ` boundaries
//ptr = strrchr (cmd, ';');
if (*cmd != '#') {
ptr = (char *)r_str_lastbut (cmd, ';', quotestr);
if (colon && ptr) {
int ret ;
*ptr = '\0';
if (r_core_cmd_subst (core, cmd) == -1) {
r_list_free (tmpenvs);
return -1;
}
cmd = ptr + 1;
ret = r_core_cmd_subst (core, cmd);
*ptr = ';';
r_list_free (tmpenvs);
return ret;
//r_cons_flush ();
}
}
// TODO must honor " and `
/* pipe console to shell process */
//ptr = strchr (cmd, '|');
ptr = (char *)r_str_lastbut (cmd, '|', quotestr);
if (ptr) {
if (ptr > cmd) {
char *ch = ptr - 1;
if (*ch == '\\') {
memmove (ch, ptr, strlen (ptr) + 1);
goto escape_pipe;
}
}
char *ptr2 = strchr (cmd, '`');
if (!ptr2 || (ptr2 && ptr2 > ptr)) {
if (!tick || (tick && tick > ptr)) {
*ptr = '\0';
cmd = r_str_trim_nc (cmd);
if (!strcmp (ptr + 1, "?")) { // "|?"
r_core_cmd_help (core, help_msg_vertical_bar);
r_list_free (tmpenvs);
return ret;
} else if (!strncmp (ptr + 1, "H", 1)) { // "|H"
scr_html = r_config_get_i (core->config, "scr.html");
r_config_set_i (core->config, "scr.html", true);
} else if (!strcmp (ptr + 1, "T")) { // "|T"
scr_color = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
core->cons->use_tts = true;
} else if (!strcmp (ptr + 1, ".")) { // "|."
ret = *cmd ? r_core_cmdf (core, ".%s", cmd) : 0;
r_list_free (tmpenvs);
return ret;
} else if (ptr[1]) { // "| grep .."
int value = core->num->value;
if (*cmd) {
r_core_cmd_pipe (core, cmd, ptr + 1);
} else {
char *res = r_io_system (core->io, ptr + 1);
if (res) {
r_cons_printf ("%s\n", res);
free (res);
}
}
core->num->value = value;
r_list_free (tmpenvs);
return 0;
} else { // "|"
scr_html = r_config_get_i (core->config, "scr.html");
r_config_set_i (core->config, "scr.html", 0);
scr_color = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
}
}
}
escape_pipe:
// TODO must honor " and `
/* bool conditions */
ptr = (char *)r_str_lastbut (cmd, '&', quotestr);
//ptr = strchr (cmd, '&');
while (ptr && *ptr && ptr[1] == '&') {
*ptr = '\0';
ret = r_cmd_call (core->rcmd, cmd);
if (ret == -1) {
eprintf ("command error(%s)\n", cmd);
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
r_list_free (tmpenvs);
return ret;
}
for (cmd = ptr + 2; cmd && *cmd == ' '; cmd++) {
;
}
ptr = strchr (cmd, '&');
}
/* Out Of Band Input */
R_FREE (core->oobi);
ptr = strstr (cmd, "?*");
if (ptr && (ptr == cmd || ptr[-1] != '~')) {
ptr[0] = 0;
if (*cmd != '#') {
int detail = 0;
if (cmd < ptr && ptr[-1] == '?') {
detail++;
if (cmd < ptr - 1 && ptr[-2] == '?') {
detail++;
}
}
r_cons_break_push (NULL, NULL);
recursive_help (core, detail, cmd);
r_cons_break_pop ();
r_cons_grep_parsecmd (ptr + 2, "`");
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
r_list_free (tmpenvs);
return 0;
}
}
#if 0
ptr = strchr (cmd, '<');
if (ptr) {
ptr[0] = '\0';
if (r_cons_singleton ()->is_interactive) {
if (ptr[1] == '<') {
/* this is a bit mess */
//const char *oprompt = strdup (r_line_singleton ()->prompt);
//oprompt = ">";
for (str = ptr + 2; str[0] == ' '; str++) {
//nothing to see here
}
eprintf ("==> Reading from stdin until '%s'\n", str);
free (core->oobi);
core->oobi = malloc (1);
if (core->oobi) {
core->oobi[0] = '\0';
}
core->oobi_len = 0;
for (;;) {
char buf[1024];
int ret;
write (1, "> ", 2);
fgets (buf, sizeof (buf) - 1, stdin); // XXX use r_line ??
if (feof (stdin)) {
break;
}
if (*buf) buf[strlen (buf) - 1]='\0';
ret = strlen (buf);
core->oobi_len += ret;
core->oobi = realloc (core->oobi, core->oobi_len + 1);
if (core->oobi) {
if (!strcmp (buf, str)) {
break;
}
strcat ((char *)core->oobi, buf);
}
}
//r_line_set_prompt (oprompt);
} else {
for (str = ptr + 1; *str == ' '; str++) {
//nothing to see here
}
if (!*str) {
goto next;
}
eprintf ("Slurping file '%s'\n", str);
free (core->oobi);
core->oobi = (ut8*)r_file_slurp (str, &core->oobi_len);
if (!core->oobi) {
eprintf ("cannot open file\n");
} else if (ptr == cmd) {
return r_core_cmd_buffer (core, (const char *)core->oobi);
}
}
} else {
eprintf ("Cannot slurp with << in non-interactive mode\n");
r_list_free (tmpenvs);
return 0;
}
}
next:
#endif
/* pipe console to file */
ptr = (char *)r_str_firstbut (cmd, '>', "\"");
// TODO honor `
if (ptr) {
if (ptr > cmd) {
char *ch = ptr - 1;
if (*ch == '\\') {
memmove (ch, ptr, strlen (ptr) + 1);
goto escape_redir;
}
}
if (ptr[0] && ptr[1] == '?') {
r_core_cmd_help (core, help_msg_greater_sign);
r_list_free (tmpenvs);
return true;
}
int fdn = 1;
int pipecolor = r_config_get_i (core->config, "scr.color.pipe");
int use_editor = false;
int ocolor = r_config_get_i (core->config, "scr.color");
*ptr = '\0';
str = r_str_trim_head_tail (ptr + 1 + (ptr[1] == '>'));
if (!*str) {
eprintf ("No output?\n");
goto next2;
}
/* r_cons_flush() handles interactive output (to the terminal)
* differently (e.g. asking about too long output). This conflicts
* with piping to a file. Disable it while piping. */
if (ptr > (cmd + 1) && IS_WHITECHAR (ptr[-2])) {
char *fdnum = ptr - 1;
if (*fdnum == 'H') { // "H>"
scr_html = r_config_get_i (core->config, "scr.html");
r_config_set_i (core->config, "scr.html", true);
pipecolor = true;
*fdnum = 0;
} else {
if (IS_DIGIT (*fdnum)) {
fdn = *fdnum - '0';
}
*fdnum = 0;
}
}
r_cons_set_interactive (false);
if (!strcmp (str, "-")) {
use_editor = true;
str = r_file_temp ("dumpedit");
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
const bool appendResult = (ptr[1] == '>');
if (*str == '$') {
// pipe to alias variable
// register output of command as an alias
char *o = r_core_cmd_str (core, cmd);
if (appendResult) {
char *oldText = r_cmd_alias_get (core->rcmd, str, 1);
if (oldText) {
char *two = r_str_newf ("%s%s", oldText, o);
if (two) {
r_cmd_alias_set (core->rcmd, str, two, 1);
free (two);
}
} else {
char *n = r_str_newf ("$%s", o);
r_cmd_alias_set (core->rcmd, str, n, 1);
free (n);
}
} else {
char *n = r_str_newf ("$%s", o);
r_cmd_alias_set (core->rcmd, str, n, 1);
free (n);
}
ret = 0;
free (o);
} else if (fdn > 0) {
// pipe to file (or append)
pipefd = r_cons_pipe_open (str, fdn, appendResult);
if (pipefd != -1) {
if (!pipecolor) {
r_config_set_i (core->config, "scr.color", COLOR_MODE_DISABLED);
}
ret = r_core_cmd_subst (core, cmd);
r_cons_flush ();
r_cons_pipe_close (pipefd);
}
}
r_cons_set_last_interactive ();
if (!pipecolor) {
r_config_set_i (core->config, "scr.color", ocolor);
}
if (use_editor) {
const char *editor = r_config_get (core->config, "cfg.editor");
if (editor && *editor) {
r_sys_cmdf ("%s '%s'", editor, str);
r_file_rm (str);
} else {
eprintf ("No cfg.editor configured\n");
}
r_config_set_i (core->config, "scr.color", ocolor);
free (str);
}
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
core->cons->use_tts = false;
r_list_free (tmpenvs);
return ret;
}
escape_redir:
next2:
/* sub commands */
ptr = strchr (cmd, '`');
if (ptr) {
if (ptr > cmd) {
char *ch = ptr - 1;
if (*ch == '\\') {
memmove (ch, ptr, strlen (ptr) + 1);
goto escape_backtick;
}
}
bool empty = false;
int oneline = 1;
if (ptr[1] == '`') {
memmove (ptr, ptr + 1, strlen (ptr));
oneline = 0;
empty = true;
}
ptr2 = strchr (ptr + 1, '`');
if (empty) {
/* do nothing */
} else if (!ptr2) {
eprintf ("parse: Missing backtick in expression.\n");
goto fail;
} else {
int value = core->num->value;
*ptr = '\0';
*ptr2 = '\0';
if (ptr[1] == '!') {
str = r_core_cmd_str_pipe (core, ptr + 1);
} else {
// Color disabled when doing backticks ?e `pi 1`
int ocolor = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", 0);
core->cmd_in_backticks = true;
str = r_core_cmd_str (core, ptr + 1);
core->cmd_in_backticks = false;
r_config_set_i (core->config, "scr.color", ocolor);
}
if (!str) {
goto fail;
}
// ignore contents if first char is pipe or comment
if (*str == '|' || *str == '*') {
eprintf ("r_core_cmd_subst_i: invalid backticked command\n");
free (str);
goto fail;
}
if (oneline && str) {
for (i = 0; str[i]; i++) {
if (str[i] == '\n') {
str[i] = ' ';
}
}
}
str = r_str_append (str, ptr2 + 1);
cmd = r_str_append (strdup (cmd), str);
core->num->value = value;
ret = r_core_cmd_subst (core, cmd);
free (cmd);
if (scr_html != -1) {
r_config_set_i (core->config, "scr.html", scr_html);
}
free (str);
r_list_free (tmpenvs);
return ret;
}
}
escape_backtick:
// TODO must honor " and `
if (*cmd != '"' && *cmd) {
const char *s = strstr (cmd, "~?");
if (s) {
bool showHelp = false;
if (cmd == s) {
// ~?
// ~??
showHelp = true;
} else {
// pd~?
// pd~??
if (!strcmp (s, "~??")) {
showHelp = true;
}
}
if (showHelp) {
r_cons_grep_help ();
r_list_free (tmpenvs);
return true;
}
}
}
if (*cmd != '.') {
grep = r_cons_grep_strip (cmd, quotestr);
}
/* temporary seek commands */
// if (*cmd != '(' && *cmd != '"') {
if (*cmd != '"') {
ptr = strchr (cmd, '@');
if (ptr == cmd + 1 && *cmd == '?') {
ptr = NULL;
}
} else {
ptr = NULL;
}
cmd_tmpseek = core->tmpseek = ptr ? true: false;
int rc = 0;
if (ptr) {
char *f, *ptr2 = strchr (ptr + 1, '!');
ut64 addr = core->offset;
bool addr_is_set = false;
char *tmpbits = NULL;
const char *offstr = NULL;
bool is_bits_set = false;
bool is_arch_set = false;
char *tmpeval = NULL;
char *tmpasm = NULL;
bool flgspc_changed = false;
int tmpfd = -1;
int sz, len;
ut8 *buf;
*ptr++ = '\0';
repeat_arroba:
arroba = (ptr[0] && ptr[1] && ptr[2])?
strchr (ptr + 2, '@'): NULL;
if (arroba) {
*arroba = 0;
}
for (; *ptr == ' '; ptr++) {
//nothing to see here
}
if (*ptr && ptr[1] == ':') {
/* do nothing here */
} else {
ptr--;
}
ptr = r_str_trim_tail (ptr);
if (ptr[1] == '?') {
r_core_cmd_help (core, help_msg_at);
} else if (ptr[1] == '%') { // "@%"
char *k = strdup (ptr + 2);
char *v = strchr (k, '=');
if (v) {
*v++ = 0;
r_sys_setenv (k, v);
r_list_append (tmpenvs, k);
} else {
free (k);
}
} else if (ptr[1] == '.') { // "@."
if (ptr[2] == '.') { // "@.."
if (ptr[3] == '.') { // "@..."
ut64 addr = r_num_tail (core->num, core->offset, ptr + 4);
r_core_block_size (core, R_ABS ((st64)addr - (st64)core->offset));
goto fuji;
} else {
addr = r_num_tail (core->num, core->offset, ptr + 3);
r_core_seek (core, addr, 1);
cmd_tmpseek = core->tmpseek = true;
goto fuji;
}
} else {
// WAT DU
eprintf ("TODO: what do you expect for @. import offset from file maybe?\n");
}
} else if (ptr[0] && ptr[1] == ':' && ptr[2]) {
switch (ptr[0]) {
case 'F': // "@F:" // temporary flag space
flgspc_changed = r_flag_space_push (core->flags, ptr + 2);
break;
case 'B': // "@B:#" // seek to the last instruction in current bb
{
int index = (int)r_num_math (core->num, ptr + 2);
RAnalBlock *bb = r_anal_bb_from_offset (core->anal, core->offset);
if (bb) {
// handle negative indices
if (index < 0) {
index = bb->ninstr + index;
}
if (index >= 0 && index < bb->ninstr) {
ut16 inst_off = r_anal_bb_offset_inst (bb, index);
r_core_seek (core, bb->addr + inst_off, 1);
cmd_tmpseek = core->tmpseek = true;
} else {
eprintf ("The current basic block has %d instructions\n", bb->ninstr);
}
} else {
eprintf ("Can't find a basic block for 0x%08"PFMT64x"\n", core->offset);
}
break;
}
break;
case 'f': // "@f:" // slurp file in block
f = r_file_slurp (ptr + 2, &sz);
if (f) {
{
RBuffer *b = r_buf_new_with_bytes ((const ut8*)f, sz);
RIODesc *d = r_io_open_buffer (core->io, b, R_PERM_RWX, 0);
if (d) {
if (tmpdesc) {
r_io_desc_close (tmpdesc);
}
tmpdesc = d;
if (pamode) {
r_config_set_i (core->config, "io.va", 1);
}
r_io_map_new (core->io, d->fd, d->perm, 0, core->offset, r_buf_size (b));
}
}
#if 0
buf = malloc (sz);
if (buf) {
free (core->block);
core->block = buf;
core->blocksize = sz;
memcpy (core->block, f, sz);
usemyblock = true;
} else {
eprintf ("cannot alloc %d", sz);
}
free (f);
#endif
} else {
eprintf ("cannot open '%s'\n", ptr + 3);
}
break;
case 'r': // "@r:" // regname
if (ptr[1] == ':') {
ut64 regval;
char *mander = strdup (ptr + 2);
char *sep = findSeparator (mander);
if (sep) {
char ch = *sep;
*sep = 0;
regval = r_debug_reg_get (core->dbg, mander);
*sep = ch;
char *numexpr = r_str_newf ("0x%"PFMT64x"%s", regval, sep);
regval = r_num_math (core->num, numexpr);
free (numexpr);
} else {
regval = r_debug_reg_get (core->dbg, ptr + 2);
}
r_core_seek (core, regval, 1);
cmd_tmpseek = core->tmpseek = true;
free (mander);
}
break;
case 'b': // "@b:" // bits
is_bits_set = set_tmp_bits (core, r_num_math (core->num, ptr + 2), &tmpbits);
cmd_ignbithints = r_config_get_i (core->config, "anal.ignbithints");
r_config_set_i (core->config, "anal.ignbithints", 1);
break;
case 'i': // "@i:"
{
ut64 addr = r_num_math (core->num, ptr + 2);
if (addr) {
r_core_cmdf (core, "so %s", ptr + 2);
// r_core_seek (core, core->offset, 1);
cmd_tmpseek = core->tmpseek = true;
}
}
break;
case 'e': // "@e:"
{
char *cmd = parse_tmp_evals (core, ptr + 2);
if (!tmpeval) {
tmpeval = cmd;
} else {
tmpeval = r_str_prepend (tmpeval, cmd);
free (cmd);
}
}
break;
case 'x': // "@x:" // hexpairs
if (ptr[1] == ':') {
buf = malloc (strlen (ptr + 2) + 1);
if (buf) {
len = r_hex_str2bin (ptr + 2, buf);
r_core_block_size (core, R_ABS (len));
if (len > 0) {
RBuffer *b = r_buf_new_with_bytes (buf, len);
RIODesc *d = r_io_open_buffer (core->io, b, R_PERM_RWX, 0);
if (d) {
if (tmpdesc) {
r_io_desc_close (tmpdesc);
}
tmpdesc = d;
if (pamode) {
r_config_set_i (core->config, "io.va", 1);
}
r_io_map_new (core->io, d->fd, d->perm, 0, core->offset, r_buf_size (b));
r_core_block_size (core, len);
r_core_block_read (core);
}
} else {
eprintf ("Error: Invalid hexpairs for @x:\n");
}
free (buf);
} else {
eprintf ("cannot allocate\n");
}
} else {
eprintf ("Invalid @x: syntax\n");
}
break;
case 'k': // "@k"
{
char *out = sdb_querys (core->sdb, NULL, 0, ptr + ((ptr[1])? 2: 1));
if (out) {
r_core_seek (core, r_num_math (core->num, out), 1);
free (out);
usemyblock = true;
}
}
break;
case 'o': // "@o:3"
if (ptr[1] == ':') {
tmpfd = core->io->desc ? core->io->desc->fd : -1;
r_io_use_fd (core->io, atoi (ptr + 2));
}
break;
case 'a': // "@a:"
if (ptr[1] == ':') {
char *q = strchr (ptr + 2, ':');
if (q) {
*q++ = 0;
int bits = r_num_math (core->num, q);
is_bits_set = set_tmp_bits (core, bits, &tmpbits);
}
is_arch_set = set_tmp_arch (core, ptr + 2, &tmpasm);
} else {
eprintf ("Usage: pd 10 @a:arm:32\n");
}
break;
case 's': // "@s:" // wtf syntax
{
len = strlen (ptr + 2);
r_core_block_size (core, len);
const ut8 *buf = (const ut8*)r_str_trim_ro (ptr + 2);
if (len > 0) {
RBuffer *b = r_buf_new_with_bytes (buf, len);
RIODesc *d = r_io_open_buffer (core->io, b, R_PERM_RWX, 0);
if (!core->io->va) {
r_config_set_i (core->config, "io.va", 1);
}
if (d) {
if (tmpdesc) {
r_io_desc_close (tmpdesc);
}
tmpdesc = d;
if (pamode) {
r_config_set_i (core->config, "io.va", 1);
}
r_io_map_new (core->io, d->fd, d->perm, 0, core->offset, r_buf_size (b));
r_core_block_size (core, len);
// r_core_block_read (core);
}
}
}
break;
default:
goto ignore;
}
*ptr = '@';
/* trim whitespaces before the @ */
/* Fixes pd @x:9090 */
char *trim = ptr - 2;
while (trim > cmd) {
if (!IS_WHITESPACE (*trim)) {
break;
}
*trim = 0;
trim--;
}
goto next_arroba;
}
ignore:
ptr = r_str_trim_head (ptr + 1) - 1;
cmd = r_str_trim_nc (cmd);
if (ptr2) {
if (strlen (ptr + 1) == 13 && strlen (ptr2 + 1) == 6 &&
!memcmp (ptr + 1, "0x", 2) &&
!memcmp (ptr2 + 1, "0x", 2)) {
/* 0xXXXX:0xYYYY */
} else if (strlen (ptr + 1) == 9 && strlen (ptr2 + 1) == 4) {
/* XXXX:YYYY */
} else {
*ptr2 = '\0';
if (!ptr2[1]) {
goto fail;
}
r_core_block_size (
core, r_num_math (core->num, ptr2 + 1));
}
}
offstr = r_str_trim_head (ptr + 1);
addr = r_num_math (core->num, offstr);
addr_is_set = true;
if (isalpha ((ut8)ptr[1]) && !addr) {
if (!r_flag_get (core->flags, ptr + 1)) {
eprintf ("Invalid address (%s)\n", ptr + 1);
goto fail;
}
} else {
char ch = *offstr;
if (ch == '-' || ch == '+') {
addr = core->offset + addr;
}
}
// remap thhe tmpdesc if any
if (addr) {
RIODesc *d = tmpdesc;
if (d) {
r_io_map_new (core->io, d->fd, d->perm, 0, addr, r_io_desc_size (d));
}
}
next_arroba:
if (arroba) {
ptr = arroba + 1;
*arroba = '@';
arroba = NULL;
goto repeat_arroba;
}
core->fixedblock = !!tmpdesc;
if (core->fixedblock) {
r_core_block_read (core);
}
if (ptr[1] == '@') {
if (ptr[2] == '@') {
char *rule = ptr + 3;
while (*rule && *rule == ' ') {
rule++;
}
ret = r_core_cmd_foreach3 (core, cmd, rule);
} else {
ret = r_core_cmd_foreach (core, cmd, ptr + 2);
}
} else {
bool tmpseek = false;
const char *fromvars[] = { "anal.from", "diff.from", "graph.from",
"io.buffer.from", "lines.from", "search.from", "zoom.from", NULL };
const char *tovars[] = { "anal.to", "diff.to", "graph.to",
"io.buffer.to", "lines.to", "search.to", "zoom.to", NULL };
ut64 curfrom[R_ARRAY_SIZE (fromvars) - 1], curto[R_ARRAY_SIZE (tovars) - 1];
// "@(A B)"
if (ptr[1] == '(') {
char *range = ptr + 3;
char *p = strchr (range, ' ');
if (!p) {
eprintf ("Usage: / ABCD @..0x1000 0x3000\n");
free (tmpeval);
free (tmpasm);
free (tmpbits);
goto fail;
}
*p = '\x00';
ut64 from = r_num_math (core->num, range);
ut64 to = r_num_math (core->num, p + 1);
// save current ranges
for (i = 0; fromvars[i]; i++) {
curfrom[i] = r_config_get_i (core->config, fromvars[i]);
}
for (i = 0; tovars[i]; i++) {
curto[i] = r_config_get_i (core->config, tovars[i]);
}
// set new ranges
for (i = 0; fromvars[i]; i++) {
r_config_set_i (core->config, fromvars[i], from);
}
for (i = 0; tovars[i]; i++) {
r_config_set_i (core->config, tovars[i], to);
}
tmpseek = true;
}
if (usemyblock) {
if (addr_is_set) {
core->offset = addr;
}
ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd));
} else {
if (addr_is_set) {
if (ptr[1]) {
r_core_seek (core, addr, 1);
r_core_block_read (core);
}
}
ret = r_cmd_call (core->rcmd, r_str_trim_head (cmd));
}
if (tmpseek) {
// restore ranges
for (i = 0; fromvars[i]; i++) {
r_config_set_i (core->config, fromvars[i], curfrom[i]);
}
for (i = 0; tovars[i]; i++) {
r_config_set_i (core->config, tovars[i], curto[i]);
}
}
}
if (ptr2) {
*ptr2 = '!';
r_core_block_size (core, tmpbsz);
}
if (is_arch_set) {
core->fixedarch = oldfixedarch;
r_config_set (core->config, "asm.arch", tmpasm);
R_FREE (tmpasm);
}
if (tmpfd != -1) {
// TODO: reuse tmpfd instead of
r_io_use_fd (core->io, tmpfd);
}
if (tmpdesc) {
if (pamode) {
r_config_set_i (core->config, "io.va", 0);
}
r_io_desc_close (tmpdesc);
tmpdesc = NULL;
}
if (is_bits_set) {
r_config_set (core->config, "asm.bits", tmpbits);
core->fixedbits = oldfixedbits;
}
if (tmpbsz != core->blocksize) {
r_core_block_size (core, tmpbsz);
}
if (tmpeval) {
r_core_cmd0 (core, tmpeval);
R_FREE (tmpeval);
}
if (flgspc_changed) {
r_flag_space_pop (core->flags);
}
*ptr = '@';
rc = ret;
goto beach;
}
fuji:
rc = cmd? r_cmd_call (core->rcmd, r_str_trim_head (cmd)): false;
beach:
r_cons_grep_process (grep);
if (scr_html != -1) {
r_cons_flush ();
r_config_set_i (core->config, "scr.html", scr_html);
}
if (scr_color != -1) {
r_config_set_i (core->config, "scr.color", scr_color);
}
r_list_free (tmpenvs);
if (tmpdesc) {
r_io_desc_close (tmpdesc);
tmpdesc = NULL;
}
core->fixedarch = oldfixedarch;
core->fixedbits = oldfixedbits;
if (tmpseek) {
*tmpseek = cmd_tmpseek;
}
if (cmd_ignbithints != -1) {
r_config_set_i (core->config, "anal.ignbithints", cmd_ignbithints);
}
return rc;
fail:
rc = -1;
goto beach;
}
static int foreach_comment(void *user, const char *k, const char *v) {
RAnalMetaUserItem *ui = user;
RCore *core = ui->anal->user;
const char *cmd = ui->user;
if (!strncmp (k, "meta.C.", 7)) {
char *cmt = (char *)sdb_decode (v, 0);
if (cmt) {
r_core_cmdf (core, "s %s", k + 7);
r_core_cmd0 (core, cmd);
free (cmt);
}
}
return 1;
}
struct exec_command_t {
RCore *core;
const char *cmd;
};
static bool exec_command_on_flag(RFlagItem *flg, void *u) {
struct exec_command_t *user = (struct exec_command_t *)u;
r_core_block_size (user->core, flg->size);
r_core_seek (user->core, flg->offset, 1);
r_core_cmd0 (user->core, user->cmd);
return true;
}
static void foreach_pairs(RCore *core, const char *cmd, const char *each) {
const char *arg;
int pair = 0;
for (arg = each ; ; ) {
char *next = strchr (arg, ' ');
if (next) {
*next = 0;
}
if (arg && *arg) {
ut64 n = r_num_get (NULL, arg);
if (pair%2) {
r_core_block_size (core, n);
r_core_cmd0 (core, cmd);
} else {
r_core_seek (core, n, 1);
}
pair++;
}
if (!next) {
break;
}
arg = next + 1;
}
}
R_API int r_core_cmd_foreach3(RCore *core, const char *cmd, char *each) { // "@@@"
RDebug *dbg = core->dbg;
RList *list, *head;
RListIter *iter;
int i;
const char *filter = NULL;
if (each[1] == ':') {
filter = each + 2;
}
switch (each[0]) {
case '=':
foreach_pairs (core, cmd, each + 1);
break;
case '?':
r_core_cmd_help (core, help_msg_at_at_at);
break;
case 'c':
if (filter) {
char *arg = r_core_cmd_str (core, filter);
foreach_pairs (core, cmd, arg);
free (arg);
} else {
eprintf ("Usage: @@@c:command # same as @@@=`command`\n");
}
break;
case 'C':
r_meta_list_cb (core->anal, R_META_TYPE_COMMENT, 0, foreach_comment, (void*)cmd, UT64_MAX);
break;
case 'm':
{
int fd = r_io_fd_get_current (core->io);
// only iterate maps of current fd
RList *maps = r_io_map_get_for_fd (core->io, fd);
RIOMap *map;
if (maps) {
RListIter *iter;
r_list_foreach (maps, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_core_block_size (core, map->itv.size);
r_core_cmd0 (core, cmd);
}
r_list_free (maps);
}
}
break;
case 'M':
if (dbg && dbg->h && dbg->maps) {
RDebugMap *map;
r_list_foreach (dbg->maps, iter, map) {
r_core_seek (core, map->addr, 1);
//r_core_block_size (core, map->size);
r_core_cmd0 (core, cmd);
}
}
break;
case 't':
// iterate over all threads
if (dbg && dbg->h && dbg->h->threads) {
int origpid = dbg->pid;
RDebugPid *p;
list = dbg->h->threads (dbg, dbg->pid);
if (!list) {
return false;
}
r_list_foreach (list, iter, p) {
r_core_cmdf (core, "dp %d", p->pid);
r_cons_printf ("PID %d\n", p->pid);
r_core_cmd0 (core, cmd);
}
r_core_cmdf (core, "dp %d", origpid);
r_list_free (list);
}
break;
case 'r':
// registers
{
ut64 offorig = core->offset;
for (i = 0; i < 128; i++) {
RRegItem *item;
ut64 value;
head = r_reg_get_list (dbg->reg, i);
if (!head) {
continue;
}
r_list_foreach (head, iter, item) {
if (item->size != core->anal->bits) {
continue;
}
value = r_reg_get_value (dbg->reg, item);
r_core_seek (core, value, 1);
r_cons_printf ("%s: ", item->name);
r_core_cmd0 (core, cmd);
}
}
r_core_seek (core, offorig, 1);
}
break;
case 'i': // @@@i
// imports
{
RBinImport *imp;
ut64 offorig = core->offset;
list = r_bin_get_imports (core->bin);
r_list_foreach (list, iter, imp) {
char *impflag = r_str_newf ("sym.imp.%s", imp->name);
ut64 addr = r_num_math (core->num, impflag);
free (impflag);
if (addr && addr != UT64_MAX) {
r_core_seek (core, addr, 1);
r_core_cmd0 (core, cmd);
}
}
r_core_seek (core, offorig, 1);
}
break;
case 'S': // "@@@S"
{
RBinObject *obj = r_bin_cur_object (core->bin);
if (obj) {
ut64 offorig = core->offset;
ut64 bszorig = core->blocksize;
RBinSection *sec;
RListIter *iter;
r_list_foreach (obj->sections, iter, sec) {
r_core_seek (core, sec->vaddr, 1);
r_core_block_size (core, sec->vsize);
r_core_cmd0 (core, cmd);
}
r_core_block_size (core, bszorig);
r_core_seek (core, offorig, 1);
}
}
#if ATTIC
if (each[1] == 'S') {
RListIter *it;
RBinSection *sec;
RBinObject *obj = r_bin_cur_object (core->bin);
int cbsz = core->blocksize;
r_list_foreach (obj->sections, it, sec){
ut64 addr = sec->vaddr;
ut64 size = sec->vsize;
// TODO:
//if (R_BIN_SCN_EXECUTABLE & sec->perm) {
// continue;
//}
r_core_seek_size (core, addr, size);
r_core_cmd (core, cmd, 0);
}
r_core_block_size (core, cbsz);
}
#endif
break;
case 's':
if (each[1] == 't') { // strings
list = r_bin_get_strings (core->bin);
RBinString *s;
if (list) {
ut64 offorig = core->offset;
ut64 obs = core->blocksize;
r_list_foreach (list, iter, s) {
r_core_block_size (core, s->size);
r_core_seek (core, s->vaddr, 1);
r_core_cmd0 (core, cmd);
}
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
} else {
// symbols
RBinSymbol *sym;
ut64 offorig = core->offset;
ut64 obs = core->blocksize;
list = r_bin_get_symbols (core->bin);
r_cons_break_push (NULL, NULL);
r_list_foreach (list, iter, sym) {
if (r_cons_is_breaked ()) {
break;
}
r_core_block_size (core, sym->size);
r_core_seek (core, sym->vaddr, 1);
r_core_cmd0 (core, cmd);
}
r_cons_break_pop ();
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
break;
case 'f': // flags
{
// TODO: honor ^C
char *glob = filter? r_str_trim_dup (filter): NULL;
ut64 off = core->offset;
ut64 obs = core->blocksize;
struct exec_command_t u = { .core = core, .cmd = cmd };
r_flag_foreach_glob (core->flags, glob, exec_command_on_flag, &u);
r_core_seek (core, off, 0);
r_core_block_size (core, obs);
free (glob);
}
break;
case 'F': // functions
{
ut64 obs = core->blocksize;
ut64 offorig = core->offset;
RAnalFunction *fcn;
list = core->anal->fcns;
r_cons_break_push (NULL, NULL);
r_list_foreach (list, iter, fcn) {
if (r_cons_is_breaked ()) {
break;
}
if (!filter || r_str_glob (fcn->name, filter)) {
r_core_seek (core, fcn->addr, 1);
r_core_block_size (core, r_anal_fcn_size (fcn));
r_core_cmd0 (core, cmd);
}
}
r_cons_break_pop ();
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
break;
case 'b':
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
ut64 offorig = core->offset;
ut64 obs = core->blocksize;
if (fcn) {
RListIter *iter;
RAnalBlock *bb;
r_list_foreach (fcn->bbs, iter, bb) {
r_core_seek (core, bb->addr, 1);
r_core_block_size (core, bb->size);
r_core_cmd0 (core, cmd);
}
r_core_block_size (core, obs);
r_core_seek (core, offorig, 1);
}
}
break;
}
return 0;
}
static void foreachOffset(RCore *core, const char *_cmd, const char *each) {
char *cmd = strdup (_cmd);
char *nextLine = NULL;
ut64 addr;
/* foreach list of items */
while (each) {
// skip spaces
while (*each == ' ') {
each++;
}
// stahp if empty string
if (!*each) {
break;
}
// find newline
char *nl = strchr (each, '\n');
if (nl) {
*nl = 0;
nextLine = nl + 1;
} else {
nextLine = NULL;
}
// chop comment in line
nl = strchr (each, '#');
if (nl) {
*nl = 0;
}
// space separated numbers
while (each && *each) {
// find spaces
while (*each == ' ') {
each++;
}
char *str = strchr (each, ' ');
if (str) {
*str = '\0';
addr = r_num_math (core->num, each);
*str = ' ';
each = str + 1;
} else {
if (!*each) {
break;
}
addr = r_num_math (core->num, each);
each = NULL;
}
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd, 0);
r_cons_flush ();
}
each = nextLine;
}
free (cmd);
}
struct duplicate_flag_t {
RList *ret;
const char *word;
};
static bool duplicate_flag(RFlagItem *flag, void *u) {
struct duplicate_flag_t *user = (struct duplicate_flag_t *)u;
/* filter per flag spaces */
if (r_str_glob (flag->name, user->word)) {
RFlagItem *cloned_item = r_flag_item_clone (flag);
if (!cloned_item) {
return false;
}
r_list_append (user->ret, cloned_item);
}
return true;
}
R_API int r_core_cmd_foreach(RCore *core, const char *cmd, char *each) {
int i, j;
char ch;
char *word = NULL;
char *str, *ostr = NULL;
RListIter *iter;
RFlagItem *flag;
ut64 oseek, addr;
for (; *cmd == ' '; cmd++) {
;
}
oseek = core->offset;
ostr = str = strdup (each);
r_cons_break_push (NULL, NULL); //pop on return
switch (each[0]) {
case '/': // "@@/"
{
char *cmdhit = strdup (r_config_get (core->config, "cmd.hit"));
r_config_set (core->config, "cmd.hit", cmd);
r_core_cmd0 (core, each);
r_config_set (core->config, "cmd.hit", cmdhit);
free (cmdhit);
}
free (ostr);
return 0;
case '?': // "@@?"
r_core_cmd_help (core, help_msg_at_at);
break;
case 'b': // "@@b" - function basic blocks
{
RListIter *iter;
RAnalBlock *bb;
RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0);
int bs = core->blocksize;
if (fcn) {
r_list_sort (fcn->bbs, bb_cmp);
r_list_foreach (fcn->bbs, iter, bb) {
r_core_block_size (core, bb->size);
r_core_seek (core, bb->addr, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
}
r_core_block_size (core, bs);
goto out_finish;
}
break;
case 's': // "@@s" - sequence
{
char *str = each + 1;
if (*str == ':' || *str == ' ') {
str++;
}
int count = r_str_split (str, ' ');
if (count == 3) {
ut64 cur;
ut64 from = r_num_math (core->num, r_str_word_get0 (str, 0));
ut64 to = r_num_math (core->num, r_str_word_get0 (str, 1));
ut64 step = r_num_math (core->num, r_str_word_get0 (str, 2));
for (cur = from; cur < to; cur += step) {
(void)r_core_seek (core, cur, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
} else {
eprintf ("Usage: cmd @@s:from to step\n");
}
goto out_finish;
}
break;
case 'i': // "@@i" - function instructions
{
RListIter *iter;
RAnalBlock *bb;
int i;
RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, core->offset, 0);
if (fcn) {
r_list_sort (fcn->bbs, bb_cmp);
r_list_foreach (fcn->bbs, iter, bb) {
for (i = 0; i < bb->op_pos_size; i++) {
ut64 addr = bb->addr + bb->op_pos[i];
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
}
}
goto out_finish;
}
break;
case 'f': // "@@f"
if (each[1] == ':') {
RAnalFunction *fcn;
RListIter *iter;
if (core->anal) {
r_list_foreach (core->anal->fcns, iter, fcn) {
if (each[2] && strstr (fcn->name, each + 2)) {
r_core_seek (core, fcn->addr, 1);
r_core_cmd (core, cmd, 0);
if (r_cons_is_breaked ()) {
break;
}
}
}
}
goto out_finish;
} else {
RAnalFunction *fcn;
RListIter *iter;
if (core->anal) {
RConsGrep grep = core->cons->context->grep;
r_list_foreach (core->anal->fcns, iter, fcn) {
char *buf;
r_core_seek (core, fcn->addr, 1);
r_cons_push ();
r_core_cmd (core, cmd, 0);
buf = (char *)r_cons_get_buffer ();
if (buf) {
buf = strdup (buf);
}
r_cons_pop ();
r_cons_strcat (buf);
free (buf);
if (r_cons_is_breaked ()) {
break;
}
}
core->cons->context->grep = grep;
}
goto out_finish;
}
break;
case 't': // "@@t"
{
RDebugPid *p;
int pid = core->dbg->pid;
if (core->dbg->h && core->dbg->h->pids) {
RList *list = core->dbg->h->pids (core->dbg, R_MAX (0, pid));
r_list_foreach (list, iter, p) {
r_cons_printf ("# PID %d\n", p->pid);
r_debug_select (core->dbg, p->pid, p->pid);
r_core_cmd (core, cmd, 0);
r_cons_newline ();
}
r_list_free (list);
}
r_debug_select (core->dbg, pid, pid);
goto out_finish;
}
break;
case 'c': // "@@c:"
if (each[1] == ':') {
char *arg = r_core_cmd_str (core, each + 2);
if (arg) {
foreachOffset (core, cmd, arg);
free (arg);
}
}
break;
case '=': // "@@="
foreachOffset (core, cmd, str + 1);
break;
case 'd': // "@@d"
if (each[1] == 'b' && each[2] == 't') {
ut64 oseek = core->offset;
RDebugFrame *frame;
RListIter *iter;
RList *list;
list = r_debug_frames (core->dbg, UT64_MAX);
i = 0;
r_list_foreach (list, iter, frame) {
switch (each[3]) {
case 'b':
r_core_seek (core, frame->bp, 1);
break;
case 's':
r_core_seek (core, frame->sp, 1);
break;
default:
case 'a':
r_core_seek (core, frame->addr, 1);
break;
}
r_core_cmd (core, cmd, 0);
r_cons_newline ();
i++;
}
r_core_seek (core, oseek, 0);
r_list_free (list);
} else {
eprintf("Invalid for-each statement. Use @@=dbt[abs]\n");
}
break;
case 'k': // "@@k"
/* foreach list of items */
{
char *out = sdb_querys (core->sdb, NULL, 0, str + ((str[1])? 2: 1));
if (out) {
each = out;
do {
while (*each == ' ') {
each++;
}
if (!*each) {
break;
}
str = strchr (each, ' ');
if (str) {
*str = '\0';
addr = r_num_math (core->num, each);
*str = ' ';
} else {
addr = r_num_math (core->num, each);
}
//eprintf ("; 0x%08"PFMT64x":\n", addr);
each = str + 1;
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd, 0);
r_cons_flush ();
} while (str != NULL);
free (out);
}
}
break;
case '.': // "@@."
if (each[1] == '(') {
char cmd2[1024];
// XXX what's this 999 ?
i = 0;
for (core->rcmd->macro.counter = 0; i < 999; core->rcmd->macro.counter++) {
if (r_cons_is_breaked ()) {
break;
}
r_cmd_macro_call (&core->rcmd->macro, each + 2);
if (!core->rcmd->macro.brk_value) {
break;
}
addr = core->rcmd->macro._brk_value;
sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr);
eprintf ("0x%08"PFMT64x" (%s)\n", addr, cmd2);
r_core_seek (core, addr, 1);
r_core_cmd (core, cmd2, 0);
i++;
}
} else {
char buf[1024];
char cmd2[1024];
FILE *fd = r_sandbox_fopen (each + 1, "r");
if (fd) {
core->rcmd->macro.counter = 0;
while (!feof (fd)) {
buf[0] = '\0';
if (!fgets (buf, sizeof (buf), fd)) {
break;
}
addr = r_num_math (core->num, buf);
eprintf ("0x%08"PFMT64x": %s\n", addr, cmd);
sprintf (cmd2, "%s @ 0x%08"PFMT64x"", cmd, addr);
r_core_seek (core, addr, 1); // XXX
r_core_cmd (core, cmd2, 0);
core->rcmd->macro.counter++;
}
fclose (fd);
} else {
eprintf ("cannot open file '%s' to read offsets\n", each + 1);
}
}
break;
default:
core->rcmd->macro.counter = 0;
for (; *each == ' '; each++) {
;
}
i = 0;
while (str[i]) {
j = i;
for (; str[j] && str[j] == ' '; j++) {
; // skip spaces
}
for (i = j; str[i] && str[i] != ' '; i++) {
; // find EOS
}
ch = str[i];
str[i] = '\0';
word = strdup (str + j);
if (!word) {
break;
}
str[i] = ch;
{
const RSpace *flagspace = r_flag_space_cur (core->flags);
RList *match_flag_items = r_list_newf ((RListFree)r_flag_item_free);
if (!match_flag_items) {
break;
}
/* duplicate flags that match word, to be sure
the command is going to be executed on flags
values at the moment the command is called
(without side effects) */
struct duplicate_flag_t u = {
.ret = match_flag_items,
.word = word,
};
r_flag_foreach_space (core->flags, flagspace, duplicate_flag, &u);
/* for all flags that match */
r_list_foreach (match_flag_items, iter, flag) {
if (r_cons_is_breaked ()) {
break;
}
char *buf = NULL;
const char *tmp = NULL;
r_core_seek (core, flag->offset, 1);
r_cons_push ();
r_core_cmd (core, cmd, 0);
tmp = r_cons_get_buffer ();
buf = tmp? strdup (tmp): NULL;
r_cons_pop ();
r_cons_strcat (buf);
free (buf);
}
r_list_free (match_flag_items);
core->rcmd->macro.counter++ ;
R_FREE (word);
}
}
}
r_cons_break_pop ();
// XXX: use r_core_seek here
core->offset = oseek;
free (word);
free (ostr);
return true;
out_finish:
free (ostr);
r_cons_break_pop ();
return false;
}
R_API void run_pending_anal(RCore *core) {
// allow incall events in the run_pending step
core->ev->incall = false;
if (core && core->anal && core->anal->cmdtail) {
char *res = core->anal->cmdtail;
core->anal->cmdtail = NULL;
r_core_cmd_lines (core, res);
free (res);
}
}
R_API int r_core_cmd(RCore *core, const char *cstr, int log) {
char *cmd, *ocmd, *ptr, *rcmd;
int ret = false, i;
if (core->cmdfilter) {
const char *invalid_chars = ";|>`@";
for (i = 0; invalid_chars[i]; i++) {
if (strchr (cstr, invalid_chars[i])) {
ret = true;
goto beach;
}
}
if (strncmp (cstr, core->cmdfilter, strlen (core->cmdfilter))) {
ret = true;
goto beach;
}
}
if (core->cmdremote) {
if (*cstr != '=' && *cstr != 'q' && strncmp (cstr, "!=", 2)) {
char *res = r_io_system (core->io, cstr);
if (res) {
r_cons_printf ("%s\n", res);
free (res);
}
goto beach; // false
}
}
if (!cstr || (*cstr == '|' && cstr[1] != '?')) {
// raw comment syntax
goto beach; // false;
}
if (!strncmp (cstr, "/*", 2)) {
if (r_sandbox_enable (0)) {
eprintf ("This command is disabled in sandbox mode\n");
goto beach; // false
}
core->incomment = true;
} else if (!strncmp (cstr, "*/", 2)) {
core->incomment = false;
goto beach; // false
}
if (core->incomment) {
goto beach; // false
}
if (log && (*cstr && (*cstr != '.' || !strncmp (cstr, ".(", 2)))) {
free (core->lastcmd);
core->lastcmd = strdup (cstr);
}
ocmd = cmd = malloc (strlen (cstr) + 4096);
if (!ocmd) {
goto beach;
}
r_str_cpy (cmd, cstr);
if (log) {
r_line_hist_add (cstr);
}
if (core->cons->context->cmd_depth < 1) {
eprintf ("r_core_cmd: That was too deep (%s)...\n", cmd);
free (ocmd);
R_FREE (core->oobi);
core->oobi_len = 0;
goto beach;
}
core->cons->context->cmd_depth--;
for (rcmd = cmd;;) {
ptr = strchr (rcmd, '\n');
if (ptr) {
*ptr = '\0';
}
ret = r_core_cmd_subst (core, rcmd);
if (ret == -1) {
eprintf ("|ERROR| Invalid command '%s' (0x%02x)\n", rcmd, *rcmd);
break;
}
if (!ptr) {
break;
}
rcmd = ptr + 1;
}
/* run pending analysis commands */
run_pending_anal (core);
core->cons->context->cmd_depth++;
free (ocmd);
R_FREE (core->oobi);
core->oobi_len = 0;
return ret;
beach:
if (r_list_empty (core->tasks)) {
r_th_lock_leave (core->lock);
} else {
RListIter *iter;
RCoreTask *task;
r_list_foreach (core->tasks, iter, task) {
r_th_pause (task->thread, false);
}
}
/* run pending analysis commands */
run_pending_anal (core);
return ret;
}
R_API int r_core_cmd_lines(RCore *core, const char *lines) {
int r, ret = true;
char *nl, *data, *odata;
if (!lines || !*lines) {
return true;
}
data = odata = strdup (lines);
if (!odata) {
return false;
}
nl = strchr (odata, '\n');
if (nl) {
r_cons_break_push (NULL, NULL);
do {
if (r_cons_is_breaked ()) {
free (odata);
r_cons_break_pop ();
return ret;
}
*nl = '\0';
r = r_core_cmd (core, data, 0);
if (r < 0) { //== -1) {
data = nl + 1;
ret = -1; //r; //false;
break;
}
r_cons_flush ();
if (data[0] == 'q') {
if (data[1] == '!') {
ret = -1;
} else {
eprintf ("'q': quit ignored. Use 'q!'\n");
}
data = nl + 1;
break;
}
data = nl + 1;
} while ((nl = strchr (data, '\n')));
r_cons_break_pop ();
}
if (ret >= 0 && data && *data) {
r_core_cmd (core, data, 0);
}
free (odata);
return ret;
}
R_API int r_core_cmd_file(RCore *core, const char *file) {
char *data = r_file_abspath (file);
if (!data) {
return false;
}
char *odata = r_file_slurp (data, NULL);
free (data);
if (!odata) {
return false;
}
if (!r_core_cmd_lines (core, odata)) {
eprintf ("Failed to run script '%s'\n", file);
free (odata);
return false;
}
free (odata);
return true;
}
R_API int r_core_cmd_command(RCore *core, const char *command) {
int ret, len;
char *buf, *rcmd, *ptr;
char *cmd = r_core_sysenv_begin (core, command);
rcmd = ptr = buf = r_sys_cmd_str (cmd, 0, &len);
if (!buf) {
free (cmd);
return -1;
}
ret = r_core_cmd (core, rcmd, 0);
r_core_sysenv_end (core, command);
free (buf);
return ret;
}
//TODO: Fix disasm loop is mandatory
R_API char *r_core_disassemble_instr(RCore *core, ut64 addr, int l) {
char *cmd, *ret = NULL;
cmd = r_str_newf ("pd %i @ 0x%08"PFMT64x, l, addr);
if (cmd) {
ret = r_core_cmd_str (core, cmd);
free (cmd);
}
return ret;
}
R_API char *r_core_disassemble_bytes(RCore *core, ut64 addr, int b) {
char *cmd, *ret = NULL;
cmd = r_str_newf ("pD %i @ 0x%08"PFMT64x, b, addr);
if (cmd) {
ret = r_core_cmd_str (core, cmd);
free (cmd);
}
return ret;
}
R_API int r_core_cmd_buffer(RCore *core, const char *buf) {
char *ptr, *optr, *str = strdup (buf);
if (!str) {
return false;
}
optr = str;
ptr = strchr (str, '\n');
while (ptr) {
*ptr = '\0';
r_core_cmd (core, optr, 0);
optr = ptr + 1;
ptr = strchr (str, '\n');
}
r_core_cmd (core, optr, 0);
free (str);
return true;
}
R_API int r_core_cmdf(RCore *core, const char *fmt, ...) {
char string[4096];
int ret;
va_list ap;
va_start (ap, fmt);
vsnprintf (string, sizeof (string), fmt, ap);
ret = r_core_cmd (core, string, 0);
va_end (ap);
return ret;
}
R_API int r_core_cmd0(RCore *core, const char *cmd) {
return r_core_cmd (core, cmd, 0);
}
R_API int r_core_flush(RCore *core, const char *cmd) {
int ret = r_core_cmd (core, cmd, 0);
r_cons_flush ();
return ret;
}
R_API char *r_core_cmd_str_pipe(RCore *core, const char *cmd) {
char *s, *tmp = NULL;
if (r_sandbox_enable (0)) {
char *p = (*cmd != '"')? strchr (cmd, '|'): NULL;
if (p) {
// This code works but its pretty ugly as its a workaround to
// make the webserver work as expected, this was broken some
// weeks. let's use this hackaround for now
char *c = strdup (cmd);
c[p - cmd] = 0;
if (!strcmp (p + 1, "H")) {
char *res = r_core_cmd_str (core, c);
free (c);
char *hres = r_cons_html_filter (res, NULL);
free (res);
return hres;
} else {
int sh = r_config_get_i (core->config, "scr.color");
r_config_set_i (core->config, "scr.color", 0);
char *ret = r_core_cmd_str (core, c);
r_config_set_i (core->config, "scr.color", sh);
free (c);
return ret;
}
}
return r_core_cmd_str (core, cmd);
}
r_cons_reset ();
r_sandbox_disable (1);
if (r_file_mkstemp ("cmd", &tmp) != -1) {
int pipefd = r_cons_pipe_open (tmp, 1, 0);
if (pipefd == -1) {
r_file_rm (tmp);
r_sandbox_disable (0);
free (tmp);
return r_core_cmd_str (core, cmd);
}
char *_cmd = strdup (cmd);
r_core_cmd_subst (core, _cmd);
r_cons_flush ();
r_cons_pipe_close (pipefd);
s = r_file_slurp (tmp, NULL);
if (s) {
r_file_rm (tmp);
r_sandbox_disable (0);
free (tmp);
free (_cmd);
return s;
}
eprintf ("slurp %s fails\n", tmp);
r_file_rm (tmp);
free (tmp);
free (_cmd);
r_sandbox_disable (0);
return r_core_cmd_str (core, cmd);
}
r_sandbox_disable (0);
return NULL;
}
R_API char *r_core_cmd_strf(RCore *core, const char *fmt, ...) {
char string[4096];
char *ret;
va_list ap;
va_start (ap, fmt);
vsnprintf (string, sizeof (string), fmt, ap);
ret = r_core_cmd_str (core, string);
va_end (ap);
return ret;
}
/* return: pointer to a buffer with the output of the command */
R_API char *r_core_cmd_str(RCore *core, const char *cmd) {
const char *static_str;
char *retstr = NULL;
r_cons_push ();
if (r_core_cmd (core, cmd, 0) == -1) {
//eprintf ("Invalid command: %s\n", cmd);
return NULL;
}
r_cons_filter ();
static_str = r_cons_get_buffer ();
retstr = strdup (static_str? static_str: "");
r_cons_pop ();
r_cons_echo (NULL);
return retstr;
}
R_API void r_core_cmd_repeat(RCore *core, int next) {
// Fix for backtickbug px`~`
if (!core->lastcmd || core->cons->context->cmd_depth < 1) {
return;
}
switch (*core->lastcmd) {
case '.':
if (core->lastcmd[1] == '(') { // macro call
r_core_cmd0 (core, core->lastcmd);
}
break;
case 'd': // debug
r_core_cmd0 (core, core->lastcmd);
switch (core->lastcmd[1]) {
case 's':
case 'c':
r_core_cmd0 (core, "sr PC;pd 1");
}
break;
case 'p': // print
case 'x':
case '$':
if (!strncmp (core->lastcmd, "pd", 2)) {
if (core->lastcmd[2]== ' ') {
r_core_cmdf (core, "so %s", core->lastcmd + 3);
} else {
r_core_cmd0 (core, "so `pi~?`");
}
} else {
if (next) {
r_core_seek (core, core->offset + core->blocksize, 1);
} else {
if (core->blocksize > core->offset) {
r_core_seek (core, 0, 1);
} else {
r_core_seek (core, core->offset - core->blocksize, 1);
}
}
}
r_core_cmd0 (core, core->lastcmd);
break;
}
}
/* run cmd in the main task synchronously */
R_API int r_core_cmd_task_sync(RCore *core, const char *cmd, bool log) {
RCoreTask *task = core->main_task;
char *s = strdup (cmd);
if (!s) {
return 0;
}
task->cmd = s;
task->cmd_log = log;
task->state = R_CORE_TASK_STATE_BEFORE_START;
int res = r_core_task_run_sync (core, task);
free (s);
return res;
}
static int cmd_ox(void *data, const char *input) {
return r_core_cmdf ((RCore*)data, "s 0%s", input);
}
static int compare_cmd_descriptor_name(const void *a, const void *b) {
return strcmp (((RCmdDescriptor *)a)->cmd, ((RCmdDescriptor *)b)->cmd);
}
static void cmd_descriptor_init(RCore *core) {
const ut8 *p;
RListIter *iter;
RCmdDescriptor *x, *y;
int n = core->cmd_descriptors->length;
r_list_sort (core->cmd_descriptors, compare_cmd_descriptor_name);
r_list_foreach (core->cmd_descriptors, iter, y) {
if (--n < 0) {
break;
}
x = &core->root_cmd_descriptor;
for (p = (const ut8 *)y->cmd; *p; p++) {
if (!x->sub[*p]) {
if (p[1]) {
RCmdDescriptor *d = R_NEW0 (RCmdDescriptor);
r_list_append (core->cmd_descriptors, d);
x->sub[*p] = d;
} else {
x->sub[*p] = y;
}
} else if (!p[1]) {
eprintf ("Command '%s' is duplicated, please check\n", y->cmd);
}
x = x->sub[*p];
}
}
}
static int core_cmd0_wrapper(void *core, const char *cmd) {
return r_core_cmd0 ((RCore *)core, cmd);
}
R_API void r_core_cmd_init(RCore *core) {
struct {
const char *cmd;
const char *description;
r_cmd_callback (cb);
void (*descriptor_init)(RCore *core);
} cmds[] = {
{"!", "run system command", cmd_system},
{"_", "print last output", cmd_last},
{"#", "calculate hash", cmd_hash},
{"$", "alias", cmd_alias},
{"%", "short version of 'env' command", cmd_env},
{"&", "tasks", cmd_tasks},
{"(", "macro", cmd_macro, cmd_macro_init},
{"*", "pointer read/write", cmd_pointer},
{"-", "open cfg.editor and run script", cmd_stdin},
{".", "interpret", cmd_interpret},
{"/", "search kw, pattern aes", cmd_search, cmd_search_init},
{"=", "io pipe", cmd_rap},
{"?", "help message", cmd_help, cmd_help_init},
{"\\", "alias for =!", cmd_rap_run},
{"'", "alias for =!", cmd_rap_run},
{"0x", "alias for s 0x", cmd_ox},
{"analysis", "analysis", cmd_anal, cmd_anal_init},
{"bsize", "change block size", cmd_bsize},
{"cmp", "compare memory", cmd_cmp, cmd_cmp_init},
{"Code", "code metadata", cmd_meta, cmd_meta_init},
{"debug", "debugger operations", cmd_debug, cmd_debug_init},
{"eval", "evaluate configuration variable", cmd_eval, cmd_eval_init},
{"flag", "get/set flags", cmd_flag, cmd_flag_init},
{"g", "egg manipulation", cmd_egg, cmd_egg_init},
{"info", "get file info", cmd_info, cmd_info_init},
{"kuery", "perform sdb query", cmd_kuery},
{"l", "list files and directories", cmd_ls},
{"join", "join the contents of the two files", cmd_join},
{"head", "show the top n number of line in file", cmd_head},
{"L", "manage dynamically loaded plugins", cmd_plugins},
{"mount", "mount filesystem", cmd_mount, cmd_mount_init},
{"open", "open or map file", cmd_open, cmd_open_init},
{"print", "print current block", cmd_print, cmd_print_init},
{"Project", "project", cmd_project, cmd_project_init},
{"quit", "exit program session", cmd_quit, cmd_quit_init},
{"Q", "alias for q!", cmd_Quit},
{":", "long commands starting with :", cmd_colon},
{"resize", "change file size", cmd_resize},
{"seek", "seek to an offset", cmd_seek, cmd_seek_init},
{"t", "type information (cparse)", cmd_type, cmd_type_init},
{"Text", "Text log utility", cmd_log, cmd_log_init},
{"u", "uname/undo", cmd_uname},
{"<", "pipe into RCons.readChar", cmd_pipein},
{"Visual", "enter visual mode", cmd_visual},
{"visualPanels", "enter visual mode", cmd_panels},
{"write", "write bytes", cmd_write, cmd_write_init},
{"x", "alias for px", cmd_hexdump},
{"yank", "yank bytes", cmd_yank},
{"zign", "zignatures", cmd_zign, cmd_zign_init},
};
core->rcmd = r_cmd_new ();
core->rcmd->macro.user = core;
core->rcmd->macro.num = core->num;
core->rcmd->macro.cmd = core_cmd0_wrapper;
core->rcmd->nullcallback = r_core_cmd_nullcallback;
core->rcmd->macro.cb_printf = (PrintfCallback)r_cons_printf;
r_cmd_set_data (core->rcmd, core);
core->cmd_descriptors = r_list_newf (free);
int i;
for (i = 0; i < R_ARRAY_SIZE (cmds); i++) {
r_cmd_add (core->rcmd, cmds[i].cmd, cmds[i].description, cmds[i].cb);
if (cmds[i].descriptor_init) {
cmds[i].descriptor_init (core);
}
}
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, $, dollar);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, %, percent);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, *, star);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, ., dot);
DEFINE_CMD_DESCRIPTOR_SPECIAL (core, =, equal);
DEFINE_CMD_DESCRIPTOR (core, b);
DEFINE_CMD_DESCRIPTOR (core, k);
DEFINE_CMD_DESCRIPTOR (core, r);
DEFINE_CMD_DESCRIPTOR (core, u);
DEFINE_CMD_DESCRIPTOR (core, y);
cmd_descriptor_init (core);
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/bad_1104_0 |
crossvul-cpp_data_good_882_2 | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
#include "vim.h"
#ifdef AMIGA
# include <time.h> /* for time() */
#endif
/*
* Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)
* It has been changed beyond recognition since then.
*
* Differences between version 7.4 and 8.x can be found with ":help version8".
* Differences between version 6.4 and 7.x can be found with ":help version7".
* Differences between version 5.8 and 6.x can be found with ":help version6".
* Differences between version 4.x and 5.x can be found with ":help version5".
* Differences between version 3.0 and 4.x can be found with ":help version4".
* All the remarks about older versions have been removed, they are not very
* interesting.
*/
#include "version.h"
char *Version = VIM_VERSION_SHORT;
static char *mediumVersion = VIM_VERSION_MEDIUM;
#if defined(HAVE_DATE_TIME) || defined(PROTO)
# if (defined(VMS) && defined(VAXC)) || defined(PROTO)
char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)
+ sizeof(__TIME__) + 3];
void
init_longVersion(void)
{
/*
* Construct the long version string. Necessary because
* VAX C can't concatenate strings in the preprocessor.
*/
strcpy(longVersion, VIM_VERSION_LONG_DATE);
strcat(longVersion, __DATE__);
strcat(longVersion, " ");
strcat(longVersion, __TIME__);
strcat(longVersion, ")");
}
# else
void
init_longVersion(void)
{
char *date_time = __DATE__ " " __TIME__;
char *msg = _("%s (%s, compiled %s)");
size_t len = strlen(msg)
+ strlen(VIM_VERSION_LONG_ONLY)
+ strlen(VIM_VERSION_DATE_ONLY)
+ strlen(date_time);
longVersion = (char *)alloc((unsigned)len);
if (longVersion == NULL)
longVersion = VIM_VERSION_LONG;
else
vim_snprintf(longVersion, len, msg,
VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);
}
# endif
#else
char *longVersion = VIM_VERSION_LONG;
void
init_longVersion(void)
{
// nothing to do
}
#endif
static char *(features[]) =
{
#ifdef HAVE_ACL
"+acl",
#else
"-acl",
#endif
#ifdef AMIGA /* only for Amiga systems */
# ifdef FEAT_ARP
"+ARP",
# else
"-ARP",
# endif
#endif
#ifdef FEAT_ARABIC
"+arabic",
#else
"-arabic",
#endif
"+autocmd",
#ifdef FEAT_AUTOCHDIR
"+autochdir",
#else
"-autochdir",
#endif
#ifdef FEAT_AUTOSERVERNAME
"+autoservername",
#else
"-autoservername",
#endif
#ifdef FEAT_BEVAL_GUI
"+balloon_eval",
#else
"-balloon_eval",
#endif
#ifdef FEAT_BEVAL_TERM
"+balloon_eval_term",
#else
"-balloon_eval_term",
#endif
#ifdef FEAT_BROWSE
"+browse",
#else
"-browse",
#endif
#ifdef NO_BUILTIN_TCAPS
"-builtin_terms",
#endif
#ifdef SOME_BUILTIN_TCAPS
"+builtin_terms",
#endif
#ifdef ALL_BUILTIN_TCAPS
"++builtin_terms",
#endif
#ifdef FEAT_BYTEOFF
"+byte_offset",
#else
"-byte_offset",
#endif
#ifdef FEAT_JOB_CHANNEL
"+channel",
#else
"-channel",
#endif
#ifdef FEAT_CINDENT
"+cindent",
#else
"-cindent",
#endif
#ifdef FEAT_CLIENTSERVER
"+clientserver",
#else
"-clientserver",
#endif
#ifdef FEAT_CLIPBOARD
"+clipboard",
#else
"-clipboard",
#endif
#ifdef FEAT_CMDL_COMPL
"+cmdline_compl",
#else
"-cmdline_compl",
#endif
#ifdef FEAT_CMDHIST
"+cmdline_hist",
#else
"-cmdline_hist",
#endif
#ifdef FEAT_CMDL_INFO
"+cmdline_info",
#else
"-cmdline_info",
#endif
#ifdef FEAT_COMMENTS
"+comments",
#else
"-comments",
#endif
#ifdef FEAT_CONCEAL
"+conceal",
#else
"-conceal",
#endif
#ifdef FEAT_CRYPT
"+cryptv",
#else
"-cryptv",
#endif
#ifdef FEAT_CSCOPE
"+cscope",
#else
"-cscope",
#endif
"+cursorbind",
#ifdef CURSOR_SHAPE
"+cursorshape",
#else
"-cursorshape",
#endif
#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)
"+dialog_con_gui",
#else
# if defined(FEAT_CON_DIALOG)
"+dialog_con",
# else
# if defined(FEAT_GUI_DIALOG)
"+dialog_gui",
# else
"-dialog",
# endif
# endif
#endif
#ifdef FEAT_DIFF
"+diff",
#else
"-diff",
#endif
#ifdef FEAT_DIGRAPHS
"+digraphs",
#else
"-digraphs",
#endif
#ifdef FEAT_GUI_MSWIN
# ifdef FEAT_DIRECTX
"+directx",
# else
"-directx",
# endif
#endif
#ifdef FEAT_DND
"+dnd",
#else
"-dnd",
#endif
#ifdef EBCDIC
"+ebcdic",
#else
"-ebcdic",
#endif
#ifdef FEAT_EMACS_TAGS
"+emacs_tags",
#else
"-emacs_tags",
#endif
#ifdef FEAT_EVAL
"+eval",
#else
"-eval",
#endif
"+ex_extra",
#ifdef FEAT_SEARCH_EXTRA
"+extra_search",
#else
"-extra_search",
#endif
"-farsi",
#ifdef FEAT_SEARCHPATH
"+file_in_path",
#else
"-file_in_path",
#endif
#ifdef FEAT_FIND_ID
"+find_in_path",
#else
"-find_in_path",
#endif
#ifdef FEAT_FLOAT
"+float",
#else
"-float",
#endif
#ifdef FEAT_FOLDING
"+folding",
#else
"-folding",
#endif
#ifdef FEAT_FOOTER
"+footer",
#else
"-footer",
#endif
/* only interesting on Unix systems */
#if !defined(USE_SYSTEM) && defined(UNIX)
"+fork()",
#endif
#ifdef FEAT_GETTEXT
# ifdef DYNAMIC_GETTEXT
"+gettext/dyn",
# else
"+gettext",
# endif
#else
"-gettext",
#endif
#ifdef FEAT_HANGULIN
"+hangul_input",
#else
"-hangul_input",
#endif
#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)
# ifdef DYNAMIC_ICONV
"+iconv/dyn",
# else
"+iconv",
# endif
#else
"-iconv",
#endif
#ifdef FEAT_INS_EXPAND
"+insert_expand",
#else
"-insert_expand",
#endif
#ifdef FEAT_JOB_CHANNEL
"+job",
#else
"-job",
#endif
#ifdef FEAT_JUMPLIST
"+jumplist",
#else
"-jumplist",
#endif
#ifdef FEAT_KEYMAP
"+keymap",
#else
"-keymap",
#endif
#ifdef FEAT_EVAL
"+lambda",
#else
"-lambda",
#endif
#ifdef FEAT_LANGMAP
"+langmap",
#else
"-langmap",
#endif
#ifdef FEAT_LIBCALL
"+libcall",
#else
"-libcall",
#endif
#ifdef FEAT_LINEBREAK
"+linebreak",
#else
"-linebreak",
#endif
#ifdef FEAT_LISP
"+lispindent",
#else
"-lispindent",
#endif
"+listcmds",
#ifdef FEAT_LOCALMAP
"+localmap",
#else
"-localmap",
#endif
#ifdef FEAT_LUA
# ifdef DYNAMIC_LUA
"+lua/dyn",
# else
"+lua",
# endif
#else
"-lua",
#endif
#ifdef FEAT_MENU
"+menu",
#else
"-menu",
#endif
#ifdef FEAT_SESSION
"+mksession",
#else
"-mksession",
#endif
#ifdef FEAT_MODIFY_FNAME
"+modify_fname",
#else
"-modify_fname",
#endif
#ifdef FEAT_MOUSE
"+mouse",
# ifdef FEAT_MOUSESHAPE
"+mouseshape",
# else
"-mouseshape",
# endif
# else
"-mouse",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_MOUSE_DEC
"+mouse_dec",
# else
"-mouse_dec",
# endif
# ifdef FEAT_MOUSE_GPM
"+mouse_gpm",
# else
"-mouse_gpm",
# endif
# ifdef FEAT_MOUSE_JSB
"+mouse_jsbterm",
# else
"-mouse_jsbterm",
# endif
# ifdef FEAT_MOUSE_NET
"+mouse_netterm",
# else
"-mouse_netterm",
# endif
#endif
#ifdef __QNX__
# ifdef FEAT_MOUSE_PTERM
"+mouse_pterm",
# else
"-mouse_pterm",
# endif
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_MOUSE_XTERM
"+mouse_sgr",
# else
"-mouse_sgr",
# endif
# ifdef FEAT_SYSMOUSE
"+mouse_sysmouse",
# else
"-mouse_sysmouse",
# endif
# ifdef FEAT_MOUSE_URXVT
"+mouse_urxvt",
# else
"-mouse_urxvt",
# endif
# ifdef FEAT_MOUSE_XTERM
"+mouse_xterm",
# else
"-mouse_xterm",
# endif
#endif
#ifdef FEAT_MBYTE_IME
# ifdef DYNAMIC_IME
"+multi_byte_ime/dyn",
# else
"+multi_byte_ime",
# endif
#else
"+multi_byte",
#endif
#ifdef FEAT_MULTI_LANG
"+multi_lang",
#else
"-multi_lang",
#endif
#ifdef FEAT_MZSCHEME
# ifdef DYNAMIC_MZSCHEME
"+mzscheme/dyn",
# else
"+mzscheme",
# endif
#else
"-mzscheme",
#endif
#ifdef FEAT_NETBEANS_INTG
"+netbeans_intg",
#else
"-netbeans_intg",
#endif
#ifdef FEAT_NUM64
"+num64",
#else
"-num64",
#endif
#ifdef FEAT_GUI_MSWIN
# ifdef FEAT_OLE
"+ole",
# else
"-ole",
# endif
#endif
#ifdef FEAT_EVAL
"+packages",
#else
"-packages",
#endif
#ifdef FEAT_PATH_EXTRA
"+path_extra",
#else
"-path_extra",
#endif
#ifdef FEAT_PERL
# ifdef DYNAMIC_PERL
"+perl/dyn",
# else
"+perl",
# endif
#else
"-perl",
#endif
#ifdef FEAT_PERSISTENT_UNDO
"+persistent_undo",
#else
"-persistent_undo",
#endif
#ifdef FEAT_PRINTER
# ifdef FEAT_POSTSCRIPT
"+postscript",
# else
"-postscript",
# endif
"+printer",
#else
"-printer",
#endif
#ifdef FEAT_PROFILE
"+profile",
#else
"-profile",
#endif
#ifdef FEAT_PYTHON
# ifdef DYNAMIC_PYTHON
"+python/dyn",
# else
"+python",
# endif
#else
"-python",
#endif
#ifdef FEAT_PYTHON3
# ifdef DYNAMIC_PYTHON3
"+python3/dyn",
# else
"+python3",
# endif
#else
"-python3",
#endif
#ifdef FEAT_QUICKFIX
"+quickfix",
#else
"-quickfix",
#endif
#ifdef FEAT_RELTIME
"+reltime",
#else
"-reltime",
#endif
#ifdef FEAT_RIGHTLEFT
"+rightleft",
#else
"-rightleft",
#endif
#ifdef FEAT_RUBY
# ifdef DYNAMIC_RUBY
"+ruby/dyn",
# else
"+ruby",
# endif
#else
"-ruby",
#endif
"+scrollbind",
#ifdef FEAT_SIGNS
"+signs",
#else
"-signs",
#endif
#ifdef FEAT_SMARTINDENT
"+smartindent",
#else
"-smartindent",
#endif
#ifdef STARTUPTIME
"+startuptime",
#else
"-startuptime",
#endif
#ifdef FEAT_STL_OPT
"+statusline",
#else
"-statusline",
#endif
"-sun_workshop",
#ifdef FEAT_SYN_HL
"+syntax",
#else
"-syntax",
#endif
/* only interesting on Unix systems */
#if defined(USE_SYSTEM) && defined(UNIX)
"+system()",
#endif
#ifdef FEAT_TAG_BINS
"+tag_binary",
#else
"-tag_binary",
#endif
"-tag_old_static",
"-tag_any_white",
#ifdef FEAT_TCL
# ifdef DYNAMIC_TCL
"+tcl/dyn",
# else
"+tcl",
# endif
#else
"-tcl",
#endif
#ifdef FEAT_TERMGUICOLORS
"+termguicolors",
#else
"-termguicolors",
#endif
#ifdef FEAT_TERMINAL
"+terminal",
#else
"-terminal",
#endif
#if defined(UNIX)
/* only Unix can have terminfo instead of termcap */
# ifdef TERMINFO
"+terminfo",
# else
"-terminfo",
# endif
#endif
#ifdef FEAT_TERMRESPONSE
"+termresponse",
#else
"-termresponse",
#endif
#ifdef FEAT_TEXTOBJ
"+textobjects",
#else
"-textobjects",
#endif
#ifdef FEAT_TEXT_PROP
"+textprop",
#else
"-textprop",
#endif
#if !defined(UNIX)
/* unix always includes termcap support */
# ifdef HAVE_TGETENT
"+tgetent",
# else
"-tgetent",
# endif
#endif
#ifdef FEAT_TIMERS
"+timers",
#else
"-timers",
#endif
#ifdef FEAT_TITLE
"+title",
#else
"-title",
#endif
#ifdef FEAT_TOOLBAR
"+toolbar",
#else
"-toolbar",
#endif
"+user_commands",
#ifdef FEAT_VARTABS
"+vartabs",
#else
"-vartabs",
#endif
"+vertsplit",
"+virtualedit",
"+visual",
"+visualextra",
#ifdef FEAT_VIMINFO
"+viminfo",
#else
"-viminfo",
#endif
"+vreplace",
#ifdef MSWIN
# ifdef FEAT_VTP
"+vtp",
# else
"-vtp",
# endif
#endif
#ifdef FEAT_WILDIGN
"+wildignore",
#else
"-wildignore",
#endif
#ifdef FEAT_WILDMENU
"+wildmenu",
#else
"-wildmenu",
#endif
"+windows",
#ifdef FEAT_WRITEBACKUP
"+writebackup",
#else
"-writebackup",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_X11
"+X11",
# else
"-X11",
# endif
#endif
#ifdef FEAT_XFONTSET
"+xfontset",
#else
"-xfontset",
#endif
#ifdef FEAT_XIM
"+xim",
#else
"-xim",
#endif
#ifdef MSWIN
# ifdef FEAT_XPM_W32
"+xpm_w32",
# else
"-xpm_w32",
# endif
#else
# ifdef HAVE_XPM
"+xpm",
# else
"-xpm",
# endif
#endif
#if defined(UNIX) || defined(VMS)
# ifdef USE_XSMP_INTERACT
"+xsmp_interact",
# else
# ifdef USE_XSMP
"+xsmp",
# else
"-xsmp",
# endif
# endif
# ifdef FEAT_XCLIPBOARD
"+xterm_clipboard",
# else
"-xterm_clipboard",
# endif
#endif
#ifdef FEAT_XTERM_SAVE
"+xterm_save",
#else
"-xterm_save",
#endif
NULL
};
static int included_patches[] =
{ /* Add new patch number below this line */
/**/
1365,
/**/
1364,
/**/
1363,
/**/
1362,
/**/
1361,
/**/
1360,
/**/
1359,
/**/
1358,
/**/
1357,
/**/
1356,
/**/
1355,
/**/
1354,
/**/
1353,
/**/
1352,
/**/
1351,
/**/
1350,
/**/
1349,
/**/
1348,
/**/
1347,
/**/
1346,
/**/
1345,
/**/
1344,
/**/
1343,
/**/
1342,
/**/
1341,
/**/
1340,
/**/
1339,
/**/
1338,
/**/
1337,
/**/
1336,
/**/
1335,
/**/
1334,
/**/
1333,
/**/
1332,
/**/
1331,
/**/
1330,
/**/
1329,
/**/
1328,
/**/
1327,
/**/
1326,
/**/
1325,
/**/
1324,
/**/
1323,
/**/
1322,
/**/
1321,
/**/
1320,
/**/
1319,
/**/
1318,
/**/
1317,
/**/
1316,
/**/
1315,
/**/
1314,
/**/
1313,
/**/
1312,
/**/
1311,
/**/
1310,
/**/
1309,
/**/
1308,
/**/
1307,
/**/
1306,
/**/
1305,
/**/
1304,
/**/
1303,
/**/
1302,
/**/
1301,
/**/
1300,
/**/
1299,
/**/
1298,
/**/
1297,
/**/
1296,
/**/
1295,
/**/
1294,
/**/
1293,
/**/
1292,
/**/
1291,
/**/
1290,
/**/
1289,
/**/
1288,
/**/
1287,
/**/
1286,
/**/
1285,
/**/
1284,
/**/
1283,
/**/
1282,
/**/
1281,
/**/
1280,
/**/
1279,
/**/
1278,
/**/
1277,
/**/
1276,
/**/
1275,
/**/
1274,
/**/
1273,
/**/
1272,
/**/
1271,
/**/
1270,
/**/
1269,
/**/
1268,
/**/
1267,
/**/
1266,
/**/
1265,
/**/
1264,
/**/
1263,
/**/
1262,
/**/
1261,
/**/
1260,
/**/
1259,
/**/
1258,
/**/
1257,
/**/
1256,
/**/
1255,
/**/
1254,
/**/
1253,
/**/
1252,
/**/
1251,
/**/
1250,
/**/
1249,
/**/
1248,
/**/
1247,
/**/
1246,
/**/
1245,
/**/
1244,
/**/
1243,
/**/
1242,
/**/
1241,
/**/
1240,
/**/
1239,
/**/
1238,
/**/
1237,
/**/
1236,
/**/
1235,
/**/
1234,
/**/
1233,
/**/
1232,
/**/
1231,
/**/
1230,
/**/
1229,
/**/
1228,
/**/
1227,
/**/
1226,
/**/
1225,
/**/
1224,
/**/
1223,
/**/
1222,
/**/
1221,
/**/
1220,
/**/
1219,
/**/
1218,
/**/
1217,
/**/
1216,
/**/
1215,
/**/
1214,
/**/
1213,
/**/
1212,
/**/
1211,
/**/
1210,
/**/
1209,
/**/
1208,
/**/
1207,
/**/
1206,
/**/
1205,
/**/
1204,
/**/
1203,
/**/
1202,
/**/
1201,
/**/
1200,
/**/
1199,
/**/
1198,
/**/
1197,
/**/
1196,
/**/
1195,
/**/
1194,
/**/
1193,
/**/
1192,
/**/
1191,
/**/
1190,
/**/
1189,
/**/
1188,
/**/
1187,
/**/
1186,
/**/
1185,
/**/
1184,
/**/
1183,
/**/
1182,
/**/
1181,
/**/
1180,
/**/
1179,
/**/
1178,
/**/
1177,
/**/
1176,
/**/
1175,
/**/
1174,
/**/
1173,
/**/
1172,
/**/
1171,
/**/
1170,
/**/
1169,
/**/
1168,
/**/
1167,
/**/
1166,
/**/
1165,
/**/
1164,
/**/
1163,
/**/
1162,
/**/
1161,
/**/
1160,
/**/
1159,
/**/
1158,
/**/
1157,
/**/
1156,
/**/
1155,
/**/
1154,
/**/
1153,
/**/
1152,
/**/
1151,
/**/
1150,
/**/
1149,
/**/
1148,
/**/
1147,
/**/
1146,
/**/
1145,
/**/
1144,
/**/
1143,
/**/
1142,
/**/
1141,
/**/
1140,
/**/
1139,
/**/
1138,
/**/
1137,
/**/
1136,
/**/
1135,
/**/
1134,
/**/
1133,
/**/
1132,
/**/
1131,
/**/
1130,
/**/
1129,
/**/
1128,
/**/
1127,
/**/
1126,
/**/
1125,
/**/
1124,
/**/
1123,
/**/
1122,
/**/
1121,
/**/
1120,
/**/
1119,
/**/
1118,
/**/
1117,
/**/
1116,
/**/
1115,
/**/
1114,
/**/
1113,
/**/
1112,
/**/
1111,
/**/
1110,
/**/
1109,
/**/
1108,
/**/
1107,
/**/
1106,
/**/
1105,
/**/
1104,
/**/
1103,
/**/
1102,
/**/
1101,
/**/
1100,
/**/
1099,
/**/
1098,
/**/
1097,
/**/
1096,
/**/
1095,
/**/
1094,
/**/
1093,
/**/
1092,
/**/
1091,
/**/
1090,
/**/
1089,
/**/
1088,
/**/
1087,
/**/
1086,
/**/
1085,
/**/
1084,
/**/
1083,
/**/
1082,
/**/
1081,
/**/
1080,
/**/
1079,
/**/
1078,
/**/
1077,
/**/
1076,
/**/
1075,
/**/
1074,
/**/
1073,
/**/
1072,
/**/
1071,
/**/
1070,
/**/
1069,
/**/
1068,
/**/
1067,
/**/
1066,
/**/
1065,
/**/
1064,
/**/
1063,
/**/
1062,
/**/
1061,
/**/
1060,
/**/
1059,
/**/
1058,
/**/
1057,
/**/
1056,
/**/
1055,
/**/
1054,
/**/
1053,
/**/
1052,
/**/
1051,
/**/
1050,
/**/
1049,
/**/
1048,
/**/
1047,
/**/
1046,
/**/
1045,
/**/
1044,
/**/
1043,
/**/
1042,
/**/
1041,
/**/
1040,
/**/
1039,
/**/
1038,
/**/
1037,
/**/
1036,
/**/
1035,
/**/
1034,
/**/
1033,
/**/
1032,
/**/
1031,
/**/
1030,
/**/
1029,
/**/
1028,
/**/
1027,
/**/
1026,
/**/
1025,
/**/
1024,
/**/
1023,
/**/
1022,
/**/
1021,
/**/
1020,
/**/
1019,
/**/
1018,
/**/
1017,
/**/
1016,
/**/
1015,
/**/
1014,
/**/
1013,
/**/
1012,
/**/
1011,
/**/
1010,
/**/
1009,
/**/
1008,
/**/
1007,
/**/
1006,
/**/
1005,
/**/
1004,
/**/
1003,
/**/
1002,
/**/
1001,
/**/
1000,
/**/
999,
/**/
998,
/**/
997,
/**/
996,
/**/
995,
/**/
994,
/**/
993,
/**/
992,
/**/
991,
/**/
990,
/**/
989,
/**/
988,
/**/
987,
/**/
986,
/**/
985,
/**/
984,
/**/
983,
/**/
982,
/**/
981,
/**/
980,
/**/
979,
/**/
978,
/**/
977,
/**/
976,
/**/
975,
/**/
974,
/**/
973,
/**/
972,
/**/
971,
/**/
970,
/**/
969,
/**/
968,
/**/
967,
/**/
966,
/**/
965,
/**/
964,
/**/
963,
/**/
962,
/**/
961,
/**/
960,
/**/
959,
/**/
958,
/**/
957,
/**/
956,
/**/
955,
/**/
954,
/**/
953,
/**/
952,
/**/
951,
/**/
950,
/**/
949,
/**/
948,
/**/
947,
/**/
946,
/**/
945,
/**/
944,
/**/
943,
/**/
942,
/**/
941,
/**/
940,
/**/
939,
/**/
938,
/**/
937,
/**/
936,
/**/
935,
/**/
934,
/**/
933,
/**/
932,
/**/
931,
/**/
930,
/**/
929,
/**/
928,
/**/
927,
/**/
926,
/**/
925,
/**/
924,
/**/
923,
/**/
922,
/**/
921,
/**/
920,
/**/
919,
/**/
918,
/**/
917,
/**/
916,
/**/
915,
/**/
914,
/**/
913,
/**/
912,
/**/
911,
/**/
910,
/**/
909,
/**/
908,
/**/
907,
/**/
906,
/**/
905,
/**/
904,
/**/
903,
/**/
902,
/**/
901,
/**/
900,
/**/
899,
/**/
898,
/**/
897,
/**/
896,
/**/
895,
/**/
894,
/**/
893,
/**/
892,
/**/
891,
/**/
890,
/**/
889,
/**/
888,
/**/
887,
/**/
886,
/**/
885,
/**/
884,
/**/
883,
/**/
882,
/**/
881,
/**/
880,
/**/
879,
/**/
878,
/**/
877,
/**/
876,
/**/
875,
/**/
874,
/**/
873,
/**/
872,
/**/
871,
/**/
870,
/**/
869,
/**/
868,
/**/
867,
/**/
866,
/**/
865,
/**/
864,
/**/
863,
/**/
862,
/**/
861,
/**/
860,
/**/
859,
/**/
858,
/**/
857,
/**/
856,
/**/
855,
/**/
854,
/**/
853,
/**/
852,
/**/
851,
/**/
850,
/**/
849,
/**/
848,
/**/
847,
/**/
846,
/**/
845,
/**/
844,
/**/
843,
/**/
842,
/**/
841,
/**/
840,
/**/
839,
/**/
838,
/**/
837,
/**/
836,
/**/
835,
/**/
834,
/**/
833,
/**/
832,
/**/
831,
/**/
830,
/**/
829,
/**/
828,
/**/
827,
/**/
826,
/**/
825,
/**/
824,
/**/
823,
/**/
822,
/**/
821,
/**/
820,
/**/
819,
/**/
818,
/**/
817,
/**/
816,
/**/
815,
/**/
814,
/**/
813,
/**/
812,
/**/
811,
/**/
810,
/**/
809,
/**/
808,
/**/
807,
/**/
806,
/**/
805,
/**/
804,
/**/
803,
/**/
802,
/**/
801,
/**/
800,
/**/
799,
/**/
798,
/**/
797,
/**/
796,
/**/
795,
/**/
794,
/**/
793,
/**/
792,
/**/
791,
/**/
790,
/**/
789,
/**/
788,
/**/
787,
/**/
786,
/**/
785,
/**/
784,
/**/
783,
/**/
782,
/**/
781,
/**/
780,
/**/
779,
/**/
778,
/**/
777,
/**/
776,
/**/
775,
/**/
774,
/**/
773,
/**/
772,
/**/
771,
/**/
770,
/**/
769,
/**/
768,
/**/
767,
/**/
766,
/**/
765,
/**/
764,
/**/
763,
/**/
762,
/**/
761,
/**/
760,
/**/
759,
/**/
758,
/**/
757,
/**/
756,
/**/
755,
/**/
754,
/**/
753,
/**/
752,
/**/
751,
/**/
750,
/**/
749,
/**/
748,
/**/
747,
/**/
746,
/**/
745,
/**/
744,
/**/
743,
/**/
742,
/**/
741,
/**/
740,
/**/
739,
/**/
738,
/**/
737,
/**/
736,
/**/
735,
/**/
734,
/**/
733,
/**/
732,
/**/
731,
/**/
730,
/**/
729,
/**/
728,
/**/
727,
/**/
726,
/**/
725,
/**/
724,
/**/
723,
/**/
722,
/**/
721,
/**/
720,
/**/
719,
/**/
718,
/**/
717,
/**/
716,
/**/
715,
/**/
714,
/**/
713,
/**/
712,
/**/
711,
/**/
710,
/**/
709,
/**/
708,
/**/
707,
/**/
706,
/**/
705,
/**/
704,
/**/
703,
/**/
702,
/**/
701,
/**/
700,
/**/
699,
/**/
698,
/**/
697,
/**/
696,
/**/
695,
/**/
694,
/**/
693,
/**/
692,
/**/
691,
/**/
690,
/**/
689,
/**/
688,
/**/
687,
/**/
686,
/**/
685,
/**/
684,
/**/
683,
/**/
682,
/**/
681,
/**/
680,
/**/
679,
/**/
678,
/**/
677,
/**/
676,
/**/
675,
/**/
674,
/**/
673,
/**/
672,
/**/
671,
/**/
670,
/**/
669,
/**/
668,
/**/
667,
/**/
666,
/**/
665,
/**/
664,
/**/
663,
/**/
662,
/**/
661,
/**/
660,
/**/
659,
/**/
658,
/**/
657,
/**/
656,
/**/
655,
/**/
654,
/**/
653,
/**/
652,
/**/
651,
/**/
650,
/**/
649,
/**/
648,
/**/
647,
/**/
646,
/**/
645,
/**/
644,
/**/
643,
/**/
642,
/**/
641,
/**/
640,
/**/
639,
/**/
638,
/**/
637,
/**/
636,
/**/
635,
/**/
634,
/**/
633,
/**/
632,
/**/
631,
/**/
630,
/**/
629,
/**/
628,
/**/
627,
/**/
626,
/**/
625,
/**/
624,
/**/
623,
/**/
622,
/**/
621,
/**/
620,
/**/
619,
/**/
618,
/**/
617,
/**/
616,
/**/
615,
/**/
614,
/**/
613,
/**/
612,
/**/
611,
/**/
610,
/**/
609,
/**/
608,
/**/
607,
/**/
606,
/**/
605,
/**/
604,
/**/
603,
/**/
602,
/**/
601,
/**/
600,
/**/
599,
/**/
598,
/**/
597,
/**/
596,
/**/
595,
/**/
594,
/**/
593,
/**/
592,
/**/
591,
/**/
590,
/**/
589,
/**/
588,
/**/
587,
/**/
586,
/**/
585,
/**/
584,
/**/
583,
/**/
582,
/**/
581,
/**/
580,
/**/
579,
/**/
578,
/**/
577,
/**/
576,
/**/
575,
/**/
574,
/**/
573,
/**/
572,
/**/
571,
/**/
570,
/**/
569,
/**/
568,
/**/
567,
/**/
566,
/**/
565,
/**/
564,
/**/
563,
/**/
562,
/**/
561,
/**/
560,
/**/
559,
/**/
558,
/**/
557,
/**/
556,
/**/
555,
/**/
554,
/**/
553,
/**/
552,
/**/
551,
/**/
550,
/**/
549,
/**/
548,
/**/
547,
/**/
546,
/**/
545,
/**/
544,
/**/
543,
/**/
542,
/**/
541,
/**/
540,
/**/
539,
/**/
538,
/**/
537,
/**/
536,
/**/
535,
/**/
534,
/**/
533,
/**/
532,
/**/
531,
/**/
530,
/**/
529,
/**/
528,
/**/
527,
/**/
526,
/**/
525,
/**/
524,
/**/
523,
/**/
522,
/**/
521,
/**/
520,
/**/
519,
/**/
518,
/**/
517,
/**/
516,
/**/
515,
/**/
514,
/**/
513,
/**/
512,
/**/
511,
/**/
510,
/**/
509,
/**/
508,
/**/
507,
/**/
506,
/**/
505,
/**/
504,
/**/
503,
/**/
502,
/**/
501,
/**/
500,
/**/
499,
/**/
498,
/**/
497,
/**/
496,
/**/
495,
/**/
494,
/**/
493,
/**/
492,
/**/
491,
/**/
490,
/**/
489,
/**/
488,
/**/
487,
/**/
486,
/**/
485,
/**/
484,
/**/
483,
/**/
482,
/**/
481,
/**/
480,
/**/
479,
/**/
478,
/**/
477,
/**/
476,
/**/
475,
/**/
474,
/**/
473,
/**/
472,
/**/
471,
/**/
470,
/**/
469,
/**/
468,
/**/
467,
/**/
466,
/**/
465,
/**/
464,
/**/
463,
/**/
462,
/**/
461,
/**/
460,
/**/
459,
/**/
458,
/**/
457,
/**/
456,
/**/
455,
/**/
454,
/**/
453,
/**/
452,
/**/
451,
/**/
450,
/**/
449,
/**/
448,
/**/
447,
/**/
446,
/**/
445,
/**/
444,
/**/
443,
/**/
442,
/**/
441,
/**/
440,
/**/
439,
/**/
438,
/**/
437,
/**/
436,
/**/
435,
/**/
434,
/**/
433,
/**/
432,
/**/
431,
/**/
430,
/**/
429,
/**/
428,
/**/
427,
/**/
426,
/**/
425,
/**/
424,
/**/
423,
/**/
422,
/**/
421,
/**/
420,
/**/
419,
/**/
418,
/**/
417,
/**/
416,
/**/
415,
/**/
414,
/**/
413,
/**/
412,
/**/
411,
/**/
410,
/**/
409,
/**/
408,
/**/
407,
/**/
406,
/**/
405,
/**/
404,
/**/
403,
/**/
402,
/**/
401,
/**/
400,
/**/
399,
/**/
398,
/**/
397,
/**/
396,
/**/
395,
/**/
394,
/**/
393,
/**/
392,
/**/
391,
/**/
390,
/**/
389,
/**/
388,
/**/
387,
/**/
386,
/**/
385,
/**/
384,
/**/
383,
/**/
382,
/**/
381,
/**/
380,
/**/
379,
/**/
378,
/**/
377,
/**/
376,
/**/
375,
/**/
374,
/**/
373,
/**/
372,
/**/
371,
/**/
370,
/**/
369,
/**/
368,
/**/
367,
/**/
366,
/**/
365,
/**/
364,
/**/
363,
/**/
362,
/**/
361,
/**/
360,
/**/
359,
/**/
358,
/**/
357,
/**/
356,
/**/
355,
/**/
354,
/**/
353,
/**/
352,
/**/
351,
/**/
350,
/**/
349,
/**/
348,
/**/
347,
/**/
346,
/**/
345,
/**/
344,
/**/
343,
/**/
342,
/**/
341,
/**/
340,
/**/
339,
/**/
338,
/**/
337,
/**/
336,
/**/
335,
/**/
334,
/**/
333,
/**/
332,
/**/
331,
/**/
330,
/**/
329,
/**/
328,
/**/
327,
/**/
326,
/**/
325,
/**/
324,
/**/
323,
/**/
322,
/**/
321,
/**/
320,
/**/
319,
/**/
318,
/**/
317,
/**/
316,
/**/
315,
/**/
314,
/**/
313,
/**/
312,
/**/
311,
/**/
310,
/**/
309,
/**/
308,
/**/
307,
/**/
306,
/**/
305,
/**/
304,
/**/
303,
/**/
302,
/**/
301,
/**/
300,
/**/
299,
/**/
298,
/**/
297,
/**/
296,
/**/
295,
/**/
294,
/**/
293,
/**/
292,
/**/
291,
/**/
290,
/**/
289,
/**/
288,
/**/
287,
/**/
286,
/**/
285,
/**/
284,
/**/
283,
/**/
282,
/**/
281,
/**/
280,
/**/
279,
/**/
278,
/**/
277,
/**/
276,
/**/
275,
/**/
274,
/**/
273,
/**/
272,
/**/
271,
/**/
270,
/**/
269,
/**/
268,
/**/
267,
/**/
266,
/**/
265,
/**/
264,
/**/
263,
/**/
262,
/**/
261,
/**/
260,
/**/
259,
/**/
258,
/**/
257,
/**/
256,
/**/
255,
/**/
254,
/**/
253,
/**/
252,
/**/
251,
/**/
250,
/**/
249,
/**/
248,
/**/
247,
/**/
246,
/**/
245,
/**/
244,
/**/
243,
/**/
242,
/**/
241,
/**/
240,
/**/
239,
/**/
238,
/**/
237,
/**/
236,
/**/
235,
/**/
234,
/**/
233,
/**/
232,
/**/
231,
/**/
230,
/**/
229,
/**/
228,
/**/
227,
/**/
226,
/**/
225,
/**/
224,
/**/
223,
/**/
222,
/**/
221,
/**/
220,
/**/
219,
/**/
218,
/**/
217,
/**/
216,
/**/
215,
/**/
214,
/**/
213,
/**/
212,
/**/
211,
/**/
210,
/**/
209,
/**/
208,
/**/
207,
/**/
206,
/**/
205,
/**/
204,
/**/
203,
/**/
202,
/**/
201,
/**/
200,
/**/
199,
/**/
198,
/**/
197,
/**/
196,
/**/
195,
/**/
194,
/**/
193,
/**/
192,
/**/
191,
/**/
190,
/**/
189,
/**/
188,
/**/
187,
/**/
186,
/**/
185,
/**/
184,
/**/
183,
/**/
182,
/**/
181,
/**/
180,
/**/
179,
/**/
178,
/**/
177,
/**/
176,
/**/
175,
/**/
174,
/**/
173,
/**/
172,
/**/
171,
/**/
170,
/**/
169,
/**/
168,
/**/
167,
/**/
166,
/**/
165,
/**/
164,
/**/
163,
/**/
162,
/**/
161,
/**/
160,
/**/
159,
/**/
158,
/**/
157,
/**/
156,
/**/
155,
/**/
154,
/**/
153,
/**/
152,
/**/
151,
/**/
150,
/**/
149,
/**/
148,
/**/
147,
/**/
146,
/**/
145,
/**/
144,
/**/
143,
/**/
142,
/**/
141,
/**/
140,
/**/
139,
/**/
138,
/**/
137,
/**/
136,
/**/
135,
/**/
134,
/**/
133,
/**/
132,
/**/
131,
/**/
130,
/**/
129,
/**/
128,
/**/
127,
/**/
126,
/**/
125,
/**/
124,
/**/
123,
/**/
122,
/**/
121,
/**/
120,
/**/
119,
/**/
118,
/**/
117,
/**/
116,
/**/
115,
/**/
114,
/**/
113,
/**/
112,
/**/
111,
/**/
110,
/**/
109,
/**/
108,
/**/
107,
/**/
106,
/**/
105,
/**/
104,
/**/
103,
/**/
102,
/**/
101,
/**/
100,
/**/
99,
/**/
98,
/**/
97,
/**/
96,
/**/
95,
/**/
94,
/**/
93,
/**/
92,
/**/
91,
/**/
90,
/**/
89,
/**/
88,
/**/
87,
/**/
86,
/**/
85,
/**/
84,
/**/
83,
/**/
82,
/**/
81,
/**/
80,
/**/
79,
/**/
78,
/**/
77,
/**/
76,
/**/
75,
/**/
74,
/**/
73,
/**/
72,
/**/
71,
/**/
70,
/**/
69,
/**/
68,
/**/
67,
/**/
66,
/**/
65,
/**/
64,
/**/
63,
/**/
62,
/**/
61,
/**/
60,
/**/
59,
/**/
58,
/**/
57,
/**/
56,
/**/
55,
/**/
54,
/**/
53,
/**/
52,
/**/
51,
/**/
50,
/**/
49,
/**/
48,
/**/
47,
/**/
46,
/**/
45,
/**/
44,
/**/
43,
/**/
42,
/**/
41,
/**/
40,
/**/
39,
/**/
38,
/**/
37,
/**/
36,
/**/
35,
/**/
34,
/**/
33,
/**/
32,
/**/
31,
/**/
30,
/**/
29,
/**/
28,
/**/
27,
/**/
26,
/**/
25,
/**/
24,
/**/
23,
/**/
22,
/**/
21,
/**/
20,
/**/
19,
/**/
18,
/**/
17,
/**/
16,
/**/
15,
/**/
14,
/**/
13,
/**/
12,
/**/
11,
/**/
10,
/**/
9,
/**/
8,
/**/
7,
/**/
6,
/**/
5,
/**/
4,
/**/
3,
/**/
2,
/**/
1,
/**/
0
};
/*
* Place to put a short description when adding a feature with a patch.
* Keep it short, e.g.,: "relative numbers", "persistent undo".
* Also add a comment marker to separate the lines.
* See the official Vim patches for the diff format: It must use a context of
* one line only. Create it by hand or use "diff -C2" and edit the patch.
*/
static char *(extra_patches[]) =
{ /* Add your patch description below this line */
/**/
NULL
};
int
highest_patch(void)
{
int i;
int h = 0;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] > h)
h = included_patches[i];
return h;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if patch "n" has been included.
*/
int
has_patch(int n)
{
int i;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] == n)
return TRUE;
return FALSE;
}
#endif
void
ex_version(exarg_T *eap)
{
/*
* Ignore a ":version 9.99" command.
*/
if (*eap->arg == NUL)
{
msg_putchar('\n');
list_version();
}
}
/*
* Output a string for the version message. If it's going to wrap, output a
* newline, unless the message is too long to fit on the screen anyway.
* When "wrap" is TRUE wrap the string in [].
*/
static void
version_msg_wrap(char_u *s, int wrap)
{
int len = (int)vim_strsize(s) + (wrap ? 2 : 0);
if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns
&& *s != '\n')
msg_putchar('\n');
if (!got_int)
{
if (wrap)
msg_puts("[");
msg_puts((char *)s);
if (wrap)
msg_puts("]");
}
}
static void
version_msg(char *s)
{
version_msg_wrap((char_u *)s, FALSE);
}
/*
* List all features aligned in columns, dictionary style.
*/
static void
list_features(void)
{
list_in_columns((char_u **)features, -1, -1);
}
/*
* List string items nicely aligned in columns.
* When "size" is < 0 then the last entry is marked with NULL.
* The entry with index "current" is inclosed in [].
*/
void
list_in_columns(char_u **items, int size, int current)
{
int i;
int ncol;
int nrow;
int item_count = 0;
int width = 0;
#ifdef FEAT_SYN_HL
int use_highlight = (items == (char_u **)features);
#endif
/* Find the length of the longest item, use that + 1 as the column
* width. */
for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)
{
int l = (int)vim_strsize(items[i]) + (i == current ? 2 : 0);
if (l > width)
width = l;
++item_count;
}
width += 1;
if (Columns < width)
{
/* Not enough screen columns - show one per line */
for (i = 0; i < item_count; ++i)
{
version_msg_wrap(items[i], i == current);
if (msg_col > 0)
msg_putchar('\n');
}
return;
}
/* The rightmost column doesn't need a separator.
* Sacrifice it to fit in one more column if possible. */
ncol = (int) (Columns + 1) / width;
nrow = item_count / ncol + (item_count % ncol ? 1 : 0);
/* i counts columns then rows. idx counts rows then columns. */
for (i = 0; !got_int && i < nrow * ncol; ++i)
{
int idx = (i / ncol) + (i % ncol) * nrow;
if (idx < item_count)
{
int last_col = (i + 1) % ncol == 0;
if (idx == current)
msg_putchar('[');
#ifdef FEAT_SYN_HL
if (use_highlight && items[idx][0] == '-')
msg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));
else
#endif
msg_puts((char *)items[idx]);
if (idx == current)
msg_putchar(']');
if (last_col)
{
if (msg_col > 0)
msg_putchar('\n');
}
else
{
while (msg_col % width)
msg_putchar(' ');
}
}
else
{
if (msg_col > 0)
msg_putchar('\n');
}
}
}
void
list_version(void)
{
int i;
int first;
char *s = "";
/*
* When adding features here, don't forget to update the list of
* internal variables in eval.c!
*/
init_longVersion();
msg(longVersion);
#ifdef MSWIN
# ifdef FEAT_GUI_MSWIN
# ifdef VIMDLL
# ifdef _WIN64
msg_puts(_("\nMS-Windows 64-bit GUI/console version"));
# else
msg_puts(_("\nMS-Windows 32-bit GUI/console version"));
# endif
# else
# ifdef _WIN64
msg_puts(_("\nMS-Windows 64-bit GUI version"));
# else
msg_puts(_("\nMS-Windows 32-bit GUI version"));
# endif
# endif
# ifdef FEAT_OLE
msg_puts(_(" with OLE support"));
# endif
# else
# ifdef _WIN64
msg_puts(_("\nMS-Windows 64-bit console version"));
# else
msg_puts(_("\nMS-Windows 32-bit console version"));
# endif
# endif
#endif
#if defined(MACOS_X)
# if defined(MACOS_X_DARWIN)
msg_puts(_("\nmacOS version"));
# else
msg_puts(_("\nmacOS version w/o darwin feat."));
# endif
#endif
#ifdef VMS
msg_puts(_("\nOpenVMS version"));
# ifdef HAVE_PATHDEF
if (*compiled_arch != NUL)
{
msg_puts(" - ");
msg_puts((char *)compiled_arch);
}
# endif
#endif
/* Print the list of patch numbers if there is at least one. */
/* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */
if (included_patches[0] != 0)
{
msg_puts(_("\nIncluded patches: "));
first = -1;
/* find last one */
for (i = 0; included_patches[i] != 0; ++i)
;
while (--i >= 0)
{
if (first < 0)
first = included_patches[i];
if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)
{
msg_puts(s);
s = ", ";
msg_outnum((long)first);
if (first != included_patches[i])
{
msg_puts("-");
msg_outnum((long)included_patches[i]);
}
first = -1;
}
}
}
/* Print the list of extra patch descriptions if there is at least one. */
if (extra_patches[0] != NULL)
{
msg_puts(_("\nExtra patches: "));
s = "";
for (i = 0; extra_patches[i] != NULL; ++i)
{
msg_puts(s);
s = ", ";
msg_puts(extra_patches[i]);
}
}
#ifdef MODIFIED_BY
msg_puts("\n");
msg_puts(_("Modified by "));
msg_puts(MODIFIED_BY);
#endif
#ifdef HAVE_PATHDEF
if (*compiled_user != NUL || *compiled_sys != NUL)
{
msg_puts(_("\nCompiled "));
if (*compiled_user != NUL)
{
msg_puts(_("by "));
msg_puts((char *)compiled_user);
}
if (*compiled_sys != NUL)
{
msg_puts("@");
msg_puts((char *)compiled_sys);
}
}
#endif
#ifdef FEAT_HUGE
msg_puts(_("\nHuge version "));
#else
# ifdef FEAT_BIG
msg_puts(_("\nBig version "));
# else
# ifdef FEAT_NORMAL
msg_puts(_("\nNormal version "));
# else
# ifdef FEAT_SMALL
msg_puts(_("\nSmall version "));
# else
msg_puts(_("\nTiny version "));
# endif
# endif
# endif
#endif
#ifndef FEAT_GUI
msg_puts(_("without GUI."));
#else
# ifdef FEAT_GUI_GTK
# ifdef USE_GTK3
msg_puts(_("with GTK3 GUI."));
# else
# ifdef FEAT_GUI_GNOME
msg_puts(_("with GTK2-GNOME GUI."));
# else
msg_puts(_("with GTK2 GUI."));
# endif
# endif
# else
# ifdef FEAT_GUI_MOTIF
msg_puts(_("with X11-Motif GUI."));
# else
# ifdef FEAT_GUI_ATHENA
# ifdef FEAT_GUI_NEXTAW
msg_puts(_("with X11-neXtaw GUI."));
# else
msg_puts(_("with X11-Athena GUI."));
# endif
# else
# ifdef FEAT_GUI_PHOTON
msg_puts(_("with Photon GUI."));
# else
# if defined(MSWIN)
msg_puts(_("with GUI."));
# else
# if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON
msg_puts(_("with Carbon GUI."));
# else
# if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX
msg_puts(_("with Cocoa GUI."));
# else
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
version_msg(_(" Features included (+) or not (-):\n"));
list_features();
#ifdef SYS_VIMRC_FILE
version_msg(_(" system vimrc file: \""));
version_msg(SYS_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE
version_msg(_(" user vimrc file: \""));
version_msg(USR_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE2
version_msg(_(" 2nd user vimrc file: \""));
version_msg(USR_VIMRC_FILE2);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE3
version_msg(_(" 3rd user vimrc file: \""));
version_msg(USR_VIMRC_FILE3);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE
version_msg(_(" user exrc file: \""));
version_msg(USR_EXRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE2
version_msg(_(" 2nd user exrc file: \""));
version_msg(USR_EXRC_FILE2);
version_msg("\"\n");
#endif
#ifdef FEAT_GUI
# ifdef SYS_GVIMRC_FILE
version_msg(_(" system gvimrc file: \""));
version_msg(SYS_GVIMRC_FILE);
version_msg("\"\n");
# endif
version_msg(_(" user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE);
version_msg("\"\n");
# ifdef USR_GVIMRC_FILE2
version_msg(_("2nd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE2);
version_msg("\"\n");
# endif
# ifdef USR_GVIMRC_FILE3
version_msg(_("3rd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE3);
version_msg("\"\n");
# endif
#endif
version_msg(_(" defaults file: \""));
version_msg(VIM_DEFAULTS_FILE);
version_msg("\"\n");
#ifdef FEAT_GUI
# ifdef SYS_MENU_FILE
version_msg(_(" system menu file: \""));
version_msg(SYS_MENU_FILE);
version_msg("\"\n");
# endif
#endif
#ifdef HAVE_PATHDEF
if (*default_vim_dir != NUL)
{
version_msg(_(" fall-back for $VIM: \""));
version_msg((char *)default_vim_dir);
version_msg("\"\n");
}
if (*default_vimruntime_dir != NUL)
{
version_msg(_(" f-b for $VIMRUNTIME: \""));
version_msg((char *)default_vimruntime_dir);
version_msg("\"\n");
}
version_msg(_("Compilation: "));
version_msg((char *)all_cflags);
version_msg("\n");
#ifdef VMS
if (*compiler_version != NUL)
{
version_msg(_("Compiler: "));
version_msg((char *)compiler_version);
version_msg("\n");
}
#endif
version_msg(_("Linking: "));
version_msg((char *)all_lflags);
#endif
#ifdef DEBUG
version_msg("\n");
version_msg(_(" DEBUG BUILD"));
#endif
}
static void do_intro_line(int row, char_u *mesg, int add_version, int attr);
/*
* Show the intro message when not editing a file.
*/
void
maybe_intro_message(void)
{
if (BUFEMPTY()
&& curbuf->b_fname == NULL
&& firstwin->w_next == NULL
&& vim_strchr(p_shm, SHM_INTRO) == NULL)
intro_message(FALSE);
}
/*
* Give an introductory message about Vim.
* Only used when starting Vim on an empty file, without a file name.
* Or with the ":intro" command (for Sven :-).
*/
void
intro_message(
int colon) /* TRUE for ":intro" */
{
int i;
int row;
int blanklines;
int sponsor;
char *p;
static char *(lines[]) =
{
N_("VIM - Vi IMproved"),
"",
N_("version "),
N_("by Bram Moolenaar et al."),
#ifdef MODIFIED_BY
" ",
#endif
N_("Vim is open source and freely distributable"),
"",
N_("Help poor children in Uganda!"),
N_("type :help iccf<Enter> for information "),
"",
N_("type :q<Enter> to exit "),
N_("type :help<Enter> or <F1> for on-line help"),
N_("type :help version8<Enter> for version info"),
NULL,
"",
N_("Running in Vi compatible mode"),
N_("type :set nocp<Enter> for Vim defaults"),
N_("type :help cp-default<Enter> for info on this"),
};
#ifdef FEAT_GUI
static char *(gui_lines[]) =
{
NULL,
NULL,
NULL,
NULL,
#ifdef MODIFIED_BY
NULL,
#endif
NULL,
NULL,
NULL,
N_("menu Help->Orphans for information "),
NULL,
N_("Running modeless, typed text is inserted"),
N_("menu Edit->Global Settings->Toggle Insert Mode "),
N_(" for two modes "),
NULL,
NULL,
NULL,
N_("menu Edit->Global Settings->Toggle Vi Compatible"),
N_(" for Vim defaults "),
};
#endif
/* blanklines = screen height - # message lines */
blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1);
if (!p_cp)
blanklines += 4; /* add 4 for not showing "Vi compatible" message */
/* Don't overwrite a statusline. Depends on 'cmdheight'. */
if (p_ls > 1)
blanklines -= Rows - topframe->fr_height;
if (blanklines < 0)
blanklines = 0;
/* Show the sponsor and register message one out of four times, the Uganda
* message two out of four times. */
sponsor = (int)time(NULL);
sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);
/* start displaying the message lines after half of the blank lines */
row = blanklines / 2;
if ((row >= 2 && Columns >= 50) || colon)
{
for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i)
{
p = lines[i];
#ifdef FEAT_GUI
if (p_im && gui.in_use && gui_lines[i] != NULL)
p = gui_lines[i];
#endif
if (p == NULL)
{
if (!p_cp)
break;
continue;
}
if (sponsor != 0)
{
if (strstr(p, "children") != NULL)
p = sponsor < 0
? N_("Sponsor Vim development!")
: N_("Become a registered Vim user!");
else if (strstr(p, "iccf") != NULL)
p = sponsor < 0
? N_("type :help sponsor<Enter> for information ")
: N_("type :help register<Enter> for information ");
else if (strstr(p, "Orphans") != NULL)
p = N_("menu Help->Sponsor/Register for information ");
}
if (*p != NUL)
do_intro_line(row, (char_u *)_(p), i == 2, 0);
++row;
}
}
/* Make the wait-return message appear just below the text. */
if (colon)
msg_row = row;
}
static void
do_intro_line(
int row,
char_u *mesg,
int add_version,
int attr)
{
char_u vers[20];
int col;
char_u *p;
int l;
int clen;
#ifdef MODIFIED_BY
# define MODBY_LEN 150
char_u modby[MODBY_LEN];
if (*mesg == ' ')
{
vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1);
l = (int)STRLEN(modby);
vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);
mesg = modby;
}
#endif
/* Center the message horizontally. */
col = vim_strsize(mesg);
if (add_version)
{
STRCPY(vers, mediumVersion);
if (highest_patch())
{
/* Check for 9.9x or 9.9xx, alpha/beta version */
if (isalpha((int)vers[3]))
{
int len = (isalpha((int)vers[4])) ? 5 : 4;
sprintf((char *)vers + len, ".%d%s", highest_patch(),
mediumVersion + len);
}
else
sprintf((char *)vers + 3, ".%d", highest_patch());
}
col += (int)STRLEN(vers);
}
col = (Columns - col) / 2;
if (col < 0)
col = 0;
/* Split up in parts to highlight <> items differently. */
for (p = mesg; *p != NUL; p += l)
{
clen = 0;
for (l = 0; p[l] != NUL
&& (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)
{
if (has_mbyte)
{
clen += ptr2cells(p + l);
l += (*mb_ptr2len)(p + l) - 1;
}
else
clen += byte2cells(p[l]);
}
screen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);
col += clen;
}
/* Add the version number to the version line. */
if (add_version)
screen_puts(vers, row, col, 0);
}
/*
* ":intro": clear screen, display intro screen and wait for return.
*/
void
ex_intro(exarg_T *eap UNUSED)
{
screenclear();
intro_message(TRUE);
wait_return(TRUE);
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/good_882_2 |
crossvul-cpp_data_bad_882_0 | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* getchar.c
*
* functions related with getting a character from the user/mapping/redo/...
*
* manipulations with redo buffer and stuff buffer
* mappings and abbreviations
*/
#include "vim.h"
/*
* These buffers are used for storing:
* - stuffed characters: A command that is translated into another command.
* - redo characters: will redo the last change.
* - recorded characters: for the "q" command.
*
* The bytes are stored like in the typeahead buffer:
* - K_SPECIAL introduces a special key (two more bytes follow). A literal
* K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
* - CSI introduces a GUI termcap code (also when gui.in_use is FALSE,
* otherwise switching the GUI on would make mappings invalid).
* A literal CSI is stored as CSI KS_EXTRA KE_CSI.
* These translations are also done on multi-byte characters!
*
* Escaping CSI bytes is done by the system-specific input functions, called
* by ui_inchar().
* Escaping K_SPECIAL is done by inchar().
* Un-escaping is done by vgetc().
*/
#define MINIMAL_SIZE 20 /* minimal size for b_str */
static buffheader_T redobuff = {{NULL, {NUL}}, NULL, 0, 0};
static buffheader_T old_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
static buffheader_T recordbuff = {{NULL, {NUL}}, NULL, 0, 0};
static int typeahead_char = 0; /* typeahead char that's not flushed */
/*
* when block_redo is TRUE redo buffer will not be changed
* used by edit() to repeat insertions and 'V' command for redoing
*/
static int block_redo = FALSE;
/*
* Make a hash value for a mapping.
* "mode" is the lower 4 bits of the State for the mapping.
* "c1" is the first character of the "lhs".
* Returns a value between 0 and 255, index in maphash.
* Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
*/
#define MAP_HASH(mode, c1) (((mode) & (NORMAL + VISUAL + SELECTMODE + OP_PENDING + TERMINAL)) ? (c1) : ((c1) ^ 0x80))
/*
* Each mapping is put in one of the 256 hash lists, to speed up finding it.
*/
static mapblock_T *(maphash[256]);
static int maphash_valid = FALSE;
/*
* List used for abbreviations.
*/
static mapblock_T *first_abbr = NULL; /* first entry in abbrlist */
static int KeyNoremap = 0; /* remapping flags */
/*
* Variables used by vgetorpeek() and flush_buffers().
*
* typebuf.tb_buf[] contains all characters that are not consumed yet.
* typebuf.tb_buf[typebuf.tb_off] is the first valid character.
* typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
* typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
* The head of the buffer may contain the result of mappings, abbreviations
* and @a commands. The length of this part is typebuf.tb_maplen.
* typebuf.tb_silent is the part where <silent> applies.
* After the head are characters that come from the terminal.
* typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
* should not be considered for abbreviations.
* Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
* in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
* contains RM_NONE for the characters that are not to be remapped.
* typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
* (typebuf has been put in globals.h, because check_termcode() needs it).
*/
#define RM_YES 0 /* tb_noremap: remap */
#define RM_NONE 1 /* tb_noremap: don't remap */
#define RM_SCRIPT 2 /* tb_noremap: remap local script mappings */
#define RM_ABBR 4 /* tb_noremap: don't remap, do abbrev. */
/* typebuf.tb_buf has three parts: room in front (for result of mappings), the
* middle for typeahead and room for new characters (which needs to be 3 *
* MAXMAPLEN) for the Amiga).
*/
#define TYPELEN_INIT (5 * (MAXMAPLEN + 3))
static char_u typebuf_init[TYPELEN_INIT]; /* initial typebuf.tb_buf */
static char_u noremapbuf_init[TYPELEN_INIT]; /* initial typebuf.tb_noremap */
static int last_recorded_len = 0; /* number of last recorded chars */
static int read_readbuf(buffheader_T *buf, int advance);
static void init_typebuf(void);
static void may_sync_undo(void);
static void closescript(void);
static int vgetorpeek(int);
static void map_free(mapblock_T **);
static void validate_maphash(void);
static void showmap(mapblock_T *mp, int local);
static int inchar(char_u *buf, int maxlen, long wait_time);
#ifdef FEAT_EVAL
static char_u *eval_map_expr(char_u *str, int c);
#endif
/*
* Free and clear a buffer.
*/
void
free_buff(buffheader_T *buf)
{
buffblock_T *p, *np;
for (p = buf->bh_first.b_next; p != NULL; p = np)
{
np = p->b_next;
vim_free(p);
}
buf->bh_first.b_next = NULL;
}
/*
* Return the contents of a buffer as a single string.
* K_SPECIAL and CSI in the returned string are escaped.
*/
static char_u *
get_buffcont(
buffheader_T *buffer,
int dozero) /* count == zero is not an error */
{
long_u count = 0;
char_u *p = NULL;
char_u *p2;
char_u *str;
buffblock_T *bp;
/* compute the total length of the string */
for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
count += (long_u)STRLEN(bp->b_str);
if ((count || dozero) && (p = lalloc(count + 1, TRUE)) != NULL)
{
p2 = p;
for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
for (str = bp->b_str; *str; )
*p2++ = *str++;
*p2 = NUL;
}
return (p);
}
/*
* Return the contents of the record buffer as a single string
* and clear the record buffer.
* K_SPECIAL and CSI in the returned string are escaped.
*/
char_u *
get_recorded(void)
{
char_u *p;
size_t len;
p = get_buffcont(&recordbuff, TRUE);
free_buff(&recordbuff);
/*
* Remove the characters that were added the last time, these must be the
* (possibly mapped) characters that stopped the recording.
*/
len = STRLEN(p);
if ((int)len >= last_recorded_len)
{
len -= last_recorded_len;
p[len] = NUL;
}
/*
* When stopping recording from Insert mode with CTRL-O q, also remove the
* CTRL-O.
*/
if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O)
p[len - 1] = NUL;
return (p);
}
/*
* Return the contents of the redo buffer as a single string.
* K_SPECIAL and CSI in the returned string are escaped.
*/
char_u *
get_inserted(void)
{
return get_buffcont(&redobuff, FALSE);
}
/*
* Add string "s" after the current block of buffer "buf".
* K_SPECIAL and CSI should have been escaped already.
*/
static void
add_buff(
buffheader_T *buf,
char_u *s,
long slen) /* length of "s" or -1 */
{
buffblock_T *p;
long_u len;
if (slen < 0)
slen = (long)STRLEN(s);
if (slen == 0) /* don't add empty strings */
return;
if (buf->bh_first.b_next == NULL) /* first add to list */
{
buf->bh_space = 0;
buf->bh_curr = &(buf->bh_first);
}
else if (buf->bh_curr == NULL) /* buffer has already been read */
{
iemsg(_("E222: Add to read buffer"));
return;
}
else if (buf->bh_index != 0)
mch_memmove(buf->bh_first.b_next->b_str,
buf->bh_first.b_next->b_str + buf->bh_index,
STRLEN(buf->bh_first.b_next->b_str + buf->bh_index) + 1);
buf->bh_index = 0;
if (buf->bh_space >= (int)slen)
{
len = (long_u)STRLEN(buf->bh_curr->b_str);
vim_strncpy(buf->bh_curr->b_str + len, s, (size_t)slen);
buf->bh_space -= slen;
}
else
{
if (slen < MINIMAL_SIZE)
len = MINIMAL_SIZE;
else
len = slen;
p = (buffblock_T *)lalloc((long_u)(sizeof(buffblock_T) + len),
TRUE);
if (p == NULL)
return; /* no space, just forget it */
buf->bh_space = (int)(len - slen);
vim_strncpy(p->b_str, s, (size_t)slen);
p->b_next = buf->bh_curr->b_next;
buf->bh_curr->b_next = p;
buf->bh_curr = p;
}
return;
}
/*
* Add number "n" to buffer "buf".
*/
static void
add_num_buff(buffheader_T *buf, long n)
{
char_u number[32];
sprintf((char *)number, "%ld", n);
add_buff(buf, number, -1L);
}
/*
* Add character 'c' to buffer "buf".
* Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
*/
static void
add_char_buff(buffheader_T *buf, int c)
{
char_u bytes[MB_MAXBYTES + 1];
int len;
int i;
char_u temp[4];
if (IS_SPECIAL(c))
len = 1;
else
len = (*mb_char2bytes)(c, bytes);
for (i = 0; i < len; ++i)
{
if (!IS_SPECIAL(c))
c = bytes[i];
if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL)
{
/* translate special key code into three byte sequence */
temp[0] = K_SPECIAL;
temp[1] = K_SECOND(c);
temp[2] = K_THIRD(c);
temp[3] = NUL;
}
#ifdef FEAT_GUI
else if (c == CSI)
{
/* Translate a CSI to a CSI - KS_EXTRA - KE_CSI sequence */
temp[0] = CSI;
temp[1] = KS_EXTRA;
temp[2] = (int)KE_CSI;
temp[3] = NUL;
}
#endif
else
{
temp[0] = c;
temp[1] = NUL;
}
add_buff(buf, temp, -1L);
}
}
/* First read ahead buffer. Used for translated commands. */
static buffheader_T readbuf1 = {{NULL, {NUL}}, NULL, 0, 0};
/* Second read ahead buffer. Used for redo. */
static buffheader_T readbuf2 = {{NULL, {NUL}}, NULL, 0, 0};
/*
* Get one byte from the read buffers. Use readbuf1 one first, use readbuf2
* if that one is empty.
* If advance == TRUE go to the next char.
* No translation is done K_SPECIAL and CSI are escaped.
*/
static int
read_readbuffers(int advance)
{
int c;
c = read_readbuf(&readbuf1, advance);
if (c == NUL)
c = read_readbuf(&readbuf2, advance);
return c;
}
static int
read_readbuf(buffheader_T *buf, int advance)
{
char_u c;
buffblock_T *curr;
if (buf->bh_first.b_next == NULL) /* buffer is empty */
return NUL;
curr = buf->bh_first.b_next;
c = curr->b_str[buf->bh_index];
if (advance)
{
if (curr->b_str[++buf->bh_index] == NUL)
{
buf->bh_first.b_next = curr->b_next;
vim_free(curr);
buf->bh_index = 0;
}
}
return c;
}
/*
* Prepare the read buffers for reading (if they contain something).
*/
static void
start_stuff(void)
{
if (readbuf1.bh_first.b_next != NULL)
{
readbuf1.bh_curr = &(readbuf1.bh_first);
readbuf1.bh_space = 0;
}
if (readbuf2.bh_first.b_next != NULL)
{
readbuf2.bh_curr = &(readbuf2.bh_first);
readbuf2.bh_space = 0;
}
}
/*
* Return TRUE if the stuff buffer is empty.
*/
int
stuff_empty(void)
{
return (readbuf1.bh_first.b_next == NULL
&& readbuf2.bh_first.b_next == NULL);
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if readbuf1 is empty. There may still be redo characters in
* redbuf2.
*/
int
readbuf1_empty(void)
{
return (readbuf1.bh_first.b_next == NULL);
}
#endif
/*
* Set a typeahead character that won't be flushed.
*/
void
typeahead_noflush(int c)
{
typeahead_char = c;
}
/*
* Remove the contents of the stuff buffer and the mapped characters in the
* typeahead buffer (used in case of an error). If "flush_typeahead" is true,
* flush all typeahead characters (used when interrupted by a CTRL-C).
*/
void
flush_buffers(flush_buffers_T flush_typeahead)
{
init_typebuf();
start_stuff();
while (read_readbuffers(TRUE) != NUL)
;
if (flush_typeahead == FLUSH_MINIMAL)
{
// remove mapped characters at the start only
typebuf.tb_off += typebuf.tb_maplen;
typebuf.tb_len -= typebuf.tb_maplen;
}
else
{
// remove typeahead
if (flush_typeahead == FLUSH_INPUT)
// We have to get all characters, because we may delete the first
// part of an escape sequence. In an xterm we get one char at a
// time and we have to get them all.
while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10L) != 0)
;
typebuf.tb_off = MAXMAPLEN;
typebuf.tb_len = 0;
#if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
/* Reset the flag that text received from a client or from feedkeys()
* was inserted in the typeahead buffer. */
typebuf_was_filled = FALSE;
#endif
}
typebuf.tb_maplen = 0;
typebuf.tb_silent = 0;
cmd_silent = FALSE;
typebuf.tb_no_abbr_cnt = 0;
}
/*
* The previous contents of the redo buffer is kept in old_redobuffer.
* This is used for the CTRL-O <.> command in insert mode.
*/
void
ResetRedobuff(void)
{
if (!block_redo)
{
free_buff(&old_redobuff);
old_redobuff = redobuff;
redobuff.bh_first.b_next = NULL;
}
}
/*
* Discard the contents of the redo buffer and restore the previous redo
* buffer.
*/
void
CancelRedo(void)
{
if (!block_redo)
{
free_buff(&redobuff);
redobuff = old_redobuff;
old_redobuff.bh_first.b_next = NULL;
start_stuff();
while (read_readbuffers(TRUE) != NUL)
;
}
}
/*
* Save redobuff and old_redobuff to save_redobuff and save_old_redobuff.
* Used before executing autocommands and user functions.
*/
void
saveRedobuff(save_redo_T *save_redo)
{
char_u *s;
save_redo->sr_redobuff = redobuff;
redobuff.bh_first.b_next = NULL;
save_redo->sr_old_redobuff = old_redobuff;
old_redobuff.bh_first.b_next = NULL;
/* Make a copy, so that ":normal ." in a function works. */
s = get_buffcont(&save_redo->sr_redobuff, FALSE);
if (s != NULL)
{
add_buff(&redobuff, s, -1L);
vim_free(s);
}
}
/*
* Restore redobuff and old_redobuff from save_redobuff and save_old_redobuff.
* Used after executing autocommands and user functions.
*/
void
restoreRedobuff(save_redo_T *save_redo)
{
free_buff(&redobuff);
redobuff = save_redo->sr_redobuff;
free_buff(&old_redobuff);
old_redobuff = save_redo->sr_old_redobuff;
}
/*
* Append "s" to the redo buffer.
* K_SPECIAL and CSI should already have been escaped.
*/
void
AppendToRedobuff(char_u *s)
{
if (!block_redo)
add_buff(&redobuff, s, -1L);
}
/*
* Append to Redo buffer literally, escaping special characters with CTRL-V.
* K_SPECIAL and CSI are escaped as well.
*/
void
AppendToRedobuffLit(
char_u *str,
int len) /* length of "str" or -1 for up to the NUL */
{
char_u *s = str;
int c;
char_u *start;
if (block_redo)
return;
while (len < 0 ? *s != NUL : s - str < len)
{
/* Put a string of normal characters in the redo buffer (that's
* faster). */
start = s;
while (*s >= ' '
#ifndef EBCDIC
&& *s < DEL /* EBCDIC: all chars above space are normal */
#endif
&& (len < 0 || s - str < len))
++s;
/* Don't put '0' or '^' as last character, just in case a CTRL-D is
* typed next. */
if (*s == NUL && (s[-1] == '0' || s[-1] == '^'))
--s;
if (s > start)
add_buff(&redobuff, start, (long)(s - start));
if (*s == NUL || (len >= 0 && s - str >= len))
break;
/* Handle a special or multibyte character. */
if (has_mbyte)
/* Handle composing chars separately. */
c = mb_cptr2char_adv(&s);
else
c = *s++;
if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^')))
add_char_buff(&redobuff, Ctrl_V);
/* CTRL-V '0' must be inserted as CTRL-V 048 (EBCDIC: xf0) */
if (*s == NUL && c == '0')
#ifdef EBCDIC
add_buff(&redobuff, (char_u *)"xf0", 3L);
#else
add_buff(&redobuff, (char_u *)"048", 3L);
#endif
else
add_char_buff(&redobuff, c);
}
}
/*
* Append a character to the redo buffer.
* Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
*/
void
AppendCharToRedobuff(int c)
{
if (!block_redo)
add_char_buff(&redobuff, c);
}
/*
* Append a number to the redo buffer.
*/
void
AppendNumberToRedobuff(long n)
{
if (!block_redo)
add_num_buff(&redobuff, n);
}
/*
* Append string "s" to the stuff buffer.
* CSI and K_SPECIAL must already have been escaped.
*/
void
stuffReadbuff(char_u *s)
{
add_buff(&readbuf1, s, -1L);
}
/*
* Append string "s" to the redo stuff buffer.
* CSI and K_SPECIAL must already have been escaped.
*/
void
stuffRedoReadbuff(char_u *s)
{
add_buff(&readbuf2, s, -1L);
}
void
stuffReadbuffLen(char_u *s, long len)
{
add_buff(&readbuf1, s, len);
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Stuff "s" into the stuff buffer, leaving special key codes unmodified and
* escaping other K_SPECIAL and CSI bytes.
* Change CR, LF and ESC into a space.
*/
void
stuffReadbuffSpec(char_u *s)
{
int c;
while (*s != NUL)
{
if (*s == K_SPECIAL && s[1] != NUL && s[2] != NUL)
{
/* Insert special key literally. */
stuffReadbuffLen(s, 3L);
s += 3;
}
else
{
c = mb_ptr2char_adv(&s);
if (c == CAR || c == NL || c == ESC)
c = ' ';
stuffcharReadbuff(c);
}
}
}
#endif
/*
* Append a character to the stuff buffer.
* Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
*/
void
stuffcharReadbuff(int c)
{
add_char_buff(&readbuf1, c);
}
/*
* Append a number to the stuff buffer.
*/
void
stuffnumReadbuff(long n)
{
add_num_buff(&readbuf1, n);
}
/*
* Read a character from the redo buffer. Translates K_SPECIAL, CSI and
* multibyte characters.
* The redo buffer is left as it is.
* If init is TRUE, prepare for redo, return FAIL if nothing to redo, OK
* otherwise.
* If old is TRUE, use old_redobuff instead of redobuff.
*/
static int
read_redo(int init, int old_redo)
{
static buffblock_T *bp;
static char_u *p;
int c;
int n;
char_u buf[MB_MAXBYTES + 1];
int i;
if (init)
{
if (old_redo)
bp = old_redobuff.bh_first.b_next;
else
bp = redobuff.bh_first.b_next;
if (bp == NULL)
return FAIL;
p = bp->b_str;
return OK;
}
if ((c = *p) != NUL)
{
/* Reverse the conversion done by add_char_buff() */
/* For a multi-byte character get all the bytes and return the
* converted character. */
if (has_mbyte && (c != K_SPECIAL || p[1] == KS_SPECIAL))
n = MB_BYTE2LEN_CHECK(c);
else
n = 1;
for (i = 0; ; ++i)
{
if (c == K_SPECIAL) /* special key or escaped K_SPECIAL */
{
c = TO_SPECIAL(p[1], p[2]);
p += 2;
}
#ifdef FEAT_GUI
if (c == CSI) /* escaped CSI */
p += 2;
#endif
if (*++p == NUL && bp->b_next != NULL)
{
bp = bp->b_next;
p = bp->b_str;
}
buf[i] = c;
if (i == n - 1) /* last byte of a character */
{
if (n != 1)
c = (*mb_ptr2char)(buf);
break;
}
c = *p;
if (c == NUL) /* cannot happen? */
break;
}
}
return c;
}
/*
* Copy the rest of the redo buffer into the stuff buffer (in a slow way).
* If old_redo is TRUE, use old_redobuff instead of redobuff.
* The escaped K_SPECIAL and CSI are copied without translation.
*/
static void
copy_redo(int old_redo)
{
int c;
while ((c = read_redo(FALSE, old_redo)) != NUL)
add_char_buff(&readbuf2, c);
}
/*
* Stuff the redo buffer into readbuf2.
* Insert the redo count into the command.
* If "old_redo" is TRUE, the last but one command is repeated
* instead of the last command (inserting text). This is used for
* CTRL-O <.> in insert mode
*
* return FAIL for failure, OK otherwise
*/
int
start_redo(long count, int old_redo)
{
int c;
/* init the pointers; return if nothing to redo */
if (read_redo(TRUE, old_redo) == FAIL)
return FAIL;
c = read_redo(FALSE, old_redo);
/* copy the buffer name, if present */
if (c == '"')
{
add_buff(&readbuf2, (char_u *)"\"", 1L);
c = read_redo(FALSE, old_redo);
/* if a numbered buffer is used, increment the number */
if (c >= '1' && c < '9')
++c;
add_char_buff(&readbuf2, c);
/* the expression register should be re-evaluated */
if (c == '=')
{
add_char_buff(&readbuf2, CAR);
cmd_silent = TRUE;
}
c = read_redo(FALSE, old_redo);
}
if (c == 'v') /* redo Visual */
{
VIsual = curwin->w_cursor;
VIsual_active = TRUE;
VIsual_select = FALSE;
VIsual_reselect = TRUE;
redo_VIsual_busy = TRUE;
c = read_redo(FALSE, old_redo);
}
/* try to enter the count (in place of a previous count) */
if (count)
{
while (VIM_ISDIGIT(c)) /* skip "old" count */
c = read_redo(FALSE, old_redo);
add_num_buff(&readbuf2, count);
}
/* copy from the redo buffer into the stuff buffer */
add_char_buff(&readbuf2, c);
copy_redo(old_redo);
return OK;
}
/*
* Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
* the redo buffer into readbuf2.
* return FAIL for failure, OK otherwise
*/
int
start_redo_ins(void)
{
int c;
if (read_redo(TRUE, FALSE) == FAIL)
return FAIL;
start_stuff();
/* skip the count and the command character */
while ((c = read_redo(FALSE, FALSE)) != NUL)
{
if (vim_strchr((char_u *)"AaIiRrOo", c) != NULL)
{
if (c == 'O' || c == 'o')
add_buff(&readbuf2, NL_STR, -1L);
break;
}
}
/* copy the typed text from the redo buffer into the stuff buffer */
copy_redo(FALSE);
block_redo = TRUE;
return OK;
}
void
stop_redo_ins(void)
{
block_redo = FALSE;
}
/*
* Initialize typebuf.tb_buf to point to typebuf_init.
* alloc() cannot be used here: In out-of-memory situations it would
* be impossible to type anything.
*/
static void
init_typebuf(void)
{
if (typebuf.tb_buf == NULL)
{
typebuf.tb_buf = typebuf_init;
typebuf.tb_noremap = noremapbuf_init;
typebuf.tb_buflen = TYPELEN_INIT;
typebuf.tb_len = 0;
typebuf.tb_off = MAXMAPLEN + 4;
typebuf.tb_change_cnt = 1;
}
}
/*
* Insert a string in position 'offset' in the typeahead buffer (for "@r"
* and ":normal" command, vgetorpeek() and check_termcode()).
*
* If noremap is REMAP_YES, new string can be mapped again.
* If noremap is REMAP_NONE, new string cannot be mapped again.
* If noremap is REMAP_SKIP, fist char of new string cannot be mapped again,
* but abbreviations are allowed.
* If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for
* script-local mappings.
* If noremap is > 0, that many characters of the new string cannot be mapped.
*
* If nottyped is TRUE, the string does not return KeyTyped (don't use when
* offset is non-zero!).
*
* If silent is TRUE, cmd_silent is set when the characters are obtained.
*
* return FAIL for failure, OK otherwise
*/
int
ins_typebuf(
char_u *str,
int noremap,
int offset,
int nottyped,
int silent)
{
char_u *s1, *s2;
int newlen;
int addlen;
int i;
int newoff;
int val;
int nrm;
init_typebuf();
if (++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
addlen = (int)STRLEN(str);
if (offset == 0 && addlen <= typebuf.tb_off)
{
/*
* Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off]
*/
typebuf.tb_off -= addlen;
mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
}
else if (typebuf.tb_len == 0 && typebuf.tb_buflen
>= addlen + 3 * (MAXMAPLEN + 4))
{
/*
* Buffer is empty and string fits in the existing buffer.
* Leave some space before and after, if possible.
*/
typebuf.tb_off = (typebuf.tb_buflen - addlen - 3 * (MAXMAPLEN + 4)) / 2;
mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
}
else
{
/*
* Need to allocate a new buffer.
* In typebuf.tb_buf there must always be room for 3 * (MAXMAPLEN + 4)
* characters. We add some extra room to avoid having to allocate too
* often.
*/
newoff = MAXMAPLEN + 4;
newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4);
if (newlen < 0) /* string is getting too long */
{
emsg(_(e_toocompl)); /* also calls flush_buffers */
setcursor();
return FAIL;
}
s1 = alloc(newlen);
if (s1 == NULL) /* out of memory */
return FAIL;
s2 = alloc(newlen);
if (s2 == NULL) /* out of memory */
{
vim_free(s1);
return FAIL;
}
typebuf.tb_buflen = newlen;
/* copy the old chars, before the insertion point */
mch_memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off,
(size_t)offset);
/* copy the new chars */
mch_memmove(s1 + newoff + offset, str, (size_t)addlen);
/* copy the old chars, after the insertion point, including the NUL at
* the end */
mch_memmove(s1 + newoff + offset + addlen,
typebuf.tb_buf + typebuf.tb_off + offset,
(size_t)(typebuf.tb_len - offset + 1));
if (typebuf.tb_buf != typebuf_init)
vim_free(typebuf.tb_buf);
typebuf.tb_buf = s1;
mch_memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off,
(size_t)offset);
mch_memmove(s2 + newoff + offset + addlen,
typebuf.tb_noremap + typebuf.tb_off + offset,
(size_t)(typebuf.tb_len - offset));
if (typebuf.tb_noremap != noremapbuf_init)
vim_free(typebuf.tb_noremap);
typebuf.tb_noremap = s2;
typebuf.tb_off = newoff;
}
typebuf.tb_len += addlen;
/* If noremap == REMAP_SCRIPT: do remap script-local mappings. */
if (noremap == REMAP_SCRIPT)
val = RM_SCRIPT;
else if (noremap == REMAP_SKIP)
val = RM_ABBR;
else
val = RM_NONE;
/*
* Adjust typebuf.tb_noremap[] for the new characters:
* If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
* (sometimes) not remappable
* If noremap == REMAP_YES: all the new characters are mappable
* If noremap > 0: "noremap" characters are not remappable, the rest
* mappable
*/
if (noremap == REMAP_SKIP)
nrm = 1;
else if (noremap < 0)
nrm = addlen;
else
nrm = noremap;
for (i = 0; i < addlen; ++i)
typebuf.tb_noremap[typebuf.tb_off + i + offset] =
(--nrm >= 0) ? val : RM_YES;
/* tb_maplen and tb_silent only remember the length of mapped and/or
* silent mappings at the start of the buffer, assuming that a mapped
* sequence doesn't result in typed characters. */
if (nottyped || typebuf.tb_maplen > offset)
typebuf.tb_maplen += addlen;
if (silent || typebuf.tb_silent > offset)
{
typebuf.tb_silent += addlen;
cmd_silent = TRUE;
}
if (typebuf.tb_no_abbr_cnt && offset == 0) /* and not used for abbrev.s */
typebuf.tb_no_abbr_cnt += addlen;
return OK;
}
/*
* Put character "c" back into the typeahead buffer.
* Can be used for a character obtained by vgetc() that needs to be put back.
* Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to
* the char.
*/
void
ins_char_typebuf(int c)
{
char_u buf[MB_MAXBYTES + 1];
if (IS_SPECIAL(c))
{
buf[0] = K_SPECIAL;
buf[1] = K_SECOND(c);
buf[2] = K_THIRD(c);
buf[3] = NUL;
}
else
buf[(*mb_char2bytes)(c, buf)] = NUL;
(void)ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent);
}
/*
* Return TRUE if the typeahead buffer was changed (while waiting for a
* character to arrive). Happens when a message was received from a client or
* from feedkeys().
* But check in a more generic way to avoid trouble: When "typebuf.tb_buf"
* changed it was reallocated and the old pointer can no longer be used.
* Or "typebuf.tb_off" may have been changed and we would overwrite characters
* that was just added.
*/
int
typebuf_changed(
int tb_change_cnt) /* old value of typebuf.tb_change_cnt */
{
return (tb_change_cnt != 0 && (typebuf.tb_change_cnt != tb_change_cnt
#if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
|| typebuf_was_filled
#endif
));
}
/*
* Return TRUE if there are no characters in the typeahead buffer that have
* not been typed (result from a mapping or come from ":normal").
*/
int
typebuf_typed(void)
{
return typebuf.tb_maplen == 0;
}
/*
* Return the number of characters that are mapped (or not typed).
*/
int
typebuf_maplen(void)
{
return typebuf.tb_maplen;
}
/*
* remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
*/
void
del_typebuf(int len, int offset)
{
int i;
if (len == 0)
return; /* nothing to do */
typebuf.tb_len -= len;
/*
* Easy case: Just increase typebuf.tb_off.
*/
if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
>= 3 * MAXMAPLEN + 3)
typebuf.tb_off += len;
/*
* Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
*/
else
{
i = typebuf.tb_off + offset;
/*
* Leave some extra room at the end to avoid reallocation.
*/
if (typebuf.tb_off > MAXMAPLEN)
{
mch_memmove(typebuf.tb_buf + MAXMAPLEN,
typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
mch_memmove(typebuf.tb_noremap + MAXMAPLEN,
typebuf.tb_noremap + typebuf.tb_off, (size_t)offset);
typebuf.tb_off = MAXMAPLEN;
}
/* adjust typebuf.tb_buf (include the NUL at the end) */
mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset,
typebuf.tb_buf + i + len,
(size_t)(typebuf.tb_len - offset + 1));
/* adjust typebuf.tb_noremap[] */
mch_memmove(typebuf.tb_noremap + typebuf.tb_off + offset,
typebuf.tb_noremap + i + len,
(size_t)(typebuf.tb_len - offset));
}
if (typebuf.tb_maplen > offset) /* adjust tb_maplen */
{
if (typebuf.tb_maplen < offset + len)
typebuf.tb_maplen = offset;
else
typebuf.tb_maplen -= len;
}
if (typebuf.tb_silent > offset) /* adjust tb_silent */
{
if (typebuf.tb_silent < offset + len)
typebuf.tb_silent = offset;
else
typebuf.tb_silent -= len;
}
if (typebuf.tb_no_abbr_cnt > offset) /* adjust tb_no_abbr_cnt */
{
if (typebuf.tb_no_abbr_cnt < offset + len)
typebuf.tb_no_abbr_cnt = offset;
else
typebuf.tb_no_abbr_cnt -= len;
}
#if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
/* Reset the flag that text received from a client or from feedkeys()
* was inserted in the typeahead buffer. */
typebuf_was_filled = FALSE;
#endif
if (++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
}
/*
* Write typed characters to script file.
* If recording is on put the character in the recordbuffer.
*/
static void
gotchars(char_u *chars, int len)
{
char_u *s = chars;
int i;
static char_u buf[4];
static int buflen = 0;
int todo = len;
while (todo--)
{
buf[buflen++] = *s++;
// When receiving a special key sequence, store it until we have all
// the bytes and we can decide what to do with it.
if (buflen == 1 && buf[0] == K_SPECIAL)
continue;
if (buflen == 2)
continue;
if (buflen == 3 && buf[1] == KS_EXTRA
&& (buf[2] == KE_FOCUSGAINED || buf[2] == KE_FOCUSLOST))
{
// Drop K_FOCUSGAINED and K_FOCUSLOST, they are not useful in a
// recording.
buflen = 0;
continue;
}
/* Handle one byte at a time; no translation to be done. */
for (i = 0; i < buflen; ++i)
updatescript(buf[i]);
if (reg_recording != 0)
{
buf[buflen] = NUL;
add_buff(&recordbuff, buf, (long)buflen);
/* remember how many chars were last recorded */
last_recorded_len += buflen;
}
buflen = 0;
}
may_sync_undo();
#ifdef FEAT_EVAL
/* output "debug mode" message next time in debug mode */
debug_did_msg = FALSE;
#endif
/* Since characters have been typed, consider the following to be in
* another mapping. Search string will be kept in history. */
++maptick;
}
/*
* Sync undo. Called when typed characters are obtained from the typeahead
* buffer, or when a menu is used.
* Do not sync:
* - In Insert mode, unless cursor key has been used.
* - While reading a script file.
* - When no_u_sync is non-zero.
*/
static void
may_sync_undo(void)
{
if ((!(State & (INSERT + CMDLINE)) || arrow_used)
&& scriptin[curscript] == NULL)
u_sync(FALSE);
}
/*
* Make "typebuf" empty and allocate new buffers.
* Returns FAIL when out of memory.
*/
int
alloc_typebuf(void)
{
typebuf.tb_buf = alloc(TYPELEN_INIT);
typebuf.tb_noremap = alloc(TYPELEN_INIT);
if (typebuf.tb_buf == NULL || typebuf.tb_noremap == NULL)
{
free_typebuf();
return FAIL;
}
typebuf.tb_buflen = TYPELEN_INIT;
typebuf.tb_off = MAXMAPLEN + 4; /* can insert without realloc */
typebuf.tb_len = 0;
typebuf.tb_maplen = 0;
typebuf.tb_silent = 0;
typebuf.tb_no_abbr_cnt = 0;
if (++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
return OK;
}
/*
* Free the buffers of "typebuf".
*/
void
free_typebuf(void)
{
if (typebuf.tb_buf == typebuf_init)
internal_error("Free typebuf 1");
else
vim_free(typebuf.tb_buf);
if (typebuf.tb_noremap == noremapbuf_init)
internal_error("Free typebuf 2");
else
vim_free(typebuf.tb_noremap);
}
/*
* When doing ":so! file", the current typeahead needs to be saved, and
* restored when "file" has been read completely.
*/
static typebuf_T saved_typebuf[NSCRIPT];
int
save_typebuf(void)
{
init_typebuf();
saved_typebuf[curscript] = typebuf;
/* If out of memory: restore typebuf and close file. */
if (alloc_typebuf() == FAIL)
{
closescript();
return FAIL;
}
return OK;
}
static int old_char = -1; /* character put back by vungetc() */
static int old_mod_mask; /* mod_mask for ungotten character */
#ifdef FEAT_MOUSE
static int old_mouse_row; /* mouse_row related to old_char */
static int old_mouse_col; /* mouse_col related to old_char */
#endif
/*
* Save all three kinds of typeahead, so that the user must type at a prompt.
*/
void
save_typeahead(tasave_T *tp)
{
tp->save_typebuf = typebuf;
tp->typebuf_valid = (alloc_typebuf() == OK);
if (!tp->typebuf_valid)
typebuf = tp->save_typebuf;
tp->old_char = old_char;
tp->old_mod_mask = old_mod_mask;
old_char = -1;
tp->save_readbuf1 = readbuf1;
readbuf1.bh_first.b_next = NULL;
tp->save_readbuf2 = readbuf2;
readbuf2.bh_first.b_next = NULL;
# ifdef USE_INPUT_BUF
tp->save_inputbuf = get_input_buf();
# endif
}
/*
* Restore the typeahead to what it was before calling save_typeahead().
* The allocated memory is freed, can only be called once!
*/
void
restore_typeahead(tasave_T *tp)
{
if (tp->typebuf_valid)
{
free_typebuf();
typebuf = tp->save_typebuf;
}
old_char = tp->old_char;
old_mod_mask = tp->old_mod_mask;
free_buff(&readbuf1);
readbuf1 = tp->save_readbuf1;
free_buff(&readbuf2);
readbuf2 = tp->save_readbuf2;
# ifdef USE_INPUT_BUF
set_input_buf(tp->save_inputbuf);
# endif
}
/*
* Open a new script file for the ":source!" command.
*/
void
openscript(
char_u *name,
int directly) /* when TRUE execute directly */
{
if (curscript + 1 == NSCRIPT)
{
emsg(_(e_nesting));
return;
}
#ifdef FEAT_EVAL
if (ignore_script)
/* Not reading from script, also don't open one. Warning message? */
return;
#endif
if (scriptin[curscript] != NULL) /* already reading script */
++curscript;
/* use NameBuff for expanded name */
expand_env(name, NameBuff, MAXPATHL);
if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
{
semsg(_(e_notopen), name);
if (curscript)
--curscript;
return;
}
if (save_typebuf() == FAIL)
return;
/*
* Execute the commands from the file right now when using ":source!"
* after ":global" or ":argdo" or in a loop. Also when another command
* follows. This means the display won't be updated. Don't do this
* always, "make test" would fail.
*/
if (directly)
{
oparg_T oa;
int oldcurscript;
int save_State = State;
int save_restart_edit = restart_edit;
int save_insertmode = p_im;
int save_finish_op = finish_op;
int save_msg_scroll = msg_scroll;
State = NORMAL;
msg_scroll = FALSE; /* no msg scrolling in Normal mode */
restart_edit = 0; /* don't go to Insert mode */
p_im = FALSE; /* don't use 'insertmode' */
clear_oparg(&oa);
finish_op = FALSE;
oldcurscript = curscript;
do
{
update_topline_cursor(); // update cursor position and topline
normal_cmd(&oa, FALSE); // execute one command
vpeekc(); // check for end of file
}
while (scriptin[oldcurscript] != NULL);
State = save_State;
msg_scroll = save_msg_scroll;
restart_edit = save_restart_edit;
p_im = save_insertmode;
finish_op = save_finish_op;
}
}
/*
* Close the currently active input script.
*/
static void
closescript(void)
{
free_typebuf();
typebuf = saved_typebuf[curscript];
fclose(scriptin[curscript]);
scriptin[curscript] = NULL;
if (curscript > 0)
--curscript;
}
#if defined(EXITFREE) || defined(PROTO)
void
close_all_scripts(void)
{
while (scriptin[0] != NULL)
closescript();
}
#endif
#if defined(FEAT_INS_EXPAND) || defined(PROTO)
/*
* Return TRUE when reading keys from a script file.
*/
int
using_script(void)
{
return scriptin[curscript] != NULL;
}
#endif
/*
* This function is called just before doing a blocking wait. Thus after
* waiting 'updatetime' for a character to arrive.
*/
void
before_blocking(void)
{
updatescript(0);
#ifdef FEAT_EVAL
if (may_garbage_collect)
garbage_collect(FALSE);
#endif
}
/*
* updatescipt() is called when a character can be written into the script file
* or when we have waited some time for a character (c == 0)
*
* All the changed memfiles are synced if c == 0 or when the number of typed
* characters reaches 'updatecount' and 'updatecount' is non-zero.
*/
void
updatescript(int c)
{
static int count = 0;
if (c && scriptout)
putc(c, scriptout);
if (c == 0 || (p_uc > 0 && ++count >= p_uc))
{
ml_sync_all(c == 0, TRUE);
count = 0;
}
}
/*
* Get the next input character.
* Can return a special key or a multi-byte character.
* Can return NUL when called recursively, use safe_vgetc() if that's not
* wanted.
* This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte.
* Collects the bytes of a multibyte character into the whole character.
* Returns the modifiers in the global "mod_mask".
*/
int
vgetc(void)
{
int c, c2;
int n;
char_u buf[MB_MAXBYTES + 1];
int i;
#ifdef FEAT_EVAL
/* Do garbage collection when garbagecollect() was called previously and
* we are now at the toplevel. */
if (may_garbage_collect && want_garbage_collect)
garbage_collect(FALSE);
#endif
/*
* If a character was put back with vungetc, it was already processed.
* Return it directly.
*/
if (old_char != -1)
{
c = old_char;
old_char = -1;
mod_mask = old_mod_mask;
#ifdef FEAT_MOUSE
mouse_row = old_mouse_row;
mouse_col = old_mouse_col;
#endif
}
else
{
mod_mask = 0x0;
last_recorded_len = 0;
for (;;) // this is done twice if there are modifiers
{
int did_inc = FALSE;
if (mod_mask
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
|| im_is_preediting()
#endif
)
{
// no mapping after modifier has been read
++no_mapping;
++allow_keys;
did_inc = TRUE; // mod_mask may change value
}
c = vgetorpeek(TRUE);
if (did_inc)
{
--no_mapping;
--allow_keys;
}
// Get two extra bytes for special keys
if (c == K_SPECIAL
#ifdef FEAT_GUI
|| (gui.in_use && c == CSI)
#endif
)
{
int save_allow_keys = allow_keys;
++no_mapping;
allow_keys = 0; // make sure BS is not found
c2 = vgetorpeek(TRUE); // no mapping for these chars
c = vgetorpeek(TRUE);
--no_mapping;
allow_keys = save_allow_keys;
if (c2 == KS_MODIFIER)
{
mod_mask = c;
continue;
}
c = TO_SPECIAL(c2, c);
#if defined(FEAT_GUI_MSWIN) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
// Handle K_TEAROFF here, the caller of vgetc() doesn't need to
// know that a menu was torn off
if (
# ifdef VIMDLL
gui.in_use &&
# endif
c == K_TEAROFF)
{
char_u name[200];
int i;
// get menu path, it ends with a <CR>
for (i = 0; (c = vgetorpeek(TRUE)) != '\r'; )
{
name[i] = c;
if (i < 199)
++i;
}
name[i] = NUL;
gui_make_tearoff(name);
continue;
}
#endif
#if defined(FEAT_GUI) && defined(FEAT_GUI_GTK) && defined(FEAT_MENU)
// GTK: <F10> normally selects the menu, but it's passed until
// here to allow mapping it. Intercept and invoke the GTK
// behavior if it's not mapped.
if (c == K_F10 && gui.menubar != NULL)
{
gtk_menu_shell_select_first(
GTK_MENU_SHELL(gui.menubar), FALSE);
continue;
}
#endif
#ifdef FEAT_GUI
if (gui.in_use)
{
// Handle focus event here, so that the caller doesn't
// need to know about it. Return K_IGNORE so that we loop
// once (needed if 'lazyredraw' is set).
if (c == K_FOCUSGAINED || c == K_FOCUSLOST)
{
ui_focus_change(c == K_FOCUSGAINED);
c = K_IGNORE;
}
// Translate K_CSI to CSI. The special key is only used
// to avoid it being recognized as the start of a special
// key.
if (c == K_CSI)
c = CSI;
}
#endif
}
// a keypad or special function key was not mapped, use it like
// its ASCII equivalent
switch (c)
{
case K_KPLUS: c = '+'; break;
case K_KMINUS: c = '-'; break;
case K_KDIVIDE: c = '/'; break;
case K_KMULTIPLY: c = '*'; break;
case K_KENTER: c = CAR; break;
case K_KPOINT:
#ifdef MSWIN
// Can be either '.' or a ',',
// depending on the type of keypad.
c = MapVirtualKey(VK_DECIMAL, 2); break;
#else
c = '.'; break;
#endif
case K_K0: c = '0'; break;
case K_K1: c = '1'; break;
case K_K2: c = '2'; break;
case K_K3: c = '3'; break;
case K_K4: c = '4'; break;
case K_K5: c = '5'; break;
case K_K6: c = '6'; break;
case K_K7: c = '7'; break;
case K_K8: c = '8'; break;
case K_K9: c = '9'; break;
case K_XHOME:
case K_ZHOME: if (mod_mask == MOD_MASK_SHIFT)
{
c = K_S_HOME;
mod_mask = 0;
}
else if (mod_mask == MOD_MASK_CTRL)
{
c = K_C_HOME;
mod_mask = 0;
}
else
c = K_HOME;
break;
case K_XEND:
case K_ZEND: if (mod_mask == MOD_MASK_SHIFT)
{
c = K_S_END;
mod_mask = 0;
}
else if (mod_mask == MOD_MASK_CTRL)
{
c = K_C_END;
mod_mask = 0;
}
else
c = K_END;
break;
case K_XUP: c = K_UP; break;
case K_XDOWN: c = K_DOWN; break;
case K_XLEFT: c = K_LEFT; break;
case K_XRIGHT: c = K_RIGHT; break;
}
// For a multi-byte character get all the bytes and return the
// converted character.
// Note: This will loop until enough bytes are received!
if (has_mbyte && (n = MB_BYTE2LEN_CHECK(c)) > 1)
{
++no_mapping;
buf[0] = c;
for (i = 1; i < n; ++i)
{
buf[i] = vgetorpeek(TRUE);
if (buf[i] == K_SPECIAL
#ifdef FEAT_GUI
|| (
# ifdef VIMDLL
gui.in_use &&
# endif
buf[i] == CSI)
#endif
)
{
// Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER
// sequence, which represents a K_SPECIAL (0x80),
// or a CSI - KS_EXTRA - KE_CSI sequence, which
// represents a CSI (0x9B),
// or a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI
// too.
c = vgetorpeek(TRUE);
if (vgetorpeek(TRUE) == (int)KE_CSI && c == KS_EXTRA)
buf[i] = CSI;
}
}
--no_mapping;
c = (*mb_ptr2char)(buf);
}
break;
}
}
#ifdef FEAT_EVAL
/*
* In the main loop "may_garbage_collect" can be set to do garbage
* collection in the first next vgetc(). It's disabled after that to
* avoid internally used Lists and Dicts to be freed.
*/
may_garbage_collect = FALSE;
#endif
#ifdef FEAT_BEVAL_TERM
if (c != K_MOUSEMOVE && c != K_IGNORE)
{
/* Don't trigger 'balloonexpr' unless only the mouse was moved. */
bevalexpr_due_set = FALSE;
ui_remove_balloon();
}
#endif
return c;
}
/*
* Like vgetc(), but never return a NUL when called recursively, get a key
* directly from the user (ignoring typeahead).
*/
int
safe_vgetc(void)
{
int c;
c = vgetc();
if (c == NUL)
c = get_keystroke();
return c;
}
/*
* Like safe_vgetc(), but loop to handle K_IGNORE.
* Also ignore scrollbar events.
*/
int
plain_vgetc(void)
{
int c;
do
c = safe_vgetc();
while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
if (c == K_PS)
/* Only handle the first pasted character. Drop the rest, since we
* don't know what to do with it. */
c = bracketed_paste(PASTE_ONE_CHAR, FALSE, NULL);
return c;
}
/*
* Check if a character is available, such that vgetc() will not block.
* If the next character is a special character or multi-byte, the returned
* character is not valid!.
* Returns NUL if no character is available.
*/
int
vpeekc(void)
{
if (old_char != -1)
return old_char;
return vgetorpeek(FALSE);
}
#if defined(FEAT_TERMRESPONSE) || defined(FEAT_TERMINAL) || defined(PROTO)
/*
* Like vpeekc(), but don't allow mapping. Do allow checking for terminal
* codes.
*/
int
vpeekc_nomap(void)
{
int c;
++no_mapping;
++allow_keys;
c = vpeekc();
--no_mapping;
--allow_keys;
return c;
}
#endif
#if defined(FEAT_INS_EXPAND) || defined(FEAT_EVAL) || defined(PROTO)
/*
* Check if any character is available, also half an escape sequence.
* Trick: when no typeahead found, but there is something in the typeahead
* buffer, it must be an ESC that is recognized as the start of a key code.
*/
int
vpeekc_any(void)
{
int c;
c = vpeekc();
if (c == NUL && typebuf.tb_len > 0)
c = ESC;
return c;
}
#endif
/*
* Call vpeekc() without causing anything to be mapped.
* Return TRUE if a character is available, FALSE otherwise.
*/
int
char_avail(void)
{
int retval;
#ifdef FEAT_EVAL
/* When test_override("char_avail", 1) was called pretend there is no
* typeahead. */
if (disable_char_avail_for_testing)
return FALSE;
#endif
++no_mapping;
retval = vpeekc();
--no_mapping;
return (retval != NUL);
}
/*
* unget one character (can only be done once!)
*/
void
vungetc(int c)
{
old_char = c;
old_mod_mask = mod_mask;
#ifdef FEAT_MOUSE
old_mouse_row = mouse_row;
old_mouse_col = mouse_col;
#endif
}
/*
* Get a byte:
* 1. from the stuffbuffer
* This is used for abbreviated commands like "D" -> "d$".
* Also used to redo a command for ".".
* 2. from the typeahead buffer
* Stores text obtained previously but not used yet.
* Also stores the result of mappings.
* Also used for the ":normal" command.
* 3. from the user
* This may do a blocking wait if "advance" is TRUE.
*
* if "advance" is TRUE (vgetc()):
* Really get the character.
* KeyTyped is set to TRUE in the case the user typed the key.
* KeyStuffed is TRUE if the character comes from the stuff buffer.
* if "advance" is FALSE (vpeekc()):
* Just look whether there is a character available.
* Return NUL if not.
*
* When "no_mapping" is zero, checks for mappings in the current mode.
* Only returns one byte (of a multi-byte character).
* K_SPECIAL and CSI may be escaped, need to get two more bytes then.
*/
static int
vgetorpeek(int advance)
{
int c, c1;
int keylen;
char_u *s;
mapblock_T *mp;
#ifdef FEAT_LOCALMAP
mapblock_T *mp2;
#endif
mapblock_T *mp_match;
int mp_match_len = 0;
int timedout = FALSE; /* waited for more than 1 second
for mapping to complete */
int mapdepth = 0; /* check for recursive mapping */
int mode_deleted = FALSE; /* set when mode has been deleted */
int local_State;
int mlen;
int max_mlen;
int i;
#ifdef FEAT_CMDL_INFO
int new_wcol, new_wrow;
#endif
#ifdef FEAT_GUI
# ifdef FEAT_MENU
int idx;
# endif
int shape_changed = FALSE; /* adjusted cursor shape */
#endif
int n;
#ifdef FEAT_LANGMAP
int nolmaplen;
#endif
int old_wcol, old_wrow;
int wait_tb_len;
/*
* This function doesn't work very well when called recursively. This may
* happen though, because of:
* 1. The call to add_to_showcmd(). char_avail() is then used to check if
* there is a character available, which calls this function. In that
* case we must return NUL, to indicate no character is available.
* 2. A GUI callback function writes to the screen, causing a
* wait_return().
* Using ":normal" can also do this, but it saves the typeahead buffer,
* thus it should be OK. But don't get a key from the user then.
*/
if (vgetc_busy > 0 && ex_normal_busy == 0)
return NUL;
local_State = get_real_state();
++vgetc_busy;
if (advance)
KeyStuffed = FALSE;
init_typebuf();
start_stuff();
if (advance && typebuf.tb_maplen == 0)
reg_executing = 0;
do
{
/*
* get a character: 1. from the stuffbuffer
*/
if (typeahead_char != 0)
{
c = typeahead_char;
if (advance)
typeahead_char = 0;
}
else
c = read_readbuffers(advance);
if (c != NUL && !got_int)
{
if (advance)
{
/* KeyTyped = FALSE; When the command that stuffed something
* was typed, behave like the stuffed command was typed.
* needed for CTRL-W CTRL-] to open a fold, for example. */
KeyStuffed = TRUE;
}
if (typebuf.tb_no_abbr_cnt == 0)
typebuf.tb_no_abbr_cnt = 1; /* no abbreviations now */
}
else
{
/*
* Loop until we either find a matching mapped key, or we
* are sure that it is not a mapped key.
* If a mapped key sequence is found we go back to the start to
* try re-mapping.
*/
for (;;)
{
long wait_time;
/*
* ui_breakcheck() is slow, don't use it too often when
* inside a mapping. But call it each time for typed
* characters.
*/
if (typebuf.tb_maplen)
line_breakcheck();
else
ui_breakcheck(); /* check for CTRL-C */
keylen = 0;
if (got_int)
{
/* flush all input */
c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0L);
/*
* If inchar() returns TRUE (script file was active) or we
* are inside a mapping, get out of Insert mode.
* Otherwise we behave like having gotten a CTRL-C.
* As a result typing CTRL-C in insert mode will
* really insert a CTRL-C.
*/
if ((c || typebuf.tb_maplen)
&& (State & (INSERT + CMDLINE)))
c = ESC;
else
c = Ctrl_C;
flush_buffers(FLUSH_INPUT); // flush all typeahead
if (advance)
{
/* Also record this character, it might be needed to
* get out of Insert mode. */
*typebuf.tb_buf = c;
gotchars(typebuf.tb_buf, 1);
}
cmd_silent = FALSE;
break;
}
else if (typebuf.tb_len > 0)
{
/*
* Check for a mappable key sequence.
* Walk through one maphash[] list until we find an
* entry that matches.
*
* Don't look for mappings if:
* - no_mapping set: mapping disabled (e.g. for CTRL-V)
* - maphash_valid not set: no mappings present.
* - typebuf.tb_buf[typebuf.tb_off] should not be remapped
* - in insert or cmdline mode and 'paste' option set
* - waiting for "hit return to continue" and CR or SPACE
* typed
* - waiting for a char with --more--
* - in Ctrl-X mode, and we get a valid char for that mode
*/
mp = NULL;
max_mlen = 0;
c1 = typebuf.tb_buf[typebuf.tb_off];
if (no_mapping == 0 && maphash_valid
&& (no_zero_mapping == 0 || c1 != '0')
&& (typebuf.tb_maplen == 0
|| (p_remap
&& (typebuf.tb_noremap[typebuf.tb_off]
& (RM_NONE|RM_ABBR)) == 0))
&& !(p_paste && (State & (INSERT + CMDLINE)))
&& !(State == HITRETURN && (c1 == CAR || c1 == ' '))
&& State != ASKMORE
&& State != CONFIRM
#ifdef FEAT_INS_EXPAND
&& !((ctrl_x_mode_not_default()
&& vim_is_ctrl_x_key(c1))
|| ((compl_cont_status & CONT_LOCAL)
&& (c1 == Ctrl_N || c1 == Ctrl_P)))
#endif
)
{
#ifdef FEAT_LANGMAP
if (c1 == K_SPECIAL)
nolmaplen = 2;
else
{
LANGMAP_ADJUST(c1,
(State & (CMDLINE | INSERT)) == 0
&& get_real_state() != SELECTMODE);
nolmaplen = 0;
}
#endif
#ifdef FEAT_LOCALMAP
/* First try buffer-local mappings. */
mp = curbuf->b_maphash[MAP_HASH(local_State, c1)];
mp2 = maphash[MAP_HASH(local_State, c1)];
if (mp == NULL)
{
/* There are no buffer-local mappings. */
mp = mp2;
mp2 = NULL;
}
#else
mp = maphash[MAP_HASH(local_State, c1)];
#endif
/*
* Loop until a partly matching mapping is found or
* all (local) mappings have been checked.
* The longest full match is remembered in "mp_match".
* A full match is only accepted if there is no partly
* match, so "aa" and "aaa" can both be mapped.
*/
mp_match = NULL;
mp_match_len = 0;
for ( ; mp != NULL;
#ifdef FEAT_LOCALMAP
mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
#endif
(mp = mp->m_next))
{
/*
* Only consider an entry if the first character
* matches and it is for the current state.
* Skip ":lmap" mappings if keys were mapped.
*/
if (mp->m_keys[0] == c1
&& (mp->m_mode & local_State)
&& ((mp->m_mode & LANGMAP) == 0
|| typebuf.tb_maplen == 0))
{
#ifdef FEAT_LANGMAP
int nomap = nolmaplen;
int c2;
#endif
/* find the match length of this mapping */
for (mlen = 1; mlen < typebuf.tb_len; ++mlen)
{
#ifdef FEAT_LANGMAP
c2 = typebuf.tb_buf[typebuf.tb_off + mlen];
if (nomap > 0)
--nomap;
else if (c2 == K_SPECIAL)
nomap = 2;
else
LANGMAP_ADJUST(c2, TRUE);
if (mp->m_keys[mlen] != c2)
#else
if (mp->m_keys[mlen] !=
typebuf.tb_buf[typebuf.tb_off + mlen])
#endif
break;
}
/* Don't allow mapping the first byte(s) of a
* multi-byte char. Happens when mapping
* <M-a> and then changing 'encoding'. Beware
* that 0x80 is escaped. */
{
char_u *p1 = mp->m_keys;
char_u *p2 = mb_unescape(&p1);
if (has_mbyte && p2 != NULL
&& MB_BYTE2LEN(c1) > MB_PTR2LEN(p2))
mlen = 0;
}
/*
* Check an entry whether it matches.
* - Full match: mlen == keylen
* - Partly match: mlen == typebuf.tb_len
*/
keylen = mp->m_keylen;
if (mlen == keylen
|| (mlen == typebuf.tb_len
&& typebuf.tb_len < keylen))
{
/*
* If only script-local mappings are
* allowed, check if the mapping starts
* with K_SNR.
*/
s = typebuf.tb_noremap + typebuf.tb_off;
if (*s == RM_SCRIPT
&& (mp->m_keys[0] != K_SPECIAL
|| mp->m_keys[1] != KS_EXTRA
|| mp->m_keys[2]
!= (int)KE_SNR))
continue;
/*
* If one of the typed keys cannot be
* remapped, skip the entry.
*/
for (n = mlen; --n >= 0; )
if (*s++ & (RM_NONE|RM_ABBR))
break;
if (n >= 0)
continue;
if (keylen > typebuf.tb_len)
{
if (!timedout && !(mp_match != NULL
&& mp_match->m_nowait))
{
/* break at a partly match */
keylen = KEYLEN_PART_MAP;
break;
}
}
else if (keylen > mp_match_len)
{
/* found a longer match */
mp_match = mp;
mp_match_len = keylen;
}
}
else
/* No match; may have to check for
* termcode at next character. */
if (max_mlen < mlen)
max_mlen = mlen;
}
}
/* If no partly match found, use the longest full
* match. */
if (keylen != KEYLEN_PART_MAP)
{
mp = mp_match;
keylen = mp_match_len;
}
}
/* Check for match with 'pastetoggle' */
if (*p_pt != NUL && mp == NULL && (State & (INSERT|NORMAL)))
{
for (mlen = 0; mlen < typebuf.tb_len && p_pt[mlen];
++mlen)
if (p_pt[mlen] != typebuf.tb_buf[typebuf.tb_off
+ mlen])
break;
if (p_pt[mlen] == NUL) /* match */
{
/* write chars to script file(s) */
if (mlen > typebuf.tb_maplen)
gotchars(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_maplen,
mlen - typebuf.tb_maplen);
del_typebuf(mlen, 0); /* remove the chars */
set_option_value((char_u *)"paste",
(long)!p_paste, NULL, 0);
if (!(State & INSERT))
{
msg_col = 0;
msg_row = Rows - 1;
msg_clr_eos(); /* clear ruler */
}
status_redraw_all();
redraw_statuslines();
showmode();
setcursor();
continue;
}
/* Need more chars for partly match. */
if (mlen == typebuf.tb_len)
keylen = KEYLEN_PART_KEY;
else if (max_mlen < mlen)
/* no match, may have to check for termcode at
* next character */
max_mlen = mlen + 1;
}
if ((mp == NULL || max_mlen >= mp_match_len)
&& keylen != KEYLEN_PART_MAP)
{
int save_keylen = keylen;
/*
* When no matching mapping found or found a
* non-matching mapping that matches at least what the
* matching mapping matched:
* Check if we have a terminal code, when:
* mapping is allowed,
* keys have not been mapped,
* and not an ESC sequence, not in insert mode or
* p_ek is on,
* and when not timed out,
*/
if ((no_mapping == 0 || allow_keys != 0)
&& (typebuf.tb_maplen == 0
|| (p_remap && typebuf.tb_noremap[
typebuf.tb_off] == RM_YES))
&& !timedout)
{
keylen = check_termcode(max_mlen + 1,
NULL, 0, NULL);
/* If no termcode matched but 'pastetoggle'
* matched partially it's like an incomplete key
* sequence. */
if (keylen == 0 && save_keylen == KEYLEN_PART_KEY)
keylen = KEYLEN_PART_KEY;
/*
* When getting a partial match, but the last
* characters were not typed, don't wait for a
* typed character to complete the termcode.
* This helps a lot when a ":normal" command ends
* in an ESC.
*/
if (keylen < 0
&& typebuf.tb_len == typebuf.tb_maplen)
keylen = 0;
}
else
keylen = 0;
if (keylen == 0) /* no matching terminal code */
{
#ifdef AMIGA /* check for window bounds report */
if (typebuf.tb_maplen == 0 && (typebuf.tb_buf[
typebuf.tb_off] & 0xff) == CSI)
{
for (s = typebuf.tb_buf + typebuf.tb_off + 1;
s < typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len
&& (VIM_ISDIGIT(*s) || *s == ';'
|| *s == ' ');
++s)
;
if (*s == 'r' || *s == '|') /* found one */
{
del_typebuf((int)(s + 1 -
(typebuf.tb_buf + typebuf.tb_off)), 0);
/* get size and redraw screen */
shell_resized();
continue;
}
if (*s == NUL) /* need more characters */
keylen = KEYLEN_PART_KEY;
}
if (keylen >= 0)
#endif
/* When there was a matching mapping and no
* termcode could be replaced after another one,
* use that mapping (loop around). If there was
* no mapping use the character from the
* typeahead buffer right here. */
if (mp == NULL)
{
/*
* get a character: 2. from the typeahead buffer
*/
c = typebuf.tb_buf[typebuf.tb_off] & 255;
if (advance) /* remove chars from tb_buf */
{
cmd_silent = (typebuf.tb_silent > 0);
if (typebuf.tb_maplen > 0)
KeyTyped = FALSE;
else
{
KeyTyped = TRUE;
/* write char to script file(s) */
gotchars(typebuf.tb_buf
+ typebuf.tb_off, 1);
}
KeyNoremap = typebuf.tb_noremap[
typebuf.tb_off];
del_typebuf(1, 0);
}
break; /* got character, break for loop */
}
}
if (keylen > 0) /* full matching terminal code */
{
#if defined(FEAT_GUI) && defined(FEAT_MENU)
if (typebuf.tb_len >= 2
&& typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
&& typebuf.tb_buf[typebuf.tb_off + 1]
== KS_MENU)
{
/*
* Using a menu may cause a break in undo!
* It's like using gotchars(), but without
* recording or writing to a script file.
*/
may_sync_undo();
del_typebuf(3, 0);
idx = get_menu_index(current_menu, local_State);
if (idx != MENU_INDEX_INVALID)
{
/*
* In Select mode and a Visual mode menu
* is used: Switch to Visual mode
* temporarily. Append K_SELECT to switch
* back to Select mode.
*/
if (VIsual_active && VIsual_select
&& (current_menu->modes & VISUAL))
{
VIsual_select = FALSE;
(void)ins_typebuf(K_SELECT_STRING,
REMAP_NONE, 0, TRUE, FALSE);
}
ins_typebuf(current_menu->strings[idx],
current_menu->noremap[idx],
0, TRUE,
current_menu->silent[idx]);
}
}
#endif /* FEAT_GUI && FEAT_MENU */
continue; /* try mapping again */
}
/* Partial match: get some more characters. When a
* matching mapping was found use that one. */
if (mp == NULL || keylen < 0)
keylen = KEYLEN_PART_KEY;
else
keylen = mp_match_len;
}
/* complete match */
if (keylen >= 0 && keylen <= typebuf.tb_len)
{
#ifdef FEAT_EVAL
int save_m_expr;
int save_m_noremap;
int save_m_silent;
char_u *save_m_keys;
char_u *save_m_str;
#else
# define save_m_noremap mp->m_noremap
# define save_m_silent mp->m_silent
#endif
/* write chars to script file(s) */
if (keylen > typebuf.tb_maplen)
gotchars(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_maplen,
keylen - typebuf.tb_maplen);
cmd_silent = (typebuf.tb_silent > 0);
del_typebuf(keylen, 0); /* remove the mapped keys */
/*
* Put the replacement string in front of mapstr.
* The depth check catches ":map x y" and ":map y x".
*/
if (++mapdepth >= p_mmd)
{
emsg(_("E223: recursive mapping"));
if (State & CMDLINE)
redrawcmdline();
else
setcursor();
flush_buffers(FLUSH_MINIMAL);
mapdepth = 0; /* for next one */
c = -1;
break;
}
/*
* In Select mode and a Visual mode mapping is used:
* Switch to Visual mode temporarily. Append K_SELECT
* to switch back to Select mode.
*/
if (VIsual_active && VIsual_select
&& (mp->m_mode & VISUAL))
{
VIsual_select = FALSE;
(void)ins_typebuf(K_SELECT_STRING, REMAP_NONE,
0, TRUE, FALSE);
}
#ifdef FEAT_EVAL
/* Copy the values from *mp that are used, because
* evaluating the expression may invoke a function
* that redefines the mapping, thereby making *mp
* invalid. */
save_m_expr = mp->m_expr;
save_m_noremap = mp->m_noremap;
save_m_silent = mp->m_silent;
save_m_keys = NULL; /* only saved when needed */
save_m_str = NULL; /* only saved when needed */
/*
* Handle ":map <expr>": evaluate the {rhs} as an
* expression. Also save and restore the command line
* for "normal :".
*/
if (mp->m_expr)
{
int save_vgetc_busy = vgetc_busy;
vgetc_busy = 0;
save_m_keys = vim_strsave(mp->m_keys);
save_m_str = vim_strsave(mp->m_str);
s = eval_map_expr(save_m_str, NUL);
vgetc_busy = save_vgetc_busy;
}
else
#endif
s = mp->m_str;
/*
* Insert the 'to' part in the typebuf.tb_buf.
* If 'from' field is the same as the start of the
* 'to' field, don't remap the first character (but do
* allow abbreviations).
* If m_noremap is set, don't remap the whole 'to'
* part.
*/
if (s == NULL)
i = FAIL;
else
{
int noremap;
if (save_m_noremap != REMAP_YES)
noremap = save_m_noremap;
else if (
#ifdef FEAT_EVAL
STRNCMP(s, save_m_keys != NULL
? save_m_keys : mp->m_keys,
(size_t)keylen)
#else
STRNCMP(s, mp->m_keys, (size_t)keylen)
#endif
!= 0)
noremap = REMAP_YES;
else
noremap = REMAP_SKIP;
i = ins_typebuf(s, noremap,
0, TRUE, cmd_silent || save_m_silent);
#ifdef FEAT_EVAL
if (save_m_expr)
vim_free(s);
#endif
}
#ifdef FEAT_EVAL
vim_free(save_m_keys);
vim_free(save_m_str);
#endif
if (i == FAIL)
{
c = -1;
break;
}
continue;
}
}
/*
* get a character: 3. from the user - handle <Esc> in Insert mode
*/
/*
* Special case: if we get an <ESC> in insert mode and there
* are no more characters at once, we pretend to go out of
* insert mode. This prevents the one second delay after
* typing an <ESC>. If we get something after all, we may
* have to redisplay the mode. That the cursor is in the wrong
* place does not matter.
*/
c = 0;
#ifdef FEAT_CMDL_INFO
new_wcol = curwin->w_wcol;
new_wrow = curwin->w_wrow;
#endif
if ( advance
&& typebuf.tb_len == 1
&& typebuf.tb_buf[typebuf.tb_off] == ESC
&& !no_mapping
&& ex_normal_busy == 0
&& typebuf.tb_maplen == 0
&& (State & INSERT)
&& (p_timeout
|| (keylen == KEYLEN_PART_KEY && p_ttimeout))
&& (c = inchar(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len, 3, 25L)) == 0)
{
colnr_T col = 0, vcol;
char_u *ptr;
if (mode_displayed)
{
unshowmode(TRUE);
mode_deleted = TRUE;
}
#ifdef FEAT_GUI
/* may show a different cursor shape */
if (gui.in_use && State != NORMAL && !cmd_silent)
{
int save_State;
save_State = State;
State = NORMAL;
gui_update_cursor(TRUE, FALSE);
State = save_State;
shape_changed = TRUE;
}
#endif
validate_cursor();
old_wcol = curwin->w_wcol;
old_wrow = curwin->w_wrow;
/* move cursor left, if possible */
if (curwin->w_cursor.col != 0)
{
if (curwin->w_wcol > 0)
{
if (did_ai)
{
/*
* We are expecting to truncate the trailing
* white-space, so find the last non-white
* character -- webb
*/
col = vcol = curwin->w_wcol = 0;
ptr = ml_get_curline();
while (col < curwin->w_cursor.col)
{
if (!VIM_ISWHITE(ptr[col]))
curwin->w_wcol = vcol;
vcol += lbr_chartabsize(ptr, ptr + col,
(colnr_T)vcol);
if (has_mbyte)
col += (*mb_ptr2len)(ptr + col);
else
++col;
}
curwin->w_wrow = curwin->w_cline_row
+ curwin->w_wcol / curwin->w_width;
curwin->w_wcol %= curwin->w_width;
curwin->w_wcol += curwin_col_off();
col = 0; /* no correction needed */
}
else
{
--curwin->w_wcol;
col = curwin->w_cursor.col - 1;
}
}
else if (curwin->w_p_wrap && curwin->w_wrow)
{
--curwin->w_wrow;
curwin->w_wcol = curwin->w_width - 1;
col = curwin->w_cursor.col - 1;
}
if (has_mbyte && col > 0 && curwin->w_wcol > 0)
{
/* Correct when the cursor is on the right halve
* of a double-wide character. */
ptr = ml_get_curline();
col -= (*mb_head_off)(ptr, ptr + col);
if ((*mb_ptr2cells)(ptr + col) > 1)
--curwin->w_wcol;
}
}
setcursor();
out_flush();
#ifdef FEAT_CMDL_INFO
new_wcol = curwin->w_wcol;
new_wrow = curwin->w_wrow;
#endif
curwin->w_wcol = old_wcol;
curwin->w_wrow = old_wrow;
}
if (c < 0)
continue; /* end of input script reached */
/* Allow mapping for just typed characters. When we get here c
* is the number of extra bytes and typebuf.tb_len is 1. */
for (n = 1; n <= c; ++n)
typebuf.tb_noremap[typebuf.tb_off + n] = RM_YES;
typebuf.tb_len += c;
/* buffer full, don't map */
if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN)
{
timedout = TRUE;
continue;
}
if (ex_normal_busy > 0)
{
#ifdef FEAT_CMDWIN
static int tc = 0;
#endif
/* No typeahead left and inside ":normal". Must return
* something to avoid getting stuck. When an incomplete
* mapping is present, behave like it timed out. */
if (typebuf.tb_len > 0)
{
timedout = TRUE;
continue;
}
/* When 'insertmode' is set, ESC just beeps in Insert
* mode. Use CTRL-L to make edit() return.
* For the command line only CTRL-C always breaks it.
* For the cmdline window: Alternate between ESC and
* CTRL-C: ESC for most situations and CTRL-C to close the
* cmdline window. */
if (p_im && (State & INSERT))
c = Ctrl_L;
#ifdef FEAT_TERMINAL
else if (terminal_is_active())
c = K_CANCEL;
#endif
else if ((State & CMDLINE)
#ifdef FEAT_CMDWIN
|| (cmdwin_type > 0 && tc == ESC)
#endif
)
c = Ctrl_C;
else
c = ESC;
#ifdef FEAT_CMDWIN
tc = c;
#endif
break;
}
/*
* get a character: 3. from the user - update display
*/
/* In insert mode a screen update is skipped when characters
* are still available. But when those available characters
* are part of a mapping, and we are going to do a blocking
* wait here. Need to update the screen to display the
* changed text so far. Also for when 'lazyredraw' is set and
* redrawing was postponed because there was something in the
* input buffer (e.g., termresponse). */
if (((State & INSERT) != 0 || p_lz) && (State & CMDLINE) == 0
&& advance && must_redraw != 0 && !need_wait_return)
{
update_screen(0);
setcursor(); /* put cursor back where it belongs */
}
/*
* If we have a partial match (and are going to wait for more
* input from the user), show the partially matched characters
* to the user with showcmd.
*/
#ifdef FEAT_CMDL_INFO
i = 0;
#endif
c1 = 0;
if (typebuf.tb_len > 0 && advance && !exmode_active)
{
if (((State & (NORMAL | INSERT)) || State == LANGMAP)
&& State != HITRETURN)
{
/* this looks nice when typing a dead character map */
if (State & INSERT
&& ptr2cells(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len - 1) == 1)
{
edit_putchar(typebuf.tb_buf[typebuf.tb_off
+ typebuf.tb_len - 1], FALSE);
setcursor(); /* put cursor back where it belongs */
c1 = 1;
}
#ifdef FEAT_CMDL_INFO
/* need to use the col and row from above here */
old_wcol = curwin->w_wcol;
old_wrow = curwin->w_wrow;
curwin->w_wcol = new_wcol;
curwin->w_wrow = new_wrow;
push_showcmd();
if (typebuf.tb_len > SHOWCMD_COLS)
i = typebuf.tb_len - SHOWCMD_COLS;
while (i < typebuf.tb_len)
(void)add_to_showcmd(typebuf.tb_buf[typebuf.tb_off
+ i++]);
curwin->w_wcol = old_wcol;
curwin->w_wrow = old_wrow;
#endif
}
/* this looks nice when typing a dead character map */
if ((State & CMDLINE)
#if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
&& cmdline_star == 0
#endif
&& ptr2cells(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len - 1) == 1)
{
putcmdline(typebuf.tb_buf[typebuf.tb_off
+ typebuf.tb_len - 1], FALSE);
c1 = 1;
}
}
/*
* get a character: 3. from the user - get it
*/
if (typebuf.tb_len == 0)
// timedout may have been set while waiting for a mapping
// that has a <Nop> RHS.
timedout = FALSE;
if (advance)
{
if (typebuf.tb_len == 0
|| !(p_timeout
|| (p_ttimeout && keylen == KEYLEN_PART_KEY)))
// blocking wait
wait_time = -1L;
else if (keylen == KEYLEN_PART_KEY && p_ttm >= 0)
wait_time = p_ttm;
else
wait_time = p_tm;
}
else
wait_time = 0;
wait_tb_len = typebuf.tb_len;
c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len,
typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1,
wait_time);
#ifdef FEAT_CMDL_INFO
if (i != 0)
pop_showcmd();
#endif
if (c1 == 1)
{
if (State & INSERT)
edit_unputchar();
if (State & CMDLINE)
unputcmdline();
else
setcursor(); /* put cursor back where it belongs */
}
if (c < 0)
continue; /* end of input script reached */
if (c == NUL) /* no character available */
{
if (!advance)
break;
if (wait_tb_len > 0) /* timed out */
{
timedout = TRUE;
continue;
}
}
else
{ /* allow mapping for just typed characters */
while (typebuf.tb_buf[typebuf.tb_off
+ typebuf.tb_len] != NUL)
typebuf.tb_noremap[typebuf.tb_off
+ typebuf.tb_len++] = RM_YES;
#ifdef HAVE_INPUT_METHOD
/* Get IM status right after getting keys, not after the
* timeout for a mapping (focus may be lost by then). */
vgetc_im_active = im_get_status();
#endif
}
} /* for (;;) */
} /* if (!character from stuffbuf) */
/* if advance is FALSE don't loop on NULs */
} while ((c < 0 && c != K_CANCEL) || (advance && c == NUL));
/*
* The "INSERT" message is taken care of here:
* if we return an ESC to exit insert mode, the message is deleted
* if we don't return an ESC but deleted the message before, redisplay it
*/
if (advance && p_smd && msg_silent == 0 && (State & INSERT))
{
if (c == ESC && !mode_deleted && !no_mapping && mode_displayed)
{
if (typebuf.tb_len && !KeyTyped)
redraw_cmdline = TRUE; /* delete mode later */
else
unshowmode(FALSE);
}
else if (c != ESC && mode_deleted)
{
if (typebuf.tb_len && !KeyTyped)
redraw_cmdline = TRUE; /* show mode later */
else
showmode();
}
}
#ifdef FEAT_GUI
/* may unshow different cursor shape */
if (gui.in_use && shape_changed)
gui_update_cursor(TRUE, FALSE);
#endif
if (timedout && c == ESC)
{
char_u nop_buf[3];
// When recording there will be no timeout. Add a <Nop> after the ESC
// to avoid that it forms a key code with following characters.
nop_buf[0] = K_SPECIAL;
nop_buf[1] = KS_EXTRA;
nop_buf[2] = KE_NOP;
gotchars(nop_buf, 3);
}
--vgetc_busy;
return c;
}
/*
* inchar() - get one character from
* 1. a scriptfile
* 2. the keyboard
*
* As much characters as we can get (upto 'maxlen') are put in "buf" and
* NUL terminated (buffer length must be 'maxlen' + 1).
* Minimum for "maxlen" is 3!!!!
*
* "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into
* it. When typebuf.tb_change_cnt changes (e.g., when a message is received
* from a remote client) "buf" can no longer be used. "tb_change_cnt" is 0
* otherwise.
*
* If we got an interrupt all input is read until none is available.
*
* If wait_time == 0 there is no waiting for the char.
* If wait_time == n we wait for n msec for a character to arrive.
* If wait_time == -1 we wait forever for a character to arrive.
*
* Return the number of obtained characters.
* Return -1 when end of input script reached.
*/
static int
inchar(
char_u *buf,
int maxlen,
long wait_time) /* milli seconds */
{
int len = 0; /* init for GCC */
int retesc = FALSE; /* return ESC with gotint */
int script_char;
int tb_change_cnt = typebuf.tb_change_cnt;
if (wait_time == -1L || wait_time > 100L) /* flush output before waiting */
{
cursor_on();
out_flush_cursor(FALSE, FALSE);
#if defined(FEAT_GUI) && defined(FEAT_MOUSESHAPE)
if (gui.in_use && postponed_mouseshape)
update_mouseshape(-1);
#endif
}
/*
* Don't reset these when at the hit-return prompt, otherwise a endless
* recursive loop may result (write error in swapfile, hit-return, timeout
* on char wait, flush swapfile, write error....).
*/
if (State != HITRETURN)
{
did_outofmem_msg = FALSE; /* display out of memory message (again) */
did_swapwrite_msg = FALSE; /* display swap file write error again */
}
undo_off = FALSE; /* restart undo now */
/*
* Get a character from a script file if there is one.
* If interrupted: Stop reading script files, close them all.
*/
script_char = -1;
while (scriptin[curscript] != NULL && script_char < 0
#ifdef FEAT_EVAL
&& !ignore_script
#endif
)
{
#ifdef MESSAGE_QUEUE
parse_queued_messages();
#endif
if (got_int || (script_char = getc(scriptin[curscript])) < 0)
{
/* Reached EOF.
* Careful: closescript() frees typebuf.tb_buf[] and buf[] may
* point inside typebuf.tb_buf[]. Don't use buf[] after this! */
closescript();
/*
* When reading script file is interrupted, return an ESC to get
* back to normal mode.
* Otherwise return -1, because typebuf.tb_buf[] has changed.
*/
if (got_int)
retesc = TRUE;
else
return -1;
}
else
{
buf[0] = script_char;
len = 1;
}
}
if (script_char < 0) /* did not get a character from script */
{
/*
* If we got an interrupt, skip all previously typed characters and
* return TRUE if quit reading script file.
* Stop reading typeahead when a single CTRL-C was read,
* fill_input_buf() returns this when not able to read from stdin.
* Don't use buf[] here, closescript() may have freed typebuf.tb_buf[]
* and buf may be pointing inside typebuf.tb_buf[].
*/
if (got_int)
{
#define DUM_LEN MAXMAPLEN * 3 + 3
char_u dum[DUM_LEN + 1];
for (;;)
{
len = ui_inchar(dum, DUM_LEN, 0L, 0);
if (len == 0 || (len == 1 && dum[0] == 3))
break;
}
return retesc;
}
/*
* Always flush the output characters when getting input characters
* from the user and not just peeking.
*/
if (wait_time == -1L || wait_time > 10L)
out_flush();
/*
* Fill up to a third of the buffer, because each character may be
* tripled below.
*/
len = ui_inchar(buf, maxlen / 3, wait_time, tb_change_cnt);
}
/* If the typebuf was changed further down, it is like nothing was added by
* this call. */
if (typebuf_changed(tb_change_cnt))
return 0;
/* Note the change in the typeahead buffer, this matters for when
* vgetorpeek() is called recursively, e.g. using getchar(1) in a timer
* function. */
if (len > 0 && ++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
return fix_input_buffer(buf, len);
}
/*
* Fix typed characters for use by vgetc() and check_termcode().
* "buf[]" must have room to triple the number of bytes!
* Returns the new length.
*/
int
fix_input_buffer(char_u *buf, int len)
{
int i;
char_u *p = buf;
/*
* Two characters are special: NUL and K_SPECIAL.
* When compiled With the GUI CSI is also special.
* Replace NUL by K_SPECIAL KS_ZERO KE_FILLER
* Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
* Replace CSI by K_SPECIAL KS_EXTRA KE_CSI
*/
for (i = len; --i >= 0; ++p)
{
#ifdef FEAT_GUI
/* When the GUI is used any character can come after a CSI, don't
* escape it. */
if (gui.in_use && p[0] == CSI && i >= 2)
{
p += 2;
i -= 2;
}
# ifndef MSWIN
/* When the GUI is not used CSI needs to be escaped. */
else if (!gui.in_use && p[0] == CSI)
{
mch_memmove(p + 3, p + 1, (size_t)i);
*p++ = K_SPECIAL;
*p++ = KS_EXTRA;
*p = (int)KE_CSI;
len += 2;
}
# endif
else
#endif
if (p[0] == NUL || (p[0] == K_SPECIAL
// timeout may generate K_CURSORHOLD
&& (i < 2 || p[1] != KS_EXTRA || p[2] != (int)KE_CURSORHOLD)
#if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
// Win32 console passes modifiers
&& (
# ifdef VIMDLL
gui.in_use ||
# endif
(i < 2 || p[1] != KS_MODIFIER))
#endif
))
{
mch_memmove(p + 3, p + 1, (size_t)i);
p[2] = K_THIRD(p[0]);
p[1] = K_SECOND(p[0]);
p[0] = K_SPECIAL;
p += 2;
len += 2;
}
}
*p = NUL; // add trailing NUL
return len;
}
#if defined(USE_INPUT_BUF) || defined(PROTO)
/*
* Return TRUE when bytes are in the input buffer or in the typeahead buffer.
* Normally the input buffer would be sufficient, but the server_to_input_buf()
* or feedkeys() may insert characters in the typeahead buffer while we are
* waiting for input to arrive.
*/
int
input_available(void)
{
return (!vim_is_input_buf_empty()
# if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
|| typebuf_was_filled
# endif
);
}
#endif
/*
* map[!] : show all key mappings
* map[!] {lhs} : show key mapping for {lhs}
* map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
* noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
* unmap[!] {lhs} : remove key mapping for {lhs}
* abbr : show all abbreviations
* abbr {lhs} : show abbreviations for {lhs}
* abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
* noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
* unabbr {lhs} : remove abbreviation for {lhs}
*
* maptype: 0 for :map, 1 for :unmap, 2 for noremap.
*
* arg is pointer to any arguments. Note: arg cannot be a read-only string,
* it will be modified.
*
* for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
* for :map! mode is INSERT + CMDLINE
* for :cmap mode is CMDLINE
* for :imap mode is INSERT
* for :lmap mode is LANGMAP
* for :nmap mode is NORMAL
* for :vmap mode is VISUAL + SELECTMODE
* for :xmap mode is VISUAL
* for :smap mode is SELECTMODE
* for :omap mode is OP_PENDING
* for :tmap mode is TERMINAL
*
* for :abbr mode is INSERT + CMDLINE
* for :iabbr mode is INSERT
* for :cabbr mode is CMDLINE
*
* Return 0 for success
* 1 for invalid arguments
* 2 for no match
* 4 for out of mem
* 5 for entry not unique
*/
int
do_map(
int maptype,
char_u *arg,
int mode,
int abbrev) /* not a mapping but an abbreviation */
{
char_u *keys;
mapblock_T *mp, **mpp;
char_u *rhs;
char_u *p;
int n;
int len = 0; /* init for GCC */
char_u *newstr;
int hasarg;
int haskey;
int did_it = FALSE;
#ifdef FEAT_LOCALMAP
int did_local = FALSE;
#endif
int round;
char_u *keys_buf = NULL;
char_u *arg_buf = NULL;
int retval = 0;
int do_backslash;
int hash;
int new_hash;
mapblock_T **abbr_table;
mapblock_T **map_table;
int unique = FALSE;
int nowait = FALSE;
int silent = FALSE;
int special = FALSE;
#ifdef FEAT_EVAL
int expr = FALSE;
#endif
int noremap;
char_u *orig_rhs;
keys = arg;
map_table = maphash;
abbr_table = &first_abbr;
/* For ":noremap" don't remap, otherwise do remap. */
if (maptype == 2)
noremap = REMAP_NONE;
else
noremap = REMAP_YES;
/* Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
* any order. */
for (;;)
{
#ifdef FEAT_LOCALMAP
/*
* Check for "<buffer>": mapping local to buffer.
*/
if (STRNCMP(keys, "<buffer>", 8) == 0)
{
keys = skipwhite(keys + 8);
map_table = curbuf->b_maphash;
abbr_table = &curbuf->b_first_abbr;
continue;
}
#endif
/*
* Check for "<nowait>": don't wait for more characters.
*/
if (STRNCMP(keys, "<nowait>", 8) == 0)
{
keys = skipwhite(keys + 8);
nowait = TRUE;
continue;
}
/*
* Check for "<silent>": don't echo commands.
*/
if (STRNCMP(keys, "<silent>", 8) == 0)
{
keys = skipwhite(keys + 8);
silent = TRUE;
continue;
}
/*
* Check for "<special>": accept special keys in <>
*/
if (STRNCMP(keys, "<special>", 9) == 0)
{
keys = skipwhite(keys + 9);
special = TRUE;
continue;
}
#ifdef FEAT_EVAL
/*
* Check for "<script>": remap script-local mappings only
*/
if (STRNCMP(keys, "<script>", 8) == 0)
{
keys = skipwhite(keys + 8);
noremap = REMAP_SCRIPT;
continue;
}
/*
* Check for "<expr>": {rhs} is an expression.
*/
if (STRNCMP(keys, "<expr>", 6) == 0)
{
keys = skipwhite(keys + 6);
expr = TRUE;
continue;
}
#endif
/*
* Check for "<unique>": don't overwrite an existing mapping.
*/
if (STRNCMP(keys, "<unique>", 8) == 0)
{
keys = skipwhite(keys + 8);
unique = TRUE;
continue;
}
break;
}
validate_maphash();
/*
* Find end of keys and skip CTRL-Vs (and backslashes) in it.
* Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
* with :unmap white space is included in the keys, no argument possible.
*/
p = keys;
do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
while (*p && (maptype == 1 || !VIM_ISWHITE(*p)))
{
if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
p[1] != NUL)
++p; /* skip CTRL-V or backslash */
++p;
}
if (*p != NUL)
*p++ = NUL;
p = skipwhite(p);
rhs = p;
hasarg = (*rhs != NUL);
haskey = (*keys != NUL);
/* check for :unmap without argument */
if (maptype == 1 && !haskey)
{
retval = 1;
goto theend;
}
/*
* If mapping has been given as ^V<C_UP> say, then replace the term codes
* with the appropriate two bytes. If it is a shifted special key, unshift
* it too, giving another two bytes.
* replace_termcodes() may move the result to allocated memory, which
* needs to be freed later (*keys_buf and *arg_buf).
* replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
*/
if (haskey)
keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, special);
orig_rhs = rhs;
if (hasarg)
{
if (STRICMP(rhs, "<nop>") == 0) /* "<Nop>" means nothing */
rhs = (char_u *)"";
else
rhs = replace_termcodes(rhs, &arg_buf, FALSE, TRUE, special);
}
/*
* check arguments and translate function keys
*/
if (haskey)
{
len = (int)STRLEN(keys);
if (len > MAXMAPLEN) /* maximum length of MAXMAPLEN chars */
{
retval = 1;
goto theend;
}
if (abbrev && maptype != 1)
{
/*
* If an abbreviation ends in a keyword character, the
* rest must be all keyword-char or all non-keyword-char.
* Otherwise we won't be able to find the start of it in a
* vi-compatible way.
*/
if (has_mbyte)
{
int first, last;
int same = -1;
first = vim_iswordp(keys);
last = first;
p = keys + (*mb_ptr2len)(keys);
n = 1;
while (p < keys + len)
{
++n; /* nr of (multi-byte) chars */
last = vim_iswordp(p); /* type of last char */
if (same == -1 && last != first)
same = n - 1; /* count of same char type */
p += (*mb_ptr2len)(p);
}
if (last && n > 2 && same >= 0 && same < n - 1)
{
retval = 1;
goto theend;
}
}
else if (vim_iswordc(keys[len - 1])) // ends in keyword char
for (n = 0; n < len - 2; ++n)
if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
{
retval = 1;
goto theend;
}
/* An abbreviation cannot contain white space. */
for (n = 0; n < len; ++n)
if (VIM_ISWHITE(keys[n]))
{
retval = 1;
goto theend;
}
}
}
if (haskey && hasarg && abbrev) /* if we will add an abbreviation */
no_abbr = FALSE; /* reset flag that indicates there are
no abbreviations */
if (!haskey || (maptype != 1 && !hasarg))
msg_start();
#ifdef FEAT_LOCALMAP
/*
* Check if a new local mapping wasn't already defined globally.
*/
if (map_table == curbuf->b_maphash && haskey && hasarg && maptype != 1)
{
/* need to loop over all global hash lists */
for (hash = 0; hash < 256 && !got_int; ++hash)
{
if (abbrev)
{
if (hash != 0) /* there is only one abbreviation list */
break;
mp = first_abbr;
}
else
mp = maphash[hash];
for ( ; mp != NULL && !got_int; mp = mp->m_next)
{
/* check entries with the same mode */
if ((mp->m_mode & mode) != 0
&& mp->m_keylen == len
&& unique
&& STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
{
if (abbrev)
semsg(_("E224: global abbreviation already exists for %s"),
mp->m_keys);
else
semsg(_("E225: global mapping already exists for %s"),
mp->m_keys);
retval = 5;
goto theend;
}
}
}
}
/*
* When listing global mappings, also list buffer-local ones here.
*/
if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
{
/* need to loop over all global hash lists */
for (hash = 0; hash < 256 && !got_int; ++hash)
{
if (abbrev)
{
if (hash != 0) /* there is only one abbreviation list */
break;
mp = curbuf->b_first_abbr;
}
else
mp = curbuf->b_maphash[hash];
for ( ; mp != NULL && !got_int; mp = mp->m_next)
{
/* check entries with the same mode */
if ((mp->m_mode & mode) != 0)
{
if (!haskey) /* show all entries */
{
showmap(mp, TRUE);
did_local = TRUE;
}
else
{
n = mp->m_keylen;
if (STRNCMP(mp->m_keys, keys,
(size_t)(n < len ? n : len)) == 0)
{
showmap(mp, TRUE);
did_local = TRUE;
}
}
}
}
}
}
#endif
/*
* Find an entry in the maphash[] list that matches.
* For :unmap we may loop two times: once to try to unmap an entry with a
* matching 'from' part, a second time, if the first fails, to unmap an
* entry with a matching 'to' part. This was done to allow ":ab foo bar"
* to be unmapped by typing ":unab foo", where "foo" will be replaced by
* "bar" because of the abbreviation.
*/
for (round = 0; (round == 0 || maptype == 1) && round <= 1
&& !did_it && !got_int; ++round)
{
/* need to loop over all hash lists */
for (hash = 0; hash < 256 && !got_int; ++hash)
{
if (abbrev)
{
if (hash > 0) /* there is only one abbreviation list */
break;
mpp = abbr_table;
}
else
mpp = &(map_table[hash]);
for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
{
if (!(mp->m_mode & mode)) /* skip entries with wrong mode */
{
mpp = &(mp->m_next);
continue;
}
if (!haskey) /* show all entries */
{
showmap(mp, map_table != maphash);
did_it = TRUE;
}
else /* do we have a match? */
{
if (round) /* second round: Try unmap "rhs" string */
{
n = (int)STRLEN(mp->m_str);
p = mp->m_str;
}
else
{
n = mp->m_keylen;
p = mp->m_keys;
}
if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
{
if (maptype == 1) /* delete entry */
{
/* Only accept a full match. For abbreviations we
* ignore trailing space when matching with the
* "lhs", since an abbreviation can't have
* trailing space. */
if (n != len && (!abbrev || round || n > len
|| *skipwhite(keys + n) != NUL))
{
mpp = &(mp->m_next);
continue;
}
/*
* We reset the indicated mode bits. If nothing is
* left the entry is deleted below.
*/
mp->m_mode &= ~mode;
did_it = TRUE; /* remember we did something */
}
else if (!hasarg) /* show matching entry */
{
showmap(mp, map_table != maphash);
did_it = TRUE;
}
else if (n != len) /* new entry is ambiguous */
{
mpp = &(mp->m_next);
continue;
}
else if (unique)
{
if (abbrev)
semsg(_("E226: abbreviation already exists for %s"),
p);
else
semsg(_("E227: mapping already exists for %s"), p);
retval = 5;
goto theend;
}
else /* new rhs for existing entry */
{
mp->m_mode &= ~mode; /* remove mode bits */
if (mp->m_mode == 0 && !did_it) /* reuse entry */
{
newstr = vim_strsave(rhs);
if (newstr == NULL)
{
retval = 4; /* no mem */
goto theend;
}
vim_free(mp->m_str);
mp->m_str = newstr;
vim_free(mp->m_orig_str);
mp->m_orig_str = vim_strsave(orig_rhs);
mp->m_noremap = noremap;
mp->m_nowait = nowait;
mp->m_silent = silent;
mp->m_mode = mode;
#ifdef FEAT_EVAL
mp->m_expr = expr;
mp->m_script_ctx = current_sctx;
mp->m_script_ctx.sc_lnum += sourcing_lnum;
#endif
did_it = TRUE;
}
}
if (mp->m_mode == 0) /* entry can be deleted */
{
map_free(mpp);
continue; /* continue with *mpp */
}
/*
* May need to put this entry into another hash list.
*/
new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
if (!abbrev && new_hash != hash)
{
*mpp = mp->m_next;
mp->m_next = map_table[new_hash];
map_table[new_hash] = mp;
continue; /* continue with *mpp */
}
}
}
mpp = &(mp->m_next);
}
}
}
if (maptype == 1) /* delete entry */
{
if (!did_it)
retval = 2; /* no match */
else if (*keys == Ctrl_C)
{
/* If CTRL-C has been unmapped, reuse it for Interrupting. */
#ifdef FEAT_LOCALMAP
if (map_table == curbuf->b_maphash)
curbuf->b_mapped_ctrl_c &= ~mode;
else
#endif
mapped_ctrl_c &= ~mode;
}
goto theend;
}
if (!haskey || !hasarg) /* print entries */
{
if (!did_it
#ifdef FEAT_LOCALMAP
&& !did_local
#endif
)
{
if (abbrev)
msg(_("No abbreviation found"));
else
msg(_("No mapping found"));
}
goto theend; /* listing finished */
}
if (did_it) /* have added the new entry already */
goto theend;
/*
* Get here when adding a new entry to the maphash[] list or abbrlist.
*/
mp = (mapblock_T *)alloc((unsigned)sizeof(mapblock_T));
if (mp == NULL)
{
retval = 4; /* no mem */
goto theend;
}
/* If CTRL-C has been mapped, don't always use it for Interrupting. */
if (*keys == Ctrl_C)
{
#ifdef FEAT_LOCALMAP
if (map_table == curbuf->b_maphash)
curbuf->b_mapped_ctrl_c |= mode;
else
#endif
mapped_ctrl_c |= mode;
}
mp->m_keys = vim_strsave(keys);
mp->m_str = vim_strsave(rhs);
mp->m_orig_str = vim_strsave(orig_rhs);
if (mp->m_keys == NULL || mp->m_str == NULL)
{
vim_free(mp->m_keys);
vim_free(mp->m_str);
vim_free(mp->m_orig_str);
vim_free(mp);
retval = 4; /* no mem */
goto theend;
}
mp->m_keylen = (int)STRLEN(mp->m_keys);
mp->m_noremap = noremap;
mp->m_nowait = nowait;
mp->m_silent = silent;
mp->m_mode = mode;
#ifdef FEAT_EVAL
mp->m_expr = expr;
mp->m_script_ctx = current_sctx;
mp->m_script_ctx.sc_lnum += sourcing_lnum;
#endif
/* add the new entry in front of the abbrlist or maphash[] list */
if (abbrev)
{
mp->m_next = *abbr_table;
*abbr_table = mp;
}
else
{
n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
mp->m_next = map_table[n];
map_table[n] = mp;
}
theend:
vim_free(keys_buf);
vim_free(arg_buf);
return retval;
}
/*
* Delete one entry from the abbrlist or maphash[].
* "mpp" is a pointer to the m_next field of the PREVIOUS entry!
*/
static void
map_free(mapblock_T **mpp)
{
mapblock_T *mp;
mp = *mpp;
vim_free(mp->m_keys);
vim_free(mp->m_str);
vim_free(mp->m_orig_str);
*mpp = mp->m_next;
vim_free(mp);
}
/*
* Initialize maphash[] for first use.
*/
static void
validate_maphash(void)
{
if (!maphash_valid)
{
vim_memset(maphash, 0, sizeof(maphash));
maphash_valid = TRUE;
}
}
/*
* Get the mapping mode from the command name.
*/
int
get_map_mode(char_u **cmdp, int forceit)
{
char_u *p;
int modec;
int mode;
p = *cmdp;
modec = *p++;
if (modec == 'i')
mode = INSERT; /* :imap */
else if (modec == 'l')
mode = LANGMAP; /* :lmap */
else if (modec == 'c')
mode = CMDLINE; /* :cmap */
else if (modec == 'n' && *p != 'o') /* avoid :noremap */
mode = NORMAL; /* :nmap */
else if (modec == 'v')
mode = VISUAL + SELECTMODE; /* :vmap */
else if (modec == 'x')
mode = VISUAL; /* :xmap */
else if (modec == 's')
mode = SELECTMODE; /* :smap */
else if (modec == 'o')
mode = OP_PENDING; /* :omap */
else if (modec == 't')
mode = TERMINAL; /* :tmap */
else
{
--p;
if (forceit)
mode = INSERT + CMDLINE; /* :map ! */
else
mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;/* :map */
}
*cmdp = p;
return mode;
}
/*
* Clear all mappings or abbreviations.
* 'abbr' should be FALSE for mappings, TRUE for abbreviations.
*/
void
map_clear(
char_u *cmdp,
char_u *arg UNUSED,
int forceit,
int abbr)
{
int mode;
#ifdef FEAT_LOCALMAP
int local;
local = (STRCMP(arg, "<buffer>") == 0);
if (!local && *arg != NUL)
{
emsg(_(e_invarg));
return;
}
#endif
mode = get_map_mode(&cmdp, forceit);
map_clear_int(curbuf, mode,
#ifdef FEAT_LOCALMAP
local,
#else
FALSE,
#endif
abbr);
}
/*
* Clear all mappings in "mode".
*/
void
map_clear_int(
buf_T *buf UNUSED, /* buffer for local mappings */
int mode, /* mode in which to delete */
int local UNUSED, /* TRUE for buffer-local mappings */
int abbr) /* TRUE for abbreviations */
{
mapblock_T *mp, **mpp;
int hash;
int new_hash;
validate_maphash();
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one abbrlist */
break;
#ifdef FEAT_LOCALMAP
if (local)
mpp = &buf->b_first_abbr;
else
#endif
mpp = &first_abbr;
}
else
{
#ifdef FEAT_LOCALMAP
if (local)
mpp = &buf->b_maphash[hash];
else
#endif
mpp = &maphash[hash];
}
while (*mpp != NULL)
{
mp = *mpp;
if (mp->m_mode & mode)
{
mp->m_mode &= ~mode;
if (mp->m_mode == 0) /* entry can be deleted */
{
map_free(mpp);
continue;
}
/*
* May need to put this entry into another hash list.
*/
new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
if (!abbr && new_hash != hash)
{
*mpp = mp->m_next;
#ifdef FEAT_LOCALMAP
if (local)
{
mp->m_next = buf->b_maphash[new_hash];
buf->b_maphash[new_hash] = mp;
}
else
#endif
{
mp->m_next = maphash[new_hash];
maphash[new_hash] = mp;
}
continue; /* continue with *mpp */
}
}
mpp = &(mp->m_next);
}
}
}
/*
* Return characters to represent the map mode in an allocated string.
* Returns NULL when out of memory.
*/
char_u *
map_mode_to_chars(int mode)
{
garray_T mapmode;
ga_init2(&mapmode, 1, 7);
if ((mode & (INSERT + CMDLINE)) == INSERT + CMDLINE)
ga_append(&mapmode, '!'); /* :map! */
else if (mode & INSERT)
ga_append(&mapmode, 'i'); /* :imap */
else if (mode & LANGMAP)
ga_append(&mapmode, 'l'); /* :lmap */
else if (mode & CMDLINE)
ga_append(&mapmode, 'c'); /* :cmap */
else if ((mode & (NORMAL + VISUAL + SELECTMODE + OP_PENDING))
== NORMAL + VISUAL + SELECTMODE + OP_PENDING)
ga_append(&mapmode, ' '); /* :map */
else
{
if (mode & NORMAL)
ga_append(&mapmode, 'n'); /* :nmap */
if (mode & OP_PENDING)
ga_append(&mapmode, 'o'); /* :omap */
if ((mode & (VISUAL + SELECTMODE)) == VISUAL + SELECTMODE)
ga_append(&mapmode, 'v'); /* :vmap */
else
{
if (mode & VISUAL)
ga_append(&mapmode, 'x'); /* :xmap */
if (mode & SELECTMODE)
ga_append(&mapmode, 's'); /* :smap */
}
}
ga_append(&mapmode, NUL);
return (char_u *)mapmode.ga_data;
}
static void
showmap(
mapblock_T *mp,
int local) /* TRUE for buffer-local map */
{
int len = 1;
char_u *mapchars;
if (message_filtered(mp->m_keys) && message_filtered(mp->m_str))
return;
if (msg_didout || msg_silent != 0)
{
msg_putchar('\n');
if (got_int) /* 'q' typed at MORE prompt */
return;
}
mapchars = map_mode_to_chars(mp->m_mode);
if (mapchars != NULL)
{
msg_puts((char *)mapchars);
len = (int)STRLEN(mapchars);
vim_free(mapchars);
}
while (++len <= 3)
msg_putchar(' ');
/* Display the LHS. Get length of what we write. */
len = msg_outtrans_special(mp->m_keys, TRUE, 0);
do
{
msg_putchar(' '); /* padd with blanks */
++len;
} while (len < 12);
if (mp->m_noremap == REMAP_NONE)
msg_puts_attr("*", HL_ATTR(HLF_8));
else if (mp->m_noremap == REMAP_SCRIPT)
msg_puts_attr("&", HL_ATTR(HLF_8));
else
msg_putchar(' ');
if (local)
msg_putchar('@');
else
msg_putchar(' ');
/* Use FALSE below if we only want things like <Up> to show up as such on
* the rhs, and not M-x etc, TRUE gets both -- webb */
if (*mp->m_str == NUL)
msg_puts_attr("<Nop>", HL_ATTR(HLF_8));
else
{
/* Remove escaping of CSI, because "m_str" is in a format to be used
* as typeahead. */
char_u *s = vim_strsave(mp->m_str);
if (s != NULL)
{
vim_unescape_csi(s);
msg_outtrans_special(s, FALSE, 0);
vim_free(s);
}
}
#ifdef FEAT_EVAL
if (p_verbose > 0)
last_set_msg(mp->m_script_ctx);
#endif
out_flush(); /* show one line at a time */
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
* Recognize termcap codes in "str".
* Also checks mappings local to the current buffer.
*/
int
map_to_exists(char_u *str, char_u *modechars, int abbr)
{
int mode = 0;
char_u *rhs;
char_u *buf;
int retval;
rhs = replace_termcodes(str, &buf, FALSE, TRUE, FALSE);
if (vim_strchr(modechars, 'n') != NULL)
mode |= NORMAL;
if (vim_strchr(modechars, 'v') != NULL)
mode |= VISUAL + SELECTMODE;
if (vim_strchr(modechars, 'x') != NULL)
mode |= VISUAL;
if (vim_strchr(modechars, 's') != NULL)
mode |= SELECTMODE;
if (vim_strchr(modechars, 'o') != NULL)
mode |= OP_PENDING;
if (vim_strchr(modechars, 'i') != NULL)
mode |= INSERT;
if (vim_strchr(modechars, 'l') != NULL)
mode |= LANGMAP;
if (vim_strchr(modechars, 'c') != NULL)
mode |= CMDLINE;
retval = map_to_exists_mode(rhs, mode, abbr);
vim_free(buf);
return retval;
}
#endif
/*
* Return TRUE if a map exists that has "str" in the rhs for mode "mode".
* Also checks mappings local to the current buffer.
*/
int
map_to_exists_mode(char_u *rhs, int mode, int abbr)
{
mapblock_T *mp;
int hash;
# ifdef FEAT_LOCALMAP
int exp_buffer = FALSE;
validate_maphash();
/* Do it twice: once for global maps and once for local maps. */
for (;;)
{
# endif
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one abbr list */
break;
#ifdef FEAT_LOCALMAP
if (exp_buffer)
mp = curbuf->b_first_abbr;
else
#endif
mp = first_abbr;
}
# ifdef FEAT_LOCALMAP
else if (exp_buffer)
mp = curbuf->b_maphash[hash];
# endif
else
mp = maphash[hash];
for (; mp; mp = mp->m_next)
{
if ((mp->m_mode & mode)
&& strstr((char *)mp->m_str, (char *)rhs) != NULL)
return TRUE;
}
}
# ifdef FEAT_LOCALMAP
if (exp_buffer)
break;
exp_buffer = TRUE;
}
# endif
return FALSE;
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Used below when expanding mapping/abbreviation names.
*/
static int expand_mapmodes = 0;
static int expand_isabbrev = 0;
#ifdef FEAT_LOCALMAP
static int expand_buffer = FALSE;
#endif
/*
* Work out what to complete when doing command line completion of mapping
* or abbreviation names.
*/
char_u *
set_context_in_map_cmd(
expand_T *xp,
char_u *cmd,
char_u *arg,
int forceit, /* TRUE if '!' given */
int isabbrev, /* TRUE if abbreviation */
int isunmap, /* TRUE if unmap/unabbrev command */
cmdidx_T cmdidx)
{
if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
xp->xp_context = EXPAND_NOTHING;
else
{
if (isunmap)
expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
else
{
expand_mapmodes = INSERT + CMDLINE;
if (!isabbrev)
expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
}
expand_isabbrev = isabbrev;
xp->xp_context = EXPAND_MAPPINGS;
#ifdef FEAT_LOCALMAP
expand_buffer = FALSE;
#endif
for (;;)
{
#ifdef FEAT_LOCALMAP
if (STRNCMP(arg, "<buffer>", 8) == 0)
{
expand_buffer = TRUE;
arg = skipwhite(arg + 8);
continue;
}
#endif
if (STRNCMP(arg, "<unique>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<nowait>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<silent>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<special>", 9) == 0)
{
arg = skipwhite(arg + 9);
continue;
}
#ifdef FEAT_EVAL
if (STRNCMP(arg, "<script>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<expr>", 6) == 0)
{
arg = skipwhite(arg + 6);
continue;
}
#endif
break;
}
xp->xp_pattern = arg;
}
return NULL;
}
/*
* Find all mapping/abbreviation names that match regexp "regmatch"'.
* For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
* Return OK if matches found, FAIL otherwise.
*/
int
ExpandMappings(
regmatch_T *regmatch,
int *num_file,
char_u ***file)
{
mapblock_T *mp;
int hash;
int count;
int round;
char_u *p;
int i;
validate_maphash();
*num_file = 0; /* return values in case of FAIL */
*file = NULL;
/*
* round == 1: Count the matches.
* round == 2: Build the array to keep the matches.
*/
for (round = 1; round <= 2; ++round)
{
count = 0;
for (i = 0; i < 7; ++i)
{
if (i == 0)
p = (char_u *)"<silent>";
else if (i == 1)
p = (char_u *)"<unique>";
#ifdef FEAT_EVAL
else if (i == 2)
p = (char_u *)"<script>";
else if (i == 3)
p = (char_u *)"<expr>";
#endif
#ifdef FEAT_LOCALMAP
else if (i == 4 && !expand_buffer)
p = (char_u *)"<buffer>";
#endif
else if (i == 5)
p = (char_u *)"<nowait>";
else if (i == 6)
p = (char_u *)"<special>";
else
continue;
if (vim_regexec(regmatch, p, (colnr_T)0))
{
if (round == 1)
++count;
else
(*file)[count++] = vim_strsave(p);
}
}
for (hash = 0; hash < 256; ++hash)
{
if (expand_isabbrev)
{
if (hash > 0) /* only one abbrev list */
break; /* for (hash) */
mp = first_abbr;
}
#ifdef FEAT_LOCALMAP
else if (expand_buffer)
mp = curbuf->b_maphash[hash];
#endif
else
mp = maphash[hash];
for (; mp; mp = mp->m_next)
{
if (mp->m_mode & expand_mapmodes)
{
p = translate_mapping(mp->m_keys);
if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
{
if (round == 1)
++count;
else
{
(*file)[count++] = p;
p = NULL;
}
}
vim_free(p);
}
} /* for (mp) */
} /* for (hash) */
if (count == 0) /* no match found */
break; /* for (round) */
if (round == 1)
{
*file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
if (*file == NULL)
return FAIL;
}
} /* for (round) */
if (count > 1)
{
char_u **ptr1;
char_u **ptr2;
char_u **ptr3;
/* Sort the matches */
sort_strings(*file, count);
/* Remove multiple entries */
ptr1 = *file;
ptr2 = ptr1 + 1;
ptr3 = ptr1 + count;
while (ptr2 < ptr3)
{
if (STRCMP(*ptr1, *ptr2))
*++ptr1 = *ptr2++;
else
{
vim_free(*ptr2++);
count--;
}
}
}
*num_file = count;
return (count == 0 ? FAIL : OK);
}
#endif /* FEAT_CMDL_COMPL */
/*
* Check for an abbreviation.
* Cursor is at ptr[col].
* When inserting, mincol is where insert started.
* For the command line, mincol is what is to be skipped over.
* "c" is the character typed before check_abbr was called. It may have
* ABBR_OFF added to avoid prepending a CTRL-V to it.
*
* Historic vi practice: The last character of an abbreviation must be an id
* character ([a-zA-Z0-9_]). The characters in front of it must be all id
* characters or all non-id characters. This allows for abbr. "#i" to
* "#include".
*
* Vim addition: Allow for abbreviations that end in a non-keyword character.
* Then there must be white space before the abbr.
*
* return TRUE if there is an abbreviation, FALSE if not
*/
int
check_abbr(
int c,
char_u *ptr,
int col,
int mincol)
{
int len;
int scol; /* starting column of the abbr. */
int j;
char_u *s;
char_u tb[MB_MAXBYTES + 4];
mapblock_T *mp;
#ifdef FEAT_LOCALMAP
mapblock_T *mp2;
#endif
int clen = 0; /* length in characters */
int is_id = TRUE;
int vim_abbr;
if (typebuf.tb_no_abbr_cnt) /* abbrev. are not recursive */
return FALSE;
/* no remapping implies no abbreviation, except for CTRL-] */
if ((KeyNoremap & (RM_NONE|RM_SCRIPT)) != 0 && c != Ctrl_RSB)
return FALSE;
/*
* Check for word before the cursor: If it ends in a keyword char all
* chars before it must be keyword chars or non-keyword chars, but not
* white space. If it ends in a non-keyword char we accept any characters
* before it except white space.
*/
if (col == 0) /* cannot be an abbr. */
return FALSE;
if (has_mbyte)
{
char_u *p;
p = mb_prevptr(ptr, ptr + col);
if (!vim_iswordp(p))
vim_abbr = TRUE; /* Vim added abbr. */
else
{
vim_abbr = FALSE; /* vi compatible abbr. */
if (p > ptr)
is_id = vim_iswordp(mb_prevptr(ptr, p));
}
clen = 1;
while (p > ptr + mincol)
{
p = mb_prevptr(ptr, p);
if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
{
p += (*mb_ptr2len)(p);
break;
}
++clen;
}
scol = (int)(p - ptr);
}
else
{
if (!vim_iswordc(ptr[col - 1]))
vim_abbr = TRUE; /* Vim added abbr. */
else
{
vim_abbr = FALSE; /* vi compatible abbr. */
if (col > 1)
is_id = vim_iswordc(ptr[col - 2]);
}
for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
&& (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
;
}
if (scol < mincol)
scol = mincol;
if (scol < col) /* there is a word in front of the cursor */
{
ptr += scol;
len = col - scol;
#ifdef FEAT_LOCALMAP
mp = curbuf->b_first_abbr;
mp2 = first_abbr;
if (mp == NULL)
{
mp = mp2;
mp2 = NULL;
}
#else
mp = first_abbr;
#endif
for ( ; mp;
#ifdef FEAT_LOCALMAP
mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
#endif
(mp = mp->m_next))
{
int qlen = mp->m_keylen;
char_u *q = mp->m_keys;
int match;
if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
{
char_u *qe = vim_strsave(mp->m_keys);
/* might have CSI escaped mp->m_keys */
if (qe != NULL)
{
q = qe;
vim_unescape_csi(q);
qlen = (int)STRLEN(q);
}
}
/* find entries with right mode and keys */
match = (mp->m_mode & State)
&& qlen == len
&& !STRNCMP(q, ptr, (size_t)len);
if (q != mp->m_keys)
vim_free(q);
if (match)
break;
}
if (mp != NULL)
{
/*
* Found a match:
* Insert the rest of the abbreviation in typebuf.tb_buf[].
* This goes from end to start.
*
* Characters 0x000 - 0x100: normal chars, may need CTRL-V,
* except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
* Characters where IS_SPECIAL() == TRUE: key codes, need
* K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
*
* Character CTRL-] is treated specially - it completes the
* abbreviation, but is not inserted into the input stream.
*/
j = 0;
if (c != Ctrl_RSB)
{
/* special key code, split up */
if (IS_SPECIAL(c) || c == K_SPECIAL)
{
tb[j++] = K_SPECIAL;
tb[j++] = K_SECOND(c);
tb[j++] = K_THIRD(c);
}
else
{
if (c < ABBR_OFF && (c < ' ' || c > '~'))
tb[j++] = Ctrl_V; /* special char needs CTRL-V */
if (has_mbyte)
{
/* if ABBR_OFF has been added, remove it here */
if (c >= ABBR_OFF)
c -= ABBR_OFF;
j += (*mb_char2bytes)(c, tb + j);
}
else
tb[j++] = c;
}
tb[j] = NUL;
/* insert the last typed char */
(void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
}
#ifdef FEAT_EVAL
if (mp->m_expr)
s = eval_map_expr(mp->m_str, c);
else
#endif
s = mp->m_str;
if (s != NULL)
{
/* insert the to string */
(void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent);
/* no abbrev. for these chars */
typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
#ifdef FEAT_EVAL
if (mp->m_expr)
vim_free(s);
#endif
}
tb[0] = Ctrl_H;
tb[1] = NUL;
if (has_mbyte)
len = clen; /* Delete characters instead of bytes */
while (len-- > 0) /* delete the from string */
(void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
return TRUE;
}
}
return FALSE;
}
#ifdef FEAT_EVAL
/*
* Evaluate the RHS of a mapping or abbreviations and take care of escaping
* special characters.
*/
static char_u *
eval_map_expr(
char_u *str,
int c) /* NUL or typed character for abbreviation */
{
char_u *res;
char_u *p;
char_u *expr;
pos_T save_cursor;
int save_msg_col;
int save_msg_row;
/* Remove escaping of CSI, because "str" is in a format to be used as
* typeahead. */
expr = vim_strsave(str);
if (expr == NULL)
return NULL;
vim_unescape_csi(expr);
/* Forbid changing text or using ":normal" to avoid most of the bad side
* effects. Also restore the cursor position. */
++textlock;
++ex_normal_lock;
set_vim_var_char(c); /* set v:char to the typed character */
save_cursor = curwin->w_cursor;
save_msg_col = msg_col;
save_msg_row = msg_row;
p = eval_to_string(expr, NULL, FALSE);
--textlock;
--ex_normal_lock;
curwin->w_cursor = save_cursor;
msg_col = save_msg_col;
msg_row = save_msg_row;
vim_free(expr);
if (p == NULL)
return NULL;
/* Escape CSI in the result to be able to use the string as typeahead. */
res = vim_strsave_escape_csi(p);
vim_free(p);
return res;
}
#endif
/*
* Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
* can be put in the typeahead buffer.
* Returns NULL when out of memory.
*/
char_u *
vim_strsave_escape_csi(
char_u *p)
{
char_u *res;
char_u *s, *d;
/* Need a buffer to hold up to three times as much. Four in case of an
* illegal utf-8 byte:
* 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER */
res = alloc((unsigned)(STRLEN(p) * 4) + 1);
if (res != NULL)
{
d = res;
for (s = p; *s != NUL; )
{
if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
{
/* Copy special key unmodified. */
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
}
else
{
/* Add character, possibly multi-byte to destination, escaping
* CSI and K_SPECIAL. Be careful, it can be an illegal byte! */
d = add_char2buf(PTR2CHAR(s), d);
s += MB_CPTR2LEN(s);
}
}
*d = NUL;
}
return res;
}
/*
* Remove escaping from CSI and K_SPECIAL characters. Reverse of
* vim_strsave_escape_csi(). Works in-place.
*/
void
vim_unescape_csi(char_u *p)
{
char_u *s = p, *d = p;
while (*s != NUL)
{
if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
{
*d++ = K_SPECIAL;
s += 3;
}
else if ((s[0] == K_SPECIAL || s[0] == CSI)
&& s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
{
*d++ = CSI;
s += 3;
}
else
*d++ = *s++;
}
*d = NUL;
}
/*
* Write map commands for the current mappings to an .exrc file.
* Return FAIL on error, OK otherwise.
*/
int
makemap(
FILE *fd,
buf_T *buf) /* buffer for local mappings or NULL */
{
mapblock_T *mp;
char_u c1, c2, c3;
char_u *p;
char *cmd;
int abbr;
int hash;
int did_cpo = FALSE;
int i;
validate_maphash();
/*
* Do the loop twice: Once for mappings, once for abbreviations.
* Then loop over all map hash lists.
*/
for (abbr = 0; abbr < 2; ++abbr)
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one abbr list */
break;
#ifdef FEAT_LOCALMAP
if (buf != NULL)
mp = buf->b_first_abbr;
else
#endif
mp = first_abbr;
}
else
{
#ifdef FEAT_LOCALMAP
if (buf != NULL)
mp = buf->b_maphash[hash];
else
#endif
mp = maphash[hash];
}
for ( ; mp; mp = mp->m_next)
{
/* skip script-local mappings */
if (mp->m_noremap == REMAP_SCRIPT)
continue;
/* skip mappings that contain a <SNR> (script-local thing),
* they probably don't work when loaded again */
for (p = mp->m_str; *p != NUL; ++p)
if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
&& p[2] == (int)KE_SNR)
break;
if (*p != NUL)
continue;
/* It's possible to create a mapping and then ":unmap" certain
* modes. We recreate this here by mapping the individual
* modes, which requires up to three of them. */
c1 = NUL;
c2 = NUL;
c3 = NUL;
if (abbr)
cmd = "abbr";
else
cmd = "map";
switch (mp->m_mode)
{
case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
break;
case NORMAL:
c1 = 'n';
break;
case VISUAL:
c1 = 'x';
break;
case SELECTMODE:
c1 = 's';
break;
case OP_PENDING:
c1 = 'o';
break;
case NORMAL + VISUAL:
c1 = 'n';
c2 = 'x';
break;
case NORMAL + SELECTMODE:
c1 = 'n';
c2 = 's';
break;
case NORMAL + OP_PENDING:
c1 = 'n';
c2 = 'o';
break;
case VISUAL + SELECTMODE:
c1 = 'v';
break;
case VISUAL + OP_PENDING:
c1 = 'x';
c2 = 'o';
break;
case SELECTMODE + OP_PENDING:
c1 = 's';
c2 = 'o';
break;
case NORMAL + VISUAL + SELECTMODE:
c1 = 'n';
c2 = 'v';
break;
case NORMAL + VISUAL + OP_PENDING:
c1 = 'n';
c2 = 'x';
c3 = 'o';
break;
case NORMAL + SELECTMODE + OP_PENDING:
c1 = 'n';
c2 = 's';
c3 = 'o';
break;
case VISUAL + SELECTMODE + OP_PENDING:
c1 = 'v';
c2 = 'o';
break;
case CMDLINE + INSERT:
if (!abbr)
cmd = "map!";
break;
case CMDLINE:
c1 = 'c';
break;
case INSERT:
c1 = 'i';
break;
case LANGMAP:
c1 = 'l';
break;
case TERMINAL:
c1 = 't';
break;
default:
iemsg(_("E228: makemap: Illegal mode"));
return FAIL;
}
do /* do this twice if c2 is set, 3 times with c3 */
{
/* When outputting <> form, need to make sure that 'cpo'
* is set to the Vim default. */
if (!did_cpo)
{
if (*mp->m_str == NUL) /* will use <Nop> */
did_cpo = TRUE;
else
for (i = 0; i < 2; ++i)
for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
if (*p == K_SPECIAL || *p == NL)
did_cpo = TRUE;
if (did_cpo)
{
if (fprintf(fd, "let s:cpo_save=&cpo") < 0
|| put_eol(fd) < 0
|| fprintf(fd, "set cpo&vim") < 0
|| put_eol(fd) < 0)
return FAIL;
}
}
if (c1 && putc(c1, fd) < 0)
return FAIL;
if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
return FAIL;
if (fputs(cmd, fd) < 0)
return FAIL;
if (buf != NULL && fputs(" <buffer>", fd) < 0)
return FAIL;
if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
return FAIL;
if (mp->m_silent && fputs(" <silent>", fd) < 0)
return FAIL;
#ifdef FEAT_EVAL
if (mp->m_noremap == REMAP_SCRIPT
&& fputs("<script>", fd) < 0)
return FAIL;
if (mp->m_expr && fputs(" <expr>", fd) < 0)
return FAIL;
#endif
if ( putc(' ', fd) < 0
|| put_escstr(fd, mp->m_keys, 0) == FAIL
|| putc(' ', fd) < 0
|| put_escstr(fd, mp->m_str, 1) == FAIL
|| put_eol(fd) < 0)
return FAIL;
c1 = c2;
c2 = c3;
c3 = NUL;
} while (c1 != NUL);
}
}
if (did_cpo)
if (fprintf(fd, "let &cpo=s:cpo_save") < 0
|| put_eol(fd) < 0
|| fprintf(fd, "unlet s:cpo_save") < 0
|| put_eol(fd) < 0)
return FAIL;
return OK;
}
/*
* write escape string to file
* "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
*
* return FAIL for failure, OK otherwise
*/
int
put_escstr(FILE *fd, char_u *strstart, int what)
{
char_u *str = strstart;
int c;
int modifiers;
/* :map xx <Nop> */
if (*str == NUL && what == 1)
{
if (fprintf(fd, "<Nop>") < 0)
return FAIL;
return OK;
}
for ( ; *str != NUL; ++str)
{
char_u *p;
/* Check for a multi-byte character, which may contain escaped
* K_SPECIAL and CSI bytes */
p = mb_unescape(&str);
if (p != NULL)
{
while (*p != NUL)
if (fputc(*p++, fd) < 0)
return FAIL;
--str;
continue;
}
c = *str;
/*
* Special key codes have to be translated to be able to make sense
* when they are read back.
*/
if (c == K_SPECIAL && what != 2)
{
modifiers = 0x0;
if (str[1] == KS_MODIFIER)
{
modifiers = str[2];
str += 3;
c = *str;
}
if (c == K_SPECIAL)
{
c = TO_SPECIAL(str[1], str[2]);
str += 2;
}
if (IS_SPECIAL(c) || modifiers) /* special key */
{
if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
return FAIL;
continue;
}
}
/*
* A '\n' in a map command should be written as <NL>.
* A '\n' in a set command should be written as \^V^J.
*/
if (c == NL)
{
if (what == 2)
{
if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
return FAIL;
}
else
{
if (fprintf(fd, "<NL>") < 0)
return FAIL;
}
continue;
}
/*
* Some characters have to be escaped with CTRL-V to
* prevent them from misinterpreted in DoOneCmd().
* A space, Tab and '"' has to be escaped with a backslash to
* prevent it to be misinterpreted in do_set().
* A space has to be escaped with a CTRL-V when it's at the start of a
* ":map" rhs.
* A '<' has to be escaped with a CTRL-V to prevent it being
* interpreted as the start of a special key name.
* A space in the lhs of a :map needs a CTRL-V.
*/
if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
{
if (putc('\\', fd) < 0)
return FAIL;
}
else if (c < ' ' || c > '~' || c == '|'
|| (what == 0 && c == ' ')
|| (what == 1 && str == strstart && c == ' ')
|| (what != 2 && c == '<'))
{
if (putc(Ctrl_V, fd) < 0)
return FAIL;
}
if (putc(c, fd) < 0)
return FAIL;
}
return OK;
}
/*
* Check all mappings for the presence of special key codes.
* Used after ":set term=xxx".
*/
void
check_map_keycodes(void)
{
mapblock_T *mp;
char_u *p;
int i;
char_u buf[3];
char_u *save_name;
int abbr;
int hash;
#ifdef FEAT_LOCALMAP
buf_T *bp;
#endif
validate_maphash();
save_name = sourcing_name;
sourcing_name = (char_u *)"mappings"; /* avoids giving error messages */
#ifdef FEAT_LOCALMAP
/* This this once for each buffer, and then once for global
* mappings/abbreviations with bp == NULL */
for (bp = firstbuf; ; bp = bp->b_next)
{
#endif
/*
* Do the loop twice: Once for mappings, once for abbreviations.
* Then loop over all map hash lists.
*/
for (abbr = 0; abbr <= 1; ++abbr)
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash) /* there is only one abbr list */
break;
#ifdef FEAT_LOCALMAP
if (bp != NULL)
mp = bp->b_first_abbr;
else
#endif
mp = first_abbr;
}
else
{
#ifdef FEAT_LOCALMAP
if (bp != NULL)
mp = bp->b_maphash[hash];
else
#endif
mp = maphash[hash];
}
for ( ; mp != NULL; mp = mp->m_next)
{
for (i = 0; i <= 1; ++i) /* do this twice */
{
if (i == 0)
p = mp->m_keys; /* once for the "from" part */
else
p = mp->m_str; /* and once for the "to" part */
while (*p)
{
if (*p == K_SPECIAL)
{
++p;
if (*p < 128) /* for "normal" tcap entries */
{
buf[0] = p[0];
buf[1] = p[1];
buf[2] = NUL;
(void)add_termcap_entry(buf, FALSE);
}
++p;
}
++p;
}
}
}
}
#ifdef FEAT_LOCALMAP
if (bp == NULL)
break;
}
#endif
sourcing_name = save_name;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Check the string "keys" against the lhs of all mappings.
* Return pointer to rhs of mapping (mapblock->m_str).
* NULL when no mapping found.
*/
char_u *
check_map(
char_u *keys,
int mode,
int exact, /* require exact match */
int ign_mod, /* ignore preceding modifier */
int abbr, /* do abbreviations */
mapblock_T **mp_ptr, /* return: pointer to mapblock or NULL */
int *local_ptr) /* return: buffer-local mapping or NULL */
{
int hash;
int len, minlen;
mapblock_T *mp;
char_u *s;
#ifdef FEAT_LOCALMAP
int local;
#endif
validate_maphash();
len = (int)STRLEN(keys);
#ifdef FEAT_LOCALMAP
for (local = 1; local >= 0; --local)
#endif
/* loop over all hash lists */
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one list. */
break;
#ifdef FEAT_LOCALMAP
if (local)
mp = curbuf->b_first_abbr;
else
#endif
mp = first_abbr;
}
#ifdef FEAT_LOCALMAP
else if (local)
mp = curbuf->b_maphash[hash];
#endif
else
mp = maphash[hash];
for ( ; mp != NULL; mp = mp->m_next)
{
/* skip entries with wrong mode, wrong length and not matching
* ones */
if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
{
if (len > mp->m_keylen)
minlen = mp->m_keylen;
else
minlen = len;
s = mp->m_keys;
if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
&& s[2] != NUL)
{
s += 3;
if (len > mp->m_keylen - 3)
minlen = mp->m_keylen - 3;
}
if (STRNCMP(s, keys, minlen) == 0)
{
if (mp_ptr != NULL)
*mp_ptr = mp;
if (local_ptr != NULL)
#ifdef FEAT_LOCALMAP
*local_ptr = local;
#else
*local_ptr = 0;
#endif
return mp->m_str;
}
}
}
}
return NULL;
}
#endif
#if defined(MSWIN) || defined(MACOS_X)
# define VIS_SEL (VISUAL+SELECTMODE) /* abbreviation */
/*
* Default mappings for some often used keys.
*/
struct initmap
{
char_u *arg;
int mode;
};
# ifdef FEAT_GUI_MSWIN
/* Use the Windows (CUA) keybindings. (GUI) */
static struct initmap initmappings[] =
{
/* paste, copy and cut */
{(char_u *)"<S-Insert> \"*P", NORMAL},
{(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
{(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
{(char_u *)"<C-Insert> \"*y", VIS_SEL},
{(char_u *)"<S-Del> \"*d", VIS_SEL},
{(char_u *)"<C-Del> \"*d", VIS_SEL},
{(char_u *)"<C-X> \"*d", VIS_SEL},
/* Missing: CTRL-C (cancel) and CTRL-V (block selection) */
};
# endif
# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
/* Use the Windows (CUA) keybindings. (Console) */
static struct initmap cinitmappings[] =
{
{(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
{(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
{(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
{(char_u *)"\316u <C-End>", INSERT+CMDLINE},
/* paste, copy and cut */
# ifdef FEAT_CLIPBOARD
{(char_u *)"\316\324 \"*P", NORMAL}, /* SHIFT-Insert is "*P */
{(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, /* SHIFT-Insert is "-d"*P */
{(char_u *)"\316\324 \022\017*", INSERT}, /* SHIFT-Insert is ^R^O* */
{(char_u *)"\316\325 \"*y", VIS_SEL}, /* CTRL-Insert is "*y */
{(char_u *)"\316\327 \"*d", VIS_SEL}, /* SHIFT-Del is "*d */
{(char_u *)"\316\330 \"*d", VIS_SEL}, /* CTRL-Del is "*d */
{(char_u *)"\030 \"*d", VIS_SEL}, /* CTRL-X is "*d */
# else
{(char_u *)"\316\324 P", NORMAL}, /* SHIFT-Insert is P */
{(char_u *)"\316\324 \"-dP", VIS_SEL}, /* SHIFT-Insert is "-dP */
{(char_u *)"\316\324 \022\017\"", INSERT}, /* SHIFT-Insert is ^R^O" */
{(char_u *)"\316\325 y", VIS_SEL}, /* CTRL-Insert is y */
{(char_u *)"\316\327 d", VIS_SEL}, /* SHIFT-Del is d */
{(char_u *)"\316\330 d", VIS_SEL}, /* CTRL-Del is d */
# endif
};
# endif
# if defined(MACOS_X)
static struct initmap initmappings[] =
{
/* Use the Standard MacOS binding. */
/* paste, copy and cut */
{(char_u *)"<D-v> \"*P", NORMAL},
{(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
{(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
{(char_u *)"<D-c> \"*y", VIS_SEL},
{(char_u *)"<D-x> \"*d", VIS_SEL},
{(char_u *)"<Backspace> \"-d", VIS_SEL},
};
# endif
# undef VIS_SEL
#endif
/*
* Set up default mappings.
*/
void
init_mappings(void)
{
#if defined(MSWIN) || defined(MACOS_X)
int i;
# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
# ifdef VIMDLL
if (!gui.starting)
# endif
{
for (i = 0;
i < (int)(sizeof(cinitmappings) / sizeof(struct initmap)); ++i)
add_map(cinitmappings[i].arg, cinitmappings[i].mode);
}
# endif
# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
for (i = 0; i < (int)(sizeof(initmappings) / sizeof(struct initmap)); ++i)
add_map(initmappings[i].arg, initmappings[i].mode);
# endif
#endif
}
#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
|| defined(PROTO)
/*
* Add a mapping "map" for mode "mode".
* Need to put string in allocated memory, because do_map() will modify it.
*/
void
add_map(char_u *map, int mode)
{
char_u *s;
char_u *cpo_save = p_cpo;
p_cpo = (char_u *)""; /* Allow <> notation */
s = vim_strsave(map);
if (s != NULL)
{
(void)do_map(0, s, mode, FALSE);
vim_free(s);
}
p_cpo = cpo_save;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-78/c/bad_882_0 |
crossvul-cpp_data_good_882_0 | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* getchar.c
*
* functions related with getting a character from the user/mapping/redo/...
*
* manipulations with redo buffer and stuff buffer
* mappings and abbreviations
*/
#include "vim.h"
/*
* These buffers are used for storing:
* - stuffed characters: A command that is translated into another command.
* - redo characters: will redo the last change.
* - recorded characters: for the "q" command.
*
* The bytes are stored like in the typeahead buffer:
* - K_SPECIAL introduces a special key (two more bytes follow). A literal
* K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
* - CSI introduces a GUI termcap code (also when gui.in_use is FALSE,
* otherwise switching the GUI on would make mappings invalid).
* A literal CSI is stored as CSI KS_EXTRA KE_CSI.
* These translations are also done on multi-byte characters!
*
* Escaping CSI bytes is done by the system-specific input functions, called
* by ui_inchar().
* Escaping K_SPECIAL is done by inchar().
* Un-escaping is done by vgetc().
*/
#define MINIMAL_SIZE 20 /* minimal size for b_str */
static buffheader_T redobuff = {{NULL, {NUL}}, NULL, 0, 0};
static buffheader_T old_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
static buffheader_T recordbuff = {{NULL, {NUL}}, NULL, 0, 0};
static int typeahead_char = 0; /* typeahead char that's not flushed */
/*
* when block_redo is TRUE redo buffer will not be changed
* used by edit() to repeat insertions and 'V' command for redoing
*/
static int block_redo = FALSE;
/*
* Make a hash value for a mapping.
* "mode" is the lower 4 bits of the State for the mapping.
* "c1" is the first character of the "lhs".
* Returns a value between 0 and 255, index in maphash.
* Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
*/
#define MAP_HASH(mode, c1) (((mode) & (NORMAL + VISUAL + SELECTMODE + OP_PENDING + TERMINAL)) ? (c1) : ((c1) ^ 0x80))
/*
* Each mapping is put in one of the 256 hash lists, to speed up finding it.
*/
static mapblock_T *(maphash[256]);
static int maphash_valid = FALSE;
/*
* List used for abbreviations.
*/
static mapblock_T *first_abbr = NULL; /* first entry in abbrlist */
static int KeyNoremap = 0; /* remapping flags */
/*
* Variables used by vgetorpeek() and flush_buffers().
*
* typebuf.tb_buf[] contains all characters that are not consumed yet.
* typebuf.tb_buf[typebuf.tb_off] is the first valid character.
* typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
* typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
* The head of the buffer may contain the result of mappings, abbreviations
* and @a commands. The length of this part is typebuf.tb_maplen.
* typebuf.tb_silent is the part where <silent> applies.
* After the head are characters that come from the terminal.
* typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
* should not be considered for abbreviations.
* Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
* in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
* contains RM_NONE for the characters that are not to be remapped.
* typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
* (typebuf has been put in globals.h, because check_termcode() needs it).
*/
#define RM_YES 0 /* tb_noremap: remap */
#define RM_NONE 1 /* tb_noremap: don't remap */
#define RM_SCRIPT 2 /* tb_noremap: remap local script mappings */
#define RM_ABBR 4 /* tb_noremap: don't remap, do abbrev. */
/* typebuf.tb_buf has three parts: room in front (for result of mappings), the
* middle for typeahead and room for new characters (which needs to be 3 *
* MAXMAPLEN) for the Amiga).
*/
#define TYPELEN_INIT (5 * (MAXMAPLEN + 3))
static char_u typebuf_init[TYPELEN_INIT]; /* initial typebuf.tb_buf */
static char_u noremapbuf_init[TYPELEN_INIT]; /* initial typebuf.tb_noremap */
static int last_recorded_len = 0; /* number of last recorded chars */
static int read_readbuf(buffheader_T *buf, int advance);
static void init_typebuf(void);
static void may_sync_undo(void);
static void closescript(void);
static int vgetorpeek(int);
static void map_free(mapblock_T **);
static void validate_maphash(void);
static void showmap(mapblock_T *mp, int local);
static int inchar(char_u *buf, int maxlen, long wait_time);
#ifdef FEAT_EVAL
static char_u *eval_map_expr(char_u *str, int c);
#endif
/*
* Free and clear a buffer.
*/
void
free_buff(buffheader_T *buf)
{
buffblock_T *p, *np;
for (p = buf->bh_first.b_next; p != NULL; p = np)
{
np = p->b_next;
vim_free(p);
}
buf->bh_first.b_next = NULL;
}
/*
* Return the contents of a buffer as a single string.
* K_SPECIAL and CSI in the returned string are escaped.
*/
static char_u *
get_buffcont(
buffheader_T *buffer,
int dozero) /* count == zero is not an error */
{
long_u count = 0;
char_u *p = NULL;
char_u *p2;
char_u *str;
buffblock_T *bp;
/* compute the total length of the string */
for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
count += (long_u)STRLEN(bp->b_str);
if ((count || dozero) && (p = lalloc(count + 1, TRUE)) != NULL)
{
p2 = p;
for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
for (str = bp->b_str; *str; )
*p2++ = *str++;
*p2 = NUL;
}
return (p);
}
/*
* Return the contents of the record buffer as a single string
* and clear the record buffer.
* K_SPECIAL and CSI in the returned string are escaped.
*/
char_u *
get_recorded(void)
{
char_u *p;
size_t len;
p = get_buffcont(&recordbuff, TRUE);
free_buff(&recordbuff);
/*
* Remove the characters that were added the last time, these must be the
* (possibly mapped) characters that stopped the recording.
*/
len = STRLEN(p);
if ((int)len >= last_recorded_len)
{
len -= last_recorded_len;
p[len] = NUL;
}
/*
* When stopping recording from Insert mode with CTRL-O q, also remove the
* CTRL-O.
*/
if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O)
p[len - 1] = NUL;
return (p);
}
/*
* Return the contents of the redo buffer as a single string.
* K_SPECIAL and CSI in the returned string are escaped.
*/
char_u *
get_inserted(void)
{
return get_buffcont(&redobuff, FALSE);
}
/*
* Add string "s" after the current block of buffer "buf".
* K_SPECIAL and CSI should have been escaped already.
*/
static void
add_buff(
buffheader_T *buf,
char_u *s,
long slen) /* length of "s" or -1 */
{
buffblock_T *p;
long_u len;
if (slen < 0)
slen = (long)STRLEN(s);
if (slen == 0) /* don't add empty strings */
return;
if (buf->bh_first.b_next == NULL) /* first add to list */
{
buf->bh_space = 0;
buf->bh_curr = &(buf->bh_first);
}
else if (buf->bh_curr == NULL) /* buffer has already been read */
{
iemsg(_("E222: Add to read buffer"));
return;
}
else if (buf->bh_index != 0)
mch_memmove(buf->bh_first.b_next->b_str,
buf->bh_first.b_next->b_str + buf->bh_index,
STRLEN(buf->bh_first.b_next->b_str + buf->bh_index) + 1);
buf->bh_index = 0;
if (buf->bh_space >= (int)slen)
{
len = (long_u)STRLEN(buf->bh_curr->b_str);
vim_strncpy(buf->bh_curr->b_str + len, s, (size_t)slen);
buf->bh_space -= slen;
}
else
{
if (slen < MINIMAL_SIZE)
len = MINIMAL_SIZE;
else
len = slen;
p = (buffblock_T *)lalloc((long_u)(sizeof(buffblock_T) + len),
TRUE);
if (p == NULL)
return; /* no space, just forget it */
buf->bh_space = (int)(len - slen);
vim_strncpy(p->b_str, s, (size_t)slen);
p->b_next = buf->bh_curr->b_next;
buf->bh_curr->b_next = p;
buf->bh_curr = p;
}
return;
}
/*
* Add number "n" to buffer "buf".
*/
static void
add_num_buff(buffheader_T *buf, long n)
{
char_u number[32];
sprintf((char *)number, "%ld", n);
add_buff(buf, number, -1L);
}
/*
* Add character 'c' to buffer "buf".
* Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
*/
static void
add_char_buff(buffheader_T *buf, int c)
{
char_u bytes[MB_MAXBYTES + 1];
int len;
int i;
char_u temp[4];
if (IS_SPECIAL(c))
len = 1;
else
len = (*mb_char2bytes)(c, bytes);
for (i = 0; i < len; ++i)
{
if (!IS_SPECIAL(c))
c = bytes[i];
if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL)
{
/* translate special key code into three byte sequence */
temp[0] = K_SPECIAL;
temp[1] = K_SECOND(c);
temp[2] = K_THIRD(c);
temp[3] = NUL;
}
#ifdef FEAT_GUI
else if (c == CSI)
{
/* Translate a CSI to a CSI - KS_EXTRA - KE_CSI sequence */
temp[0] = CSI;
temp[1] = KS_EXTRA;
temp[2] = (int)KE_CSI;
temp[3] = NUL;
}
#endif
else
{
temp[0] = c;
temp[1] = NUL;
}
add_buff(buf, temp, -1L);
}
}
/* First read ahead buffer. Used for translated commands. */
static buffheader_T readbuf1 = {{NULL, {NUL}}, NULL, 0, 0};
/* Second read ahead buffer. Used for redo. */
static buffheader_T readbuf2 = {{NULL, {NUL}}, NULL, 0, 0};
/*
* Get one byte from the read buffers. Use readbuf1 one first, use readbuf2
* if that one is empty.
* If advance == TRUE go to the next char.
* No translation is done K_SPECIAL and CSI are escaped.
*/
static int
read_readbuffers(int advance)
{
int c;
c = read_readbuf(&readbuf1, advance);
if (c == NUL)
c = read_readbuf(&readbuf2, advance);
return c;
}
static int
read_readbuf(buffheader_T *buf, int advance)
{
char_u c;
buffblock_T *curr;
if (buf->bh_first.b_next == NULL) /* buffer is empty */
return NUL;
curr = buf->bh_first.b_next;
c = curr->b_str[buf->bh_index];
if (advance)
{
if (curr->b_str[++buf->bh_index] == NUL)
{
buf->bh_first.b_next = curr->b_next;
vim_free(curr);
buf->bh_index = 0;
}
}
return c;
}
/*
* Prepare the read buffers for reading (if they contain something).
*/
static void
start_stuff(void)
{
if (readbuf1.bh_first.b_next != NULL)
{
readbuf1.bh_curr = &(readbuf1.bh_first);
readbuf1.bh_space = 0;
}
if (readbuf2.bh_first.b_next != NULL)
{
readbuf2.bh_curr = &(readbuf2.bh_first);
readbuf2.bh_space = 0;
}
}
/*
* Return TRUE if the stuff buffer is empty.
*/
int
stuff_empty(void)
{
return (readbuf1.bh_first.b_next == NULL
&& readbuf2.bh_first.b_next == NULL);
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if readbuf1 is empty. There may still be redo characters in
* redbuf2.
*/
int
readbuf1_empty(void)
{
return (readbuf1.bh_first.b_next == NULL);
}
#endif
/*
* Set a typeahead character that won't be flushed.
*/
void
typeahead_noflush(int c)
{
typeahead_char = c;
}
/*
* Remove the contents of the stuff buffer and the mapped characters in the
* typeahead buffer (used in case of an error). If "flush_typeahead" is true,
* flush all typeahead characters (used when interrupted by a CTRL-C).
*/
void
flush_buffers(flush_buffers_T flush_typeahead)
{
init_typebuf();
start_stuff();
while (read_readbuffers(TRUE) != NUL)
;
if (flush_typeahead == FLUSH_MINIMAL)
{
// remove mapped characters at the start only
typebuf.tb_off += typebuf.tb_maplen;
typebuf.tb_len -= typebuf.tb_maplen;
}
else
{
// remove typeahead
if (flush_typeahead == FLUSH_INPUT)
// We have to get all characters, because we may delete the first
// part of an escape sequence. In an xterm we get one char at a
// time and we have to get them all.
while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10L) != 0)
;
typebuf.tb_off = MAXMAPLEN;
typebuf.tb_len = 0;
#if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
/* Reset the flag that text received from a client or from feedkeys()
* was inserted in the typeahead buffer. */
typebuf_was_filled = FALSE;
#endif
}
typebuf.tb_maplen = 0;
typebuf.tb_silent = 0;
cmd_silent = FALSE;
typebuf.tb_no_abbr_cnt = 0;
}
/*
* The previous contents of the redo buffer is kept in old_redobuffer.
* This is used for the CTRL-O <.> command in insert mode.
*/
void
ResetRedobuff(void)
{
if (!block_redo)
{
free_buff(&old_redobuff);
old_redobuff = redobuff;
redobuff.bh_first.b_next = NULL;
}
}
/*
* Discard the contents of the redo buffer and restore the previous redo
* buffer.
*/
void
CancelRedo(void)
{
if (!block_redo)
{
free_buff(&redobuff);
redobuff = old_redobuff;
old_redobuff.bh_first.b_next = NULL;
start_stuff();
while (read_readbuffers(TRUE) != NUL)
;
}
}
/*
* Save redobuff and old_redobuff to save_redobuff and save_old_redobuff.
* Used before executing autocommands and user functions.
*/
void
saveRedobuff(save_redo_T *save_redo)
{
char_u *s;
save_redo->sr_redobuff = redobuff;
redobuff.bh_first.b_next = NULL;
save_redo->sr_old_redobuff = old_redobuff;
old_redobuff.bh_first.b_next = NULL;
/* Make a copy, so that ":normal ." in a function works. */
s = get_buffcont(&save_redo->sr_redobuff, FALSE);
if (s != NULL)
{
add_buff(&redobuff, s, -1L);
vim_free(s);
}
}
/*
* Restore redobuff and old_redobuff from save_redobuff and save_old_redobuff.
* Used after executing autocommands and user functions.
*/
void
restoreRedobuff(save_redo_T *save_redo)
{
free_buff(&redobuff);
redobuff = save_redo->sr_redobuff;
free_buff(&old_redobuff);
old_redobuff = save_redo->sr_old_redobuff;
}
/*
* Append "s" to the redo buffer.
* K_SPECIAL and CSI should already have been escaped.
*/
void
AppendToRedobuff(char_u *s)
{
if (!block_redo)
add_buff(&redobuff, s, -1L);
}
/*
* Append to Redo buffer literally, escaping special characters with CTRL-V.
* K_SPECIAL and CSI are escaped as well.
*/
void
AppendToRedobuffLit(
char_u *str,
int len) /* length of "str" or -1 for up to the NUL */
{
char_u *s = str;
int c;
char_u *start;
if (block_redo)
return;
while (len < 0 ? *s != NUL : s - str < len)
{
/* Put a string of normal characters in the redo buffer (that's
* faster). */
start = s;
while (*s >= ' '
#ifndef EBCDIC
&& *s < DEL /* EBCDIC: all chars above space are normal */
#endif
&& (len < 0 || s - str < len))
++s;
/* Don't put '0' or '^' as last character, just in case a CTRL-D is
* typed next. */
if (*s == NUL && (s[-1] == '0' || s[-1] == '^'))
--s;
if (s > start)
add_buff(&redobuff, start, (long)(s - start));
if (*s == NUL || (len >= 0 && s - str >= len))
break;
/* Handle a special or multibyte character. */
if (has_mbyte)
/* Handle composing chars separately. */
c = mb_cptr2char_adv(&s);
else
c = *s++;
if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^')))
add_char_buff(&redobuff, Ctrl_V);
/* CTRL-V '0' must be inserted as CTRL-V 048 (EBCDIC: xf0) */
if (*s == NUL && c == '0')
#ifdef EBCDIC
add_buff(&redobuff, (char_u *)"xf0", 3L);
#else
add_buff(&redobuff, (char_u *)"048", 3L);
#endif
else
add_char_buff(&redobuff, c);
}
}
/*
* Append a character to the redo buffer.
* Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
*/
void
AppendCharToRedobuff(int c)
{
if (!block_redo)
add_char_buff(&redobuff, c);
}
/*
* Append a number to the redo buffer.
*/
void
AppendNumberToRedobuff(long n)
{
if (!block_redo)
add_num_buff(&redobuff, n);
}
/*
* Append string "s" to the stuff buffer.
* CSI and K_SPECIAL must already have been escaped.
*/
void
stuffReadbuff(char_u *s)
{
add_buff(&readbuf1, s, -1L);
}
/*
* Append string "s" to the redo stuff buffer.
* CSI and K_SPECIAL must already have been escaped.
*/
void
stuffRedoReadbuff(char_u *s)
{
add_buff(&readbuf2, s, -1L);
}
void
stuffReadbuffLen(char_u *s, long len)
{
add_buff(&readbuf1, s, len);
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Stuff "s" into the stuff buffer, leaving special key codes unmodified and
* escaping other K_SPECIAL and CSI bytes.
* Change CR, LF and ESC into a space.
*/
void
stuffReadbuffSpec(char_u *s)
{
int c;
while (*s != NUL)
{
if (*s == K_SPECIAL && s[1] != NUL && s[2] != NUL)
{
/* Insert special key literally. */
stuffReadbuffLen(s, 3L);
s += 3;
}
else
{
c = mb_ptr2char_adv(&s);
if (c == CAR || c == NL || c == ESC)
c = ' ';
stuffcharReadbuff(c);
}
}
}
#endif
/*
* Append a character to the stuff buffer.
* Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
*/
void
stuffcharReadbuff(int c)
{
add_char_buff(&readbuf1, c);
}
/*
* Append a number to the stuff buffer.
*/
void
stuffnumReadbuff(long n)
{
add_num_buff(&readbuf1, n);
}
/*
* Read a character from the redo buffer. Translates K_SPECIAL, CSI and
* multibyte characters.
* The redo buffer is left as it is.
* If init is TRUE, prepare for redo, return FAIL if nothing to redo, OK
* otherwise.
* If old is TRUE, use old_redobuff instead of redobuff.
*/
static int
read_redo(int init, int old_redo)
{
static buffblock_T *bp;
static char_u *p;
int c;
int n;
char_u buf[MB_MAXBYTES + 1];
int i;
if (init)
{
if (old_redo)
bp = old_redobuff.bh_first.b_next;
else
bp = redobuff.bh_first.b_next;
if (bp == NULL)
return FAIL;
p = bp->b_str;
return OK;
}
if ((c = *p) != NUL)
{
/* Reverse the conversion done by add_char_buff() */
/* For a multi-byte character get all the bytes and return the
* converted character. */
if (has_mbyte && (c != K_SPECIAL || p[1] == KS_SPECIAL))
n = MB_BYTE2LEN_CHECK(c);
else
n = 1;
for (i = 0; ; ++i)
{
if (c == K_SPECIAL) /* special key or escaped K_SPECIAL */
{
c = TO_SPECIAL(p[1], p[2]);
p += 2;
}
#ifdef FEAT_GUI
if (c == CSI) /* escaped CSI */
p += 2;
#endif
if (*++p == NUL && bp->b_next != NULL)
{
bp = bp->b_next;
p = bp->b_str;
}
buf[i] = c;
if (i == n - 1) /* last byte of a character */
{
if (n != 1)
c = (*mb_ptr2char)(buf);
break;
}
c = *p;
if (c == NUL) /* cannot happen? */
break;
}
}
return c;
}
/*
* Copy the rest of the redo buffer into the stuff buffer (in a slow way).
* If old_redo is TRUE, use old_redobuff instead of redobuff.
* The escaped K_SPECIAL and CSI are copied without translation.
*/
static void
copy_redo(int old_redo)
{
int c;
while ((c = read_redo(FALSE, old_redo)) != NUL)
add_char_buff(&readbuf2, c);
}
/*
* Stuff the redo buffer into readbuf2.
* Insert the redo count into the command.
* If "old_redo" is TRUE, the last but one command is repeated
* instead of the last command (inserting text). This is used for
* CTRL-O <.> in insert mode
*
* return FAIL for failure, OK otherwise
*/
int
start_redo(long count, int old_redo)
{
int c;
/* init the pointers; return if nothing to redo */
if (read_redo(TRUE, old_redo) == FAIL)
return FAIL;
c = read_redo(FALSE, old_redo);
/* copy the buffer name, if present */
if (c == '"')
{
add_buff(&readbuf2, (char_u *)"\"", 1L);
c = read_redo(FALSE, old_redo);
/* if a numbered buffer is used, increment the number */
if (c >= '1' && c < '9')
++c;
add_char_buff(&readbuf2, c);
/* the expression register should be re-evaluated */
if (c == '=')
{
add_char_buff(&readbuf2, CAR);
cmd_silent = TRUE;
}
c = read_redo(FALSE, old_redo);
}
if (c == 'v') /* redo Visual */
{
VIsual = curwin->w_cursor;
VIsual_active = TRUE;
VIsual_select = FALSE;
VIsual_reselect = TRUE;
redo_VIsual_busy = TRUE;
c = read_redo(FALSE, old_redo);
}
/* try to enter the count (in place of a previous count) */
if (count)
{
while (VIM_ISDIGIT(c)) /* skip "old" count */
c = read_redo(FALSE, old_redo);
add_num_buff(&readbuf2, count);
}
/* copy from the redo buffer into the stuff buffer */
add_char_buff(&readbuf2, c);
copy_redo(old_redo);
return OK;
}
/*
* Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
* the redo buffer into readbuf2.
* return FAIL for failure, OK otherwise
*/
int
start_redo_ins(void)
{
int c;
if (read_redo(TRUE, FALSE) == FAIL)
return FAIL;
start_stuff();
/* skip the count and the command character */
while ((c = read_redo(FALSE, FALSE)) != NUL)
{
if (vim_strchr((char_u *)"AaIiRrOo", c) != NULL)
{
if (c == 'O' || c == 'o')
add_buff(&readbuf2, NL_STR, -1L);
break;
}
}
/* copy the typed text from the redo buffer into the stuff buffer */
copy_redo(FALSE);
block_redo = TRUE;
return OK;
}
void
stop_redo_ins(void)
{
block_redo = FALSE;
}
/*
* Initialize typebuf.tb_buf to point to typebuf_init.
* alloc() cannot be used here: In out-of-memory situations it would
* be impossible to type anything.
*/
static void
init_typebuf(void)
{
if (typebuf.tb_buf == NULL)
{
typebuf.tb_buf = typebuf_init;
typebuf.tb_noremap = noremapbuf_init;
typebuf.tb_buflen = TYPELEN_INIT;
typebuf.tb_len = 0;
typebuf.tb_off = MAXMAPLEN + 4;
typebuf.tb_change_cnt = 1;
}
}
/*
* Insert a string in position 'offset' in the typeahead buffer (for "@r"
* and ":normal" command, vgetorpeek() and check_termcode()).
*
* If noremap is REMAP_YES, new string can be mapped again.
* If noremap is REMAP_NONE, new string cannot be mapped again.
* If noremap is REMAP_SKIP, fist char of new string cannot be mapped again,
* but abbreviations are allowed.
* If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for
* script-local mappings.
* If noremap is > 0, that many characters of the new string cannot be mapped.
*
* If nottyped is TRUE, the string does not return KeyTyped (don't use when
* offset is non-zero!).
*
* If silent is TRUE, cmd_silent is set when the characters are obtained.
*
* return FAIL for failure, OK otherwise
*/
int
ins_typebuf(
char_u *str,
int noremap,
int offset,
int nottyped,
int silent)
{
char_u *s1, *s2;
int newlen;
int addlen;
int i;
int newoff;
int val;
int nrm;
init_typebuf();
if (++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
addlen = (int)STRLEN(str);
if (offset == 0 && addlen <= typebuf.tb_off)
{
/*
* Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off]
*/
typebuf.tb_off -= addlen;
mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
}
else if (typebuf.tb_len == 0 && typebuf.tb_buflen
>= addlen + 3 * (MAXMAPLEN + 4))
{
/*
* Buffer is empty and string fits in the existing buffer.
* Leave some space before and after, if possible.
*/
typebuf.tb_off = (typebuf.tb_buflen - addlen - 3 * (MAXMAPLEN + 4)) / 2;
mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
}
else
{
/*
* Need to allocate a new buffer.
* In typebuf.tb_buf there must always be room for 3 * (MAXMAPLEN + 4)
* characters. We add some extra room to avoid having to allocate too
* often.
*/
newoff = MAXMAPLEN + 4;
newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4);
if (newlen < 0) /* string is getting too long */
{
emsg(_(e_toocompl)); /* also calls flush_buffers */
setcursor();
return FAIL;
}
s1 = alloc(newlen);
if (s1 == NULL) /* out of memory */
return FAIL;
s2 = alloc(newlen);
if (s2 == NULL) /* out of memory */
{
vim_free(s1);
return FAIL;
}
typebuf.tb_buflen = newlen;
/* copy the old chars, before the insertion point */
mch_memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off,
(size_t)offset);
/* copy the new chars */
mch_memmove(s1 + newoff + offset, str, (size_t)addlen);
/* copy the old chars, after the insertion point, including the NUL at
* the end */
mch_memmove(s1 + newoff + offset + addlen,
typebuf.tb_buf + typebuf.tb_off + offset,
(size_t)(typebuf.tb_len - offset + 1));
if (typebuf.tb_buf != typebuf_init)
vim_free(typebuf.tb_buf);
typebuf.tb_buf = s1;
mch_memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off,
(size_t)offset);
mch_memmove(s2 + newoff + offset + addlen,
typebuf.tb_noremap + typebuf.tb_off + offset,
(size_t)(typebuf.tb_len - offset));
if (typebuf.tb_noremap != noremapbuf_init)
vim_free(typebuf.tb_noremap);
typebuf.tb_noremap = s2;
typebuf.tb_off = newoff;
}
typebuf.tb_len += addlen;
/* If noremap == REMAP_SCRIPT: do remap script-local mappings. */
if (noremap == REMAP_SCRIPT)
val = RM_SCRIPT;
else if (noremap == REMAP_SKIP)
val = RM_ABBR;
else
val = RM_NONE;
/*
* Adjust typebuf.tb_noremap[] for the new characters:
* If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
* (sometimes) not remappable
* If noremap == REMAP_YES: all the new characters are mappable
* If noremap > 0: "noremap" characters are not remappable, the rest
* mappable
*/
if (noremap == REMAP_SKIP)
nrm = 1;
else if (noremap < 0)
nrm = addlen;
else
nrm = noremap;
for (i = 0; i < addlen; ++i)
typebuf.tb_noremap[typebuf.tb_off + i + offset] =
(--nrm >= 0) ? val : RM_YES;
/* tb_maplen and tb_silent only remember the length of mapped and/or
* silent mappings at the start of the buffer, assuming that a mapped
* sequence doesn't result in typed characters. */
if (nottyped || typebuf.tb_maplen > offset)
typebuf.tb_maplen += addlen;
if (silent || typebuf.tb_silent > offset)
{
typebuf.tb_silent += addlen;
cmd_silent = TRUE;
}
if (typebuf.tb_no_abbr_cnt && offset == 0) /* and not used for abbrev.s */
typebuf.tb_no_abbr_cnt += addlen;
return OK;
}
/*
* Put character "c" back into the typeahead buffer.
* Can be used for a character obtained by vgetc() that needs to be put back.
* Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to
* the char.
*/
void
ins_char_typebuf(int c)
{
char_u buf[MB_MAXBYTES + 1];
if (IS_SPECIAL(c))
{
buf[0] = K_SPECIAL;
buf[1] = K_SECOND(c);
buf[2] = K_THIRD(c);
buf[3] = NUL;
}
else
buf[(*mb_char2bytes)(c, buf)] = NUL;
(void)ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent);
}
/*
* Return TRUE if the typeahead buffer was changed (while waiting for a
* character to arrive). Happens when a message was received from a client or
* from feedkeys().
* But check in a more generic way to avoid trouble: When "typebuf.tb_buf"
* changed it was reallocated and the old pointer can no longer be used.
* Or "typebuf.tb_off" may have been changed and we would overwrite characters
* that was just added.
*/
int
typebuf_changed(
int tb_change_cnt) /* old value of typebuf.tb_change_cnt */
{
return (tb_change_cnt != 0 && (typebuf.tb_change_cnt != tb_change_cnt
#if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
|| typebuf_was_filled
#endif
));
}
/*
* Return TRUE if there are no characters in the typeahead buffer that have
* not been typed (result from a mapping or come from ":normal").
*/
int
typebuf_typed(void)
{
return typebuf.tb_maplen == 0;
}
/*
* Return the number of characters that are mapped (or not typed).
*/
int
typebuf_maplen(void)
{
return typebuf.tb_maplen;
}
/*
* remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
*/
void
del_typebuf(int len, int offset)
{
int i;
if (len == 0)
return; /* nothing to do */
typebuf.tb_len -= len;
/*
* Easy case: Just increase typebuf.tb_off.
*/
if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
>= 3 * MAXMAPLEN + 3)
typebuf.tb_off += len;
/*
* Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
*/
else
{
i = typebuf.tb_off + offset;
/*
* Leave some extra room at the end to avoid reallocation.
*/
if (typebuf.tb_off > MAXMAPLEN)
{
mch_memmove(typebuf.tb_buf + MAXMAPLEN,
typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
mch_memmove(typebuf.tb_noremap + MAXMAPLEN,
typebuf.tb_noremap + typebuf.tb_off, (size_t)offset);
typebuf.tb_off = MAXMAPLEN;
}
/* adjust typebuf.tb_buf (include the NUL at the end) */
mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset,
typebuf.tb_buf + i + len,
(size_t)(typebuf.tb_len - offset + 1));
/* adjust typebuf.tb_noremap[] */
mch_memmove(typebuf.tb_noremap + typebuf.tb_off + offset,
typebuf.tb_noremap + i + len,
(size_t)(typebuf.tb_len - offset));
}
if (typebuf.tb_maplen > offset) /* adjust tb_maplen */
{
if (typebuf.tb_maplen < offset + len)
typebuf.tb_maplen = offset;
else
typebuf.tb_maplen -= len;
}
if (typebuf.tb_silent > offset) /* adjust tb_silent */
{
if (typebuf.tb_silent < offset + len)
typebuf.tb_silent = offset;
else
typebuf.tb_silent -= len;
}
if (typebuf.tb_no_abbr_cnt > offset) /* adjust tb_no_abbr_cnt */
{
if (typebuf.tb_no_abbr_cnt < offset + len)
typebuf.tb_no_abbr_cnt = offset;
else
typebuf.tb_no_abbr_cnt -= len;
}
#if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
/* Reset the flag that text received from a client or from feedkeys()
* was inserted in the typeahead buffer. */
typebuf_was_filled = FALSE;
#endif
if (++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
}
/*
* Write typed characters to script file.
* If recording is on put the character in the recordbuffer.
*/
static void
gotchars(char_u *chars, int len)
{
char_u *s = chars;
int i;
static char_u buf[4];
static int buflen = 0;
int todo = len;
while (todo--)
{
buf[buflen++] = *s++;
// When receiving a special key sequence, store it until we have all
// the bytes and we can decide what to do with it.
if (buflen == 1 && buf[0] == K_SPECIAL)
continue;
if (buflen == 2)
continue;
if (buflen == 3 && buf[1] == KS_EXTRA
&& (buf[2] == KE_FOCUSGAINED || buf[2] == KE_FOCUSLOST))
{
// Drop K_FOCUSGAINED and K_FOCUSLOST, they are not useful in a
// recording.
buflen = 0;
continue;
}
/* Handle one byte at a time; no translation to be done. */
for (i = 0; i < buflen; ++i)
updatescript(buf[i]);
if (reg_recording != 0)
{
buf[buflen] = NUL;
add_buff(&recordbuff, buf, (long)buflen);
/* remember how many chars were last recorded */
last_recorded_len += buflen;
}
buflen = 0;
}
may_sync_undo();
#ifdef FEAT_EVAL
/* output "debug mode" message next time in debug mode */
debug_did_msg = FALSE;
#endif
/* Since characters have been typed, consider the following to be in
* another mapping. Search string will be kept in history. */
++maptick;
}
/*
* Sync undo. Called when typed characters are obtained from the typeahead
* buffer, or when a menu is used.
* Do not sync:
* - In Insert mode, unless cursor key has been used.
* - While reading a script file.
* - When no_u_sync is non-zero.
*/
static void
may_sync_undo(void)
{
if ((!(State & (INSERT + CMDLINE)) || arrow_used)
&& scriptin[curscript] == NULL)
u_sync(FALSE);
}
/*
* Make "typebuf" empty and allocate new buffers.
* Returns FAIL when out of memory.
*/
int
alloc_typebuf(void)
{
typebuf.tb_buf = alloc(TYPELEN_INIT);
typebuf.tb_noremap = alloc(TYPELEN_INIT);
if (typebuf.tb_buf == NULL || typebuf.tb_noremap == NULL)
{
free_typebuf();
return FAIL;
}
typebuf.tb_buflen = TYPELEN_INIT;
typebuf.tb_off = MAXMAPLEN + 4; /* can insert without realloc */
typebuf.tb_len = 0;
typebuf.tb_maplen = 0;
typebuf.tb_silent = 0;
typebuf.tb_no_abbr_cnt = 0;
if (++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
return OK;
}
/*
* Free the buffers of "typebuf".
*/
void
free_typebuf(void)
{
if (typebuf.tb_buf == typebuf_init)
internal_error("Free typebuf 1");
else
vim_free(typebuf.tb_buf);
if (typebuf.tb_noremap == noremapbuf_init)
internal_error("Free typebuf 2");
else
vim_free(typebuf.tb_noremap);
}
/*
* When doing ":so! file", the current typeahead needs to be saved, and
* restored when "file" has been read completely.
*/
static typebuf_T saved_typebuf[NSCRIPT];
int
save_typebuf(void)
{
init_typebuf();
saved_typebuf[curscript] = typebuf;
/* If out of memory: restore typebuf and close file. */
if (alloc_typebuf() == FAIL)
{
closescript();
return FAIL;
}
return OK;
}
static int old_char = -1; /* character put back by vungetc() */
static int old_mod_mask; /* mod_mask for ungotten character */
#ifdef FEAT_MOUSE
static int old_mouse_row; /* mouse_row related to old_char */
static int old_mouse_col; /* mouse_col related to old_char */
#endif
/*
* Save all three kinds of typeahead, so that the user must type at a prompt.
*/
void
save_typeahead(tasave_T *tp)
{
tp->save_typebuf = typebuf;
tp->typebuf_valid = (alloc_typebuf() == OK);
if (!tp->typebuf_valid)
typebuf = tp->save_typebuf;
tp->old_char = old_char;
tp->old_mod_mask = old_mod_mask;
old_char = -1;
tp->save_readbuf1 = readbuf1;
readbuf1.bh_first.b_next = NULL;
tp->save_readbuf2 = readbuf2;
readbuf2.bh_first.b_next = NULL;
# ifdef USE_INPUT_BUF
tp->save_inputbuf = get_input_buf();
# endif
}
/*
* Restore the typeahead to what it was before calling save_typeahead().
* The allocated memory is freed, can only be called once!
*/
void
restore_typeahead(tasave_T *tp)
{
if (tp->typebuf_valid)
{
free_typebuf();
typebuf = tp->save_typebuf;
}
old_char = tp->old_char;
old_mod_mask = tp->old_mod_mask;
free_buff(&readbuf1);
readbuf1 = tp->save_readbuf1;
free_buff(&readbuf2);
readbuf2 = tp->save_readbuf2;
# ifdef USE_INPUT_BUF
set_input_buf(tp->save_inputbuf);
# endif
}
/*
* Open a new script file for the ":source!" command.
*/
void
openscript(
char_u *name,
int directly) /* when TRUE execute directly */
{
if (curscript + 1 == NSCRIPT)
{
emsg(_(e_nesting));
return;
}
// Disallow sourcing a file in the sandbox, the commands would be executed
// later, possibly outside of the sandbox.
if (check_secure())
return;
#ifdef FEAT_EVAL
if (ignore_script)
/* Not reading from script, also don't open one. Warning message? */
return;
#endif
if (scriptin[curscript] != NULL) /* already reading script */
++curscript;
/* use NameBuff for expanded name */
expand_env(name, NameBuff, MAXPATHL);
if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
{
semsg(_(e_notopen), name);
if (curscript)
--curscript;
return;
}
if (save_typebuf() == FAIL)
return;
/*
* Execute the commands from the file right now when using ":source!"
* after ":global" or ":argdo" or in a loop. Also when another command
* follows. This means the display won't be updated. Don't do this
* always, "make test" would fail.
*/
if (directly)
{
oparg_T oa;
int oldcurscript;
int save_State = State;
int save_restart_edit = restart_edit;
int save_insertmode = p_im;
int save_finish_op = finish_op;
int save_msg_scroll = msg_scroll;
State = NORMAL;
msg_scroll = FALSE; /* no msg scrolling in Normal mode */
restart_edit = 0; /* don't go to Insert mode */
p_im = FALSE; /* don't use 'insertmode' */
clear_oparg(&oa);
finish_op = FALSE;
oldcurscript = curscript;
do
{
update_topline_cursor(); // update cursor position and topline
normal_cmd(&oa, FALSE); // execute one command
vpeekc(); // check for end of file
}
while (scriptin[oldcurscript] != NULL);
State = save_State;
msg_scroll = save_msg_scroll;
restart_edit = save_restart_edit;
p_im = save_insertmode;
finish_op = save_finish_op;
}
}
/*
* Close the currently active input script.
*/
static void
closescript(void)
{
free_typebuf();
typebuf = saved_typebuf[curscript];
fclose(scriptin[curscript]);
scriptin[curscript] = NULL;
if (curscript > 0)
--curscript;
}
#if defined(EXITFREE) || defined(PROTO)
void
close_all_scripts(void)
{
while (scriptin[0] != NULL)
closescript();
}
#endif
#if defined(FEAT_INS_EXPAND) || defined(PROTO)
/*
* Return TRUE when reading keys from a script file.
*/
int
using_script(void)
{
return scriptin[curscript] != NULL;
}
#endif
/*
* This function is called just before doing a blocking wait. Thus after
* waiting 'updatetime' for a character to arrive.
*/
void
before_blocking(void)
{
updatescript(0);
#ifdef FEAT_EVAL
if (may_garbage_collect)
garbage_collect(FALSE);
#endif
}
/*
* updatescipt() is called when a character can be written into the script file
* or when we have waited some time for a character (c == 0)
*
* All the changed memfiles are synced if c == 0 or when the number of typed
* characters reaches 'updatecount' and 'updatecount' is non-zero.
*/
void
updatescript(int c)
{
static int count = 0;
if (c && scriptout)
putc(c, scriptout);
if (c == 0 || (p_uc > 0 && ++count >= p_uc))
{
ml_sync_all(c == 0, TRUE);
count = 0;
}
}
/*
* Get the next input character.
* Can return a special key or a multi-byte character.
* Can return NUL when called recursively, use safe_vgetc() if that's not
* wanted.
* This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte.
* Collects the bytes of a multibyte character into the whole character.
* Returns the modifiers in the global "mod_mask".
*/
int
vgetc(void)
{
int c, c2;
int n;
char_u buf[MB_MAXBYTES + 1];
int i;
#ifdef FEAT_EVAL
/* Do garbage collection when garbagecollect() was called previously and
* we are now at the toplevel. */
if (may_garbage_collect && want_garbage_collect)
garbage_collect(FALSE);
#endif
/*
* If a character was put back with vungetc, it was already processed.
* Return it directly.
*/
if (old_char != -1)
{
c = old_char;
old_char = -1;
mod_mask = old_mod_mask;
#ifdef FEAT_MOUSE
mouse_row = old_mouse_row;
mouse_col = old_mouse_col;
#endif
}
else
{
mod_mask = 0x0;
last_recorded_len = 0;
for (;;) // this is done twice if there are modifiers
{
int did_inc = FALSE;
if (mod_mask
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
|| im_is_preediting()
#endif
)
{
// no mapping after modifier has been read
++no_mapping;
++allow_keys;
did_inc = TRUE; // mod_mask may change value
}
c = vgetorpeek(TRUE);
if (did_inc)
{
--no_mapping;
--allow_keys;
}
// Get two extra bytes for special keys
if (c == K_SPECIAL
#ifdef FEAT_GUI
|| (gui.in_use && c == CSI)
#endif
)
{
int save_allow_keys = allow_keys;
++no_mapping;
allow_keys = 0; // make sure BS is not found
c2 = vgetorpeek(TRUE); // no mapping for these chars
c = vgetorpeek(TRUE);
--no_mapping;
allow_keys = save_allow_keys;
if (c2 == KS_MODIFIER)
{
mod_mask = c;
continue;
}
c = TO_SPECIAL(c2, c);
#if defined(FEAT_GUI_MSWIN) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
// Handle K_TEAROFF here, the caller of vgetc() doesn't need to
// know that a menu was torn off
if (
# ifdef VIMDLL
gui.in_use &&
# endif
c == K_TEAROFF)
{
char_u name[200];
int i;
// get menu path, it ends with a <CR>
for (i = 0; (c = vgetorpeek(TRUE)) != '\r'; )
{
name[i] = c;
if (i < 199)
++i;
}
name[i] = NUL;
gui_make_tearoff(name);
continue;
}
#endif
#if defined(FEAT_GUI) && defined(FEAT_GUI_GTK) && defined(FEAT_MENU)
// GTK: <F10> normally selects the menu, but it's passed until
// here to allow mapping it. Intercept and invoke the GTK
// behavior if it's not mapped.
if (c == K_F10 && gui.menubar != NULL)
{
gtk_menu_shell_select_first(
GTK_MENU_SHELL(gui.menubar), FALSE);
continue;
}
#endif
#ifdef FEAT_GUI
if (gui.in_use)
{
// Handle focus event here, so that the caller doesn't
// need to know about it. Return K_IGNORE so that we loop
// once (needed if 'lazyredraw' is set).
if (c == K_FOCUSGAINED || c == K_FOCUSLOST)
{
ui_focus_change(c == K_FOCUSGAINED);
c = K_IGNORE;
}
// Translate K_CSI to CSI. The special key is only used
// to avoid it being recognized as the start of a special
// key.
if (c == K_CSI)
c = CSI;
}
#endif
}
// a keypad or special function key was not mapped, use it like
// its ASCII equivalent
switch (c)
{
case K_KPLUS: c = '+'; break;
case K_KMINUS: c = '-'; break;
case K_KDIVIDE: c = '/'; break;
case K_KMULTIPLY: c = '*'; break;
case K_KENTER: c = CAR; break;
case K_KPOINT:
#ifdef MSWIN
// Can be either '.' or a ',',
// depending on the type of keypad.
c = MapVirtualKey(VK_DECIMAL, 2); break;
#else
c = '.'; break;
#endif
case K_K0: c = '0'; break;
case K_K1: c = '1'; break;
case K_K2: c = '2'; break;
case K_K3: c = '3'; break;
case K_K4: c = '4'; break;
case K_K5: c = '5'; break;
case K_K6: c = '6'; break;
case K_K7: c = '7'; break;
case K_K8: c = '8'; break;
case K_K9: c = '9'; break;
case K_XHOME:
case K_ZHOME: if (mod_mask == MOD_MASK_SHIFT)
{
c = K_S_HOME;
mod_mask = 0;
}
else if (mod_mask == MOD_MASK_CTRL)
{
c = K_C_HOME;
mod_mask = 0;
}
else
c = K_HOME;
break;
case K_XEND:
case K_ZEND: if (mod_mask == MOD_MASK_SHIFT)
{
c = K_S_END;
mod_mask = 0;
}
else if (mod_mask == MOD_MASK_CTRL)
{
c = K_C_END;
mod_mask = 0;
}
else
c = K_END;
break;
case K_XUP: c = K_UP; break;
case K_XDOWN: c = K_DOWN; break;
case K_XLEFT: c = K_LEFT; break;
case K_XRIGHT: c = K_RIGHT; break;
}
// For a multi-byte character get all the bytes and return the
// converted character.
// Note: This will loop until enough bytes are received!
if (has_mbyte && (n = MB_BYTE2LEN_CHECK(c)) > 1)
{
++no_mapping;
buf[0] = c;
for (i = 1; i < n; ++i)
{
buf[i] = vgetorpeek(TRUE);
if (buf[i] == K_SPECIAL
#ifdef FEAT_GUI
|| (
# ifdef VIMDLL
gui.in_use &&
# endif
buf[i] == CSI)
#endif
)
{
// Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER
// sequence, which represents a K_SPECIAL (0x80),
// or a CSI - KS_EXTRA - KE_CSI sequence, which
// represents a CSI (0x9B),
// or a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI
// too.
c = vgetorpeek(TRUE);
if (vgetorpeek(TRUE) == (int)KE_CSI && c == KS_EXTRA)
buf[i] = CSI;
}
}
--no_mapping;
c = (*mb_ptr2char)(buf);
}
break;
}
}
#ifdef FEAT_EVAL
/*
* In the main loop "may_garbage_collect" can be set to do garbage
* collection in the first next vgetc(). It's disabled after that to
* avoid internally used Lists and Dicts to be freed.
*/
may_garbage_collect = FALSE;
#endif
#ifdef FEAT_BEVAL_TERM
if (c != K_MOUSEMOVE && c != K_IGNORE)
{
/* Don't trigger 'balloonexpr' unless only the mouse was moved. */
bevalexpr_due_set = FALSE;
ui_remove_balloon();
}
#endif
return c;
}
/*
* Like vgetc(), but never return a NUL when called recursively, get a key
* directly from the user (ignoring typeahead).
*/
int
safe_vgetc(void)
{
int c;
c = vgetc();
if (c == NUL)
c = get_keystroke();
return c;
}
/*
* Like safe_vgetc(), but loop to handle K_IGNORE.
* Also ignore scrollbar events.
*/
int
plain_vgetc(void)
{
int c;
do
c = safe_vgetc();
while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
if (c == K_PS)
/* Only handle the first pasted character. Drop the rest, since we
* don't know what to do with it. */
c = bracketed_paste(PASTE_ONE_CHAR, FALSE, NULL);
return c;
}
/*
* Check if a character is available, such that vgetc() will not block.
* If the next character is a special character or multi-byte, the returned
* character is not valid!.
* Returns NUL if no character is available.
*/
int
vpeekc(void)
{
if (old_char != -1)
return old_char;
return vgetorpeek(FALSE);
}
#if defined(FEAT_TERMRESPONSE) || defined(FEAT_TERMINAL) || defined(PROTO)
/*
* Like vpeekc(), but don't allow mapping. Do allow checking for terminal
* codes.
*/
int
vpeekc_nomap(void)
{
int c;
++no_mapping;
++allow_keys;
c = vpeekc();
--no_mapping;
--allow_keys;
return c;
}
#endif
#if defined(FEAT_INS_EXPAND) || defined(FEAT_EVAL) || defined(PROTO)
/*
* Check if any character is available, also half an escape sequence.
* Trick: when no typeahead found, but there is something in the typeahead
* buffer, it must be an ESC that is recognized as the start of a key code.
*/
int
vpeekc_any(void)
{
int c;
c = vpeekc();
if (c == NUL && typebuf.tb_len > 0)
c = ESC;
return c;
}
#endif
/*
* Call vpeekc() without causing anything to be mapped.
* Return TRUE if a character is available, FALSE otherwise.
*/
int
char_avail(void)
{
int retval;
#ifdef FEAT_EVAL
/* When test_override("char_avail", 1) was called pretend there is no
* typeahead. */
if (disable_char_avail_for_testing)
return FALSE;
#endif
++no_mapping;
retval = vpeekc();
--no_mapping;
return (retval != NUL);
}
/*
* unget one character (can only be done once!)
*/
void
vungetc(int c)
{
old_char = c;
old_mod_mask = mod_mask;
#ifdef FEAT_MOUSE
old_mouse_row = mouse_row;
old_mouse_col = mouse_col;
#endif
}
/*
* Get a byte:
* 1. from the stuffbuffer
* This is used for abbreviated commands like "D" -> "d$".
* Also used to redo a command for ".".
* 2. from the typeahead buffer
* Stores text obtained previously but not used yet.
* Also stores the result of mappings.
* Also used for the ":normal" command.
* 3. from the user
* This may do a blocking wait if "advance" is TRUE.
*
* if "advance" is TRUE (vgetc()):
* Really get the character.
* KeyTyped is set to TRUE in the case the user typed the key.
* KeyStuffed is TRUE if the character comes from the stuff buffer.
* if "advance" is FALSE (vpeekc()):
* Just look whether there is a character available.
* Return NUL if not.
*
* When "no_mapping" is zero, checks for mappings in the current mode.
* Only returns one byte (of a multi-byte character).
* K_SPECIAL and CSI may be escaped, need to get two more bytes then.
*/
static int
vgetorpeek(int advance)
{
int c, c1;
int keylen;
char_u *s;
mapblock_T *mp;
#ifdef FEAT_LOCALMAP
mapblock_T *mp2;
#endif
mapblock_T *mp_match;
int mp_match_len = 0;
int timedout = FALSE; /* waited for more than 1 second
for mapping to complete */
int mapdepth = 0; /* check for recursive mapping */
int mode_deleted = FALSE; /* set when mode has been deleted */
int local_State;
int mlen;
int max_mlen;
int i;
#ifdef FEAT_CMDL_INFO
int new_wcol, new_wrow;
#endif
#ifdef FEAT_GUI
# ifdef FEAT_MENU
int idx;
# endif
int shape_changed = FALSE; /* adjusted cursor shape */
#endif
int n;
#ifdef FEAT_LANGMAP
int nolmaplen;
#endif
int old_wcol, old_wrow;
int wait_tb_len;
/*
* This function doesn't work very well when called recursively. This may
* happen though, because of:
* 1. The call to add_to_showcmd(). char_avail() is then used to check if
* there is a character available, which calls this function. In that
* case we must return NUL, to indicate no character is available.
* 2. A GUI callback function writes to the screen, causing a
* wait_return().
* Using ":normal" can also do this, but it saves the typeahead buffer,
* thus it should be OK. But don't get a key from the user then.
*/
if (vgetc_busy > 0 && ex_normal_busy == 0)
return NUL;
local_State = get_real_state();
++vgetc_busy;
if (advance)
KeyStuffed = FALSE;
init_typebuf();
start_stuff();
if (advance && typebuf.tb_maplen == 0)
reg_executing = 0;
do
{
/*
* get a character: 1. from the stuffbuffer
*/
if (typeahead_char != 0)
{
c = typeahead_char;
if (advance)
typeahead_char = 0;
}
else
c = read_readbuffers(advance);
if (c != NUL && !got_int)
{
if (advance)
{
/* KeyTyped = FALSE; When the command that stuffed something
* was typed, behave like the stuffed command was typed.
* needed for CTRL-W CTRL-] to open a fold, for example. */
KeyStuffed = TRUE;
}
if (typebuf.tb_no_abbr_cnt == 0)
typebuf.tb_no_abbr_cnt = 1; /* no abbreviations now */
}
else
{
/*
* Loop until we either find a matching mapped key, or we
* are sure that it is not a mapped key.
* If a mapped key sequence is found we go back to the start to
* try re-mapping.
*/
for (;;)
{
long wait_time;
/*
* ui_breakcheck() is slow, don't use it too often when
* inside a mapping. But call it each time for typed
* characters.
*/
if (typebuf.tb_maplen)
line_breakcheck();
else
ui_breakcheck(); /* check for CTRL-C */
keylen = 0;
if (got_int)
{
/* flush all input */
c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0L);
/*
* If inchar() returns TRUE (script file was active) or we
* are inside a mapping, get out of Insert mode.
* Otherwise we behave like having gotten a CTRL-C.
* As a result typing CTRL-C in insert mode will
* really insert a CTRL-C.
*/
if ((c || typebuf.tb_maplen)
&& (State & (INSERT + CMDLINE)))
c = ESC;
else
c = Ctrl_C;
flush_buffers(FLUSH_INPUT); // flush all typeahead
if (advance)
{
/* Also record this character, it might be needed to
* get out of Insert mode. */
*typebuf.tb_buf = c;
gotchars(typebuf.tb_buf, 1);
}
cmd_silent = FALSE;
break;
}
else if (typebuf.tb_len > 0)
{
/*
* Check for a mappable key sequence.
* Walk through one maphash[] list until we find an
* entry that matches.
*
* Don't look for mappings if:
* - no_mapping set: mapping disabled (e.g. for CTRL-V)
* - maphash_valid not set: no mappings present.
* - typebuf.tb_buf[typebuf.tb_off] should not be remapped
* - in insert or cmdline mode and 'paste' option set
* - waiting for "hit return to continue" and CR or SPACE
* typed
* - waiting for a char with --more--
* - in Ctrl-X mode, and we get a valid char for that mode
*/
mp = NULL;
max_mlen = 0;
c1 = typebuf.tb_buf[typebuf.tb_off];
if (no_mapping == 0 && maphash_valid
&& (no_zero_mapping == 0 || c1 != '0')
&& (typebuf.tb_maplen == 0
|| (p_remap
&& (typebuf.tb_noremap[typebuf.tb_off]
& (RM_NONE|RM_ABBR)) == 0))
&& !(p_paste && (State & (INSERT + CMDLINE)))
&& !(State == HITRETURN && (c1 == CAR || c1 == ' '))
&& State != ASKMORE
&& State != CONFIRM
#ifdef FEAT_INS_EXPAND
&& !((ctrl_x_mode_not_default()
&& vim_is_ctrl_x_key(c1))
|| ((compl_cont_status & CONT_LOCAL)
&& (c1 == Ctrl_N || c1 == Ctrl_P)))
#endif
)
{
#ifdef FEAT_LANGMAP
if (c1 == K_SPECIAL)
nolmaplen = 2;
else
{
LANGMAP_ADJUST(c1,
(State & (CMDLINE | INSERT)) == 0
&& get_real_state() != SELECTMODE);
nolmaplen = 0;
}
#endif
#ifdef FEAT_LOCALMAP
/* First try buffer-local mappings. */
mp = curbuf->b_maphash[MAP_HASH(local_State, c1)];
mp2 = maphash[MAP_HASH(local_State, c1)];
if (mp == NULL)
{
/* There are no buffer-local mappings. */
mp = mp2;
mp2 = NULL;
}
#else
mp = maphash[MAP_HASH(local_State, c1)];
#endif
/*
* Loop until a partly matching mapping is found or
* all (local) mappings have been checked.
* The longest full match is remembered in "mp_match".
* A full match is only accepted if there is no partly
* match, so "aa" and "aaa" can both be mapped.
*/
mp_match = NULL;
mp_match_len = 0;
for ( ; mp != NULL;
#ifdef FEAT_LOCALMAP
mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
#endif
(mp = mp->m_next))
{
/*
* Only consider an entry if the first character
* matches and it is for the current state.
* Skip ":lmap" mappings if keys were mapped.
*/
if (mp->m_keys[0] == c1
&& (mp->m_mode & local_State)
&& ((mp->m_mode & LANGMAP) == 0
|| typebuf.tb_maplen == 0))
{
#ifdef FEAT_LANGMAP
int nomap = nolmaplen;
int c2;
#endif
/* find the match length of this mapping */
for (mlen = 1; mlen < typebuf.tb_len; ++mlen)
{
#ifdef FEAT_LANGMAP
c2 = typebuf.tb_buf[typebuf.tb_off + mlen];
if (nomap > 0)
--nomap;
else if (c2 == K_SPECIAL)
nomap = 2;
else
LANGMAP_ADJUST(c2, TRUE);
if (mp->m_keys[mlen] != c2)
#else
if (mp->m_keys[mlen] !=
typebuf.tb_buf[typebuf.tb_off + mlen])
#endif
break;
}
/* Don't allow mapping the first byte(s) of a
* multi-byte char. Happens when mapping
* <M-a> and then changing 'encoding'. Beware
* that 0x80 is escaped. */
{
char_u *p1 = mp->m_keys;
char_u *p2 = mb_unescape(&p1);
if (has_mbyte && p2 != NULL
&& MB_BYTE2LEN(c1) > MB_PTR2LEN(p2))
mlen = 0;
}
/*
* Check an entry whether it matches.
* - Full match: mlen == keylen
* - Partly match: mlen == typebuf.tb_len
*/
keylen = mp->m_keylen;
if (mlen == keylen
|| (mlen == typebuf.tb_len
&& typebuf.tb_len < keylen))
{
/*
* If only script-local mappings are
* allowed, check if the mapping starts
* with K_SNR.
*/
s = typebuf.tb_noremap + typebuf.tb_off;
if (*s == RM_SCRIPT
&& (mp->m_keys[0] != K_SPECIAL
|| mp->m_keys[1] != KS_EXTRA
|| mp->m_keys[2]
!= (int)KE_SNR))
continue;
/*
* If one of the typed keys cannot be
* remapped, skip the entry.
*/
for (n = mlen; --n >= 0; )
if (*s++ & (RM_NONE|RM_ABBR))
break;
if (n >= 0)
continue;
if (keylen > typebuf.tb_len)
{
if (!timedout && !(mp_match != NULL
&& mp_match->m_nowait))
{
/* break at a partly match */
keylen = KEYLEN_PART_MAP;
break;
}
}
else if (keylen > mp_match_len)
{
/* found a longer match */
mp_match = mp;
mp_match_len = keylen;
}
}
else
/* No match; may have to check for
* termcode at next character. */
if (max_mlen < mlen)
max_mlen = mlen;
}
}
/* If no partly match found, use the longest full
* match. */
if (keylen != KEYLEN_PART_MAP)
{
mp = mp_match;
keylen = mp_match_len;
}
}
/* Check for match with 'pastetoggle' */
if (*p_pt != NUL && mp == NULL && (State & (INSERT|NORMAL)))
{
for (mlen = 0; mlen < typebuf.tb_len && p_pt[mlen];
++mlen)
if (p_pt[mlen] != typebuf.tb_buf[typebuf.tb_off
+ mlen])
break;
if (p_pt[mlen] == NUL) /* match */
{
/* write chars to script file(s) */
if (mlen > typebuf.tb_maplen)
gotchars(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_maplen,
mlen - typebuf.tb_maplen);
del_typebuf(mlen, 0); /* remove the chars */
set_option_value((char_u *)"paste",
(long)!p_paste, NULL, 0);
if (!(State & INSERT))
{
msg_col = 0;
msg_row = Rows - 1;
msg_clr_eos(); /* clear ruler */
}
status_redraw_all();
redraw_statuslines();
showmode();
setcursor();
continue;
}
/* Need more chars for partly match. */
if (mlen == typebuf.tb_len)
keylen = KEYLEN_PART_KEY;
else if (max_mlen < mlen)
/* no match, may have to check for termcode at
* next character */
max_mlen = mlen + 1;
}
if ((mp == NULL || max_mlen >= mp_match_len)
&& keylen != KEYLEN_PART_MAP)
{
int save_keylen = keylen;
/*
* When no matching mapping found or found a
* non-matching mapping that matches at least what the
* matching mapping matched:
* Check if we have a terminal code, when:
* mapping is allowed,
* keys have not been mapped,
* and not an ESC sequence, not in insert mode or
* p_ek is on,
* and when not timed out,
*/
if ((no_mapping == 0 || allow_keys != 0)
&& (typebuf.tb_maplen == 0
|| (p_remap && typebuf.tb_noremap[
typebuf.tb_off] == RM_YES))
&& !timedout)
{
keylen = check_termcode(max_mlen + 1,
NULL, 0, NULL);
/* If no termcode matched but 'pastetoggle'
* matched partially it's like an incomplete key
* sequence. */
if (keylen == 0 && save_keylen == KEYLEN_PART_KEY)
keylen = KEYLEN_PART_KEY;
/*
* When getting a partial match, but the last
* characters were not typed, don't wait for a
* typed character to complete the termcode.
* This helps a lot when a ":normal" command ends
* in an ESC.
*/
if (keylen < 0
&& typebuf.tb_len == typebuf.tb_maplen)
keylen = 0;
}
else
keylen = 0;
if (keylen == 0) /* no matching terminal code */
{
#ifdef AMIGA /* check for window bounds report */
if (typebuf.tb_maplen == 0 && (typebuf.tb_buf[
typebuf.tb_off] & 0xff) == CSI)
{
for (s = typebuf.tb_buf + typebuf.tb_off + 1;
s < typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len
&& (VIM_ISDIGIT(*s) || *s == ';'
|| *s == ' ');
++s)
;
if (*s == 'r' || *s == '|') /* found one */
{
del_typebuf((int)(s + 1 -
(typebuf.tb_buf + typebuf.tb_off)), 0);
/* get size and redraw screen */
shell_resized();
continue;
}
if (*s == NUL) /* need more characters */
keylen = KEYLEN_PART_KEY;
}
if (keylen >= 0)
#endif
/* When there was a matching mapping and no
* termcode could be replaced after another one,
* use that mapping (loop around). If there was
* no mapping use the character from the
* typeahead buffer right here. */
if (mp == NULL)
{
/*
* get a character: 2. from the typeahead buffer
*/
c = typebuf.tb_buf[typebuf.tb_off] & 255;
if (advance) /* remove chars from tb_buf */
{
cmd_silent = (typebuf.tb_silent > 0);
if (typebuf.tb_maplen > 0)
KeyTyped = FALSE;
else
{
KeyTyped = TRUE;
/* write char to script file(s) */
gotchars(typebuf.tb_buf
+ typebuf.tb_off, 1);
}
KeyNoremap = typebuf.tb_noremap[
typebuf.tb_off];
del_typebuf(1, 0);
}
break; /* got character, break for loop */
}
}
if (keylen > 0) /* full matching terminal code */
{
#if defined(FEAT_GUI) && defined(FEAT_MENU)
if (typebuf.tb_len >= 2
&& typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
&& typebuf.tb_buf[typebuf.tb_off + 1]
== KS_MENU)
{
/*
* Using a menu may cause a break in undo!
* It's like using gotchars(), but without
* recording or writing to a script file.
*/
may_sync_undo();
del_typebuf(3, 0);
idx = get_menu_index(current_menu, local_State);
if (idx != MENU_INDEX_INVALID)
{
/*
* In Select mode and a Visual mode menu
* is used: Switch to Visual mode
* temporarily. Append K_SELECT to switch
* back to Select mode.
*/
if (VIsual_active && VIsual_select
&& (current_menu->modes & VISUAL))
{
VIsual_select = FALSE;
(void)ins_typebuf(K_SELECT_STRING,
REMAP_NONE, 0, TRUE, FALSE);
}
ins_typebuf(current_menu->strings[idx],
current_menu->noremap[idx],
0, TRUE,
current_menu->silent[idx]);
}
}
#endif /* FEAT_GUI && FEAT_MENU */
continue; /* try mapping again */
}
/* Partial match: get some more characters. When a
* matching mapping was found use that one. */
if (mp == NULL || keylen < 0)
keylen = KEYLEN_PART_KEY;
else
keylen = mp_match_len;
}
/* complete match */
if (keylen >= 0 && keylen <= typebuf.tb_len)
{
#ifdef FEAT_EVAL
int save_m_expr;
int save_m_noremap;
int save_m_silent;
char_u *save_m_keys;
char_u *save_m_str;
#else
# define save_m_noremap mp->m_noremap
# define save_m_silent mp->m_silent
#endif
/* write chars to script file(s) */
if (keylen > typebuf.tb_maplen)
gotchars(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_maplen,
keylen - typebuf.tb_maplen);
cmd_silent = (typebuf.tb_silent > 0);
del_typebuf(keylen, 0); /* remove the mapped keys */
/*
* Put the replacement string in front of mapstr.
* The depth check catches ":map x y" and ":map y x".
*/
if (++mapdepth >= p_mmd)
{
emsg(_("E223: recursive mapping"));
if (State & CMDLINE)
redrawcmdline();
else
setcursor();
flush_buffers(FLUSH_MINIMAL);
mapdepth = 0; /* for next one */
c = -1;
break;
}
/*
* In Select mode and a Visual mode mapping is used:
* Switch to Visual mode temporarily. Append K_SELECT
* to switch back to Select mode.
*/
if (VIsual_active && VIsual_select
&& (mp->m_mode & VISUAL))
{
VIsual_select = FALSE;
(void)ins_typebuf(K_SELECT_STRING, REMAP_NONE,
0, TRUE, FALSE);
}
#ifdef FEAT_EVAL
/* Copy the values from *mp that are used, because
* evaluating the expression may invoke a function
* that redefines the mapping, thereby making *mp
* invalid. */
save_m_expr = mp->m_expr;
save_m_noremap = mp->m_noremap;
save_m_silent = mp->m_silent;
save_m_keys = NULL; /* only saved when needed */
save_m_str = NULL; /* only saved when needed */
/*
* Handle ":map <expr>": evaluate the {rhs} as an
* expression. Also save and restore the command line
* for "normal :".
*/
if (mp->m_expr)
{
int save_vgetc_busy = vgetc_busy;
vgetc_busy = 0;
save_m_keys = vim_strsave(mp->m_keys);
save_m_str = vim_strsave(mp->m_str);
s = eval_map_expr(save_m_str, NUL);
vgetc_busy = save_vgetc_busy;
}
else
#endif
s = mp->m_str;
/*
* Insert the 'to' part in the typebuf.tb_buf.
* If 'from' field is the same as the start of the
* 'to' field, don't remap the first character (but do
* allow abbreviations).
* If m_noremap is set, don't remap the whole 'to'
* part.
*/
if (s == NULL)
i = FAIL;
else
{
int noremap;
if (save_m_noremap != REMAP_YES)
noremap = save_m_noremap;
else if (
#ifdef FEAT_EVAL
STRNCMP(s, save_m_keys != NULL
? save_m_keys : mp->m_keys,
(size_t)keylen)
#else
STRNCMP(s, mp->m_keys, (size_t)keylen)
#endif
!= 0)
noremap = REMAP_YES;
else
noremap = REMAP_SKIP;
i = ins_typebuf(s, noremap,
0, TRUE, cmd_silent || save_m_silent);
#ifdef FEAT_EVAL
if (save_m_expr)
vim_free(s);
#endif
}
#ifdef FEAT_EVAL
vim_free(save_m_keys);
vim_free(save_m_str);
#endif
if (i == FAIL)
{
c = -1;
break;
}
continue;
}
}
/*
* get a character: 3. from the user - handle <Esc> in Insert mode
*/
/*
* Special case: if we get an <ESC> in insert mode and there
* are no more characters at once, we pretend to go out of
* insert mode. This prevents the one second delay after
* typing an <ESC>. If we get something after all, we may
* have to redisplay the mode. That the cursor is in the wrong
* place does not matter.
*/
c = 0;
#ifdef FEAT_CMDL_INFO
new_wcol = curwin->w_wcol;
new_wrow = curwin->w_wrow;
#endif
if ( advance
&& typebuf.tb_len == 1
&& typebuf.tb_buf[typebuf.tb_off] == ESC
&& !no_mapping
&& ex_normal_busy == 0
&& typebuf.tb_maplen == 0
&& (State & INSERT)
&& (p_timeout
|| (keylen == KEYLEN_PART_KEY && p_ttimeout))
&& (c = inchar(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len, 3, 25L)) == 0)
{
colnr_T col = 0, vcol;
char_u *ptr;
if (mode_displayed)
{
unshowmode(TRUE);
mode_deleted = TRUE;
}
#ifdef FEAT_GUI
/* may show a different cursor shape */
if (gui.in_use && State != NORMAL && !cmd_silent)
{
int save_State;
save_State = State;
State = NORMAL;
gui_update_cursor(TRUE, FALSE);
State = save_State;
shape_changed = TRUE;
}
#endif
validate_cursor();
old_wcol = curwin->w_wcol;
old_wrow = curwin->w_wrow;
/* move cursor left, if possible */
if (curwin->w_cursor.col != 0)
{
if (curwin->w_wcol > 0)
{
if (did_ai)
{
/*
* We are expecting to truncate the trailing
* white-space, so find the last non-white
* character -- webb
*/
col = vcol = curwin->w_wcol = 0;
ptr = ml_get_curline();
while (col < curwin->w_cursor.col)
{
if (!VIM_ISWHITE(ptr[col]))
curwin->w_wcol = vcol;
vcol += lbr_chartabsize(ptr, ptr + col,
(colnr_T)vcol);
if (has_mbyte)
col += (*mb_ptr2len)(ptr + col);
else
++col;
}
curwin->w_wrow = curwin->w_cline_row
+ curwin->w_wcol / curwin->w_width;
curwin->w_wcol %= curwin->w_width;
curwin->w_wcol += curwin_col_off();
col = 0; /* no correction needed */
}
else
{
--curwin->w_wcol;
col = curwin->w_cursor.col - 1;
}
}
else if (curwin->w_p_wrap && curwin->w_wrow)
{
--curwin->w_wrow;
curwin->w_wcol = curwin->w_width - 1;
col = curwin->w_cursor.col - 1;
}
if (has_mbyte && col > 0 && curwin->w_wcol > 0)
{
/* Correct when the cursor is on the right halve
* of a double-wide character. */
ptr = ml_get_curline();
col -= (*mb_head_off)(ptr, ptr + col);
if ((*mb_ptr2cells)(ptr + col) > 1)
--curwin->w_wcol;
}
}
setcursor();
out_flush();
#ifdef FEAT_CMDL_INFO
new_wcol = curwin->w_wcol;
new_wrow = curwin->w_wrow;
#endif
curwin->w_wcol = old_wcol;
curwin->w_wrow = old_wrow;
}
if (c < 0)
continue; /* end of input script reached */
/* Allow mapping for just typed characters. When we get here c
* is the number of extra bytes and typebuf.tb_len is 1. */
for (n = 1; n <= c; ++n)
typebuf.tb_noremap[typebuf.tb_off + n] = RM_YES;
typebuf.tb_len += c;
/* buffer full, don't map */
if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN)
{
timedout = TRUE;
continue;
}
if (ex_normal_busy > 0)
{
#ifdef FEAT_CMDWIN
static int tc = 0;
#endif
/* No typeahead left and inside ":normal". Must return
* something to avoid getting stuck. When an incomplete
* mapping is present, behave like it timed out. */
if (typebuf.tb_len > 0)
{
timedout = TRUE;
continue;
}
/* When 'insertmode' is set, ESC just beeps in Insert
* mode. Use CTRL-L to make edit() return.
* For the command line only CTRL-C always breaks it.
* For the cmdline window: Alternate between ESC and
* CTRL-C: ESC for most situations and CTRL-C to close the
* cmdline window. */
if (p_im && (State & INSERT))
c = Ctrl_L;
#ifdef FEAT_TERMINAL
else if (terminal_is_active())
c = K_CANCEL;
#endif
else if ((State & CMDLINE)
#ifdef FEAT_CMDWIN
|| (cmdwin_type > 0 && tc == ESC)
#endif
)
c = Ctrl_C;
else
c = ESC;
#ifdef FEAT_CMDWIN
tc = c;
#endif
break;
}
/*
* get a character: 3. from the user - update display
*/
/* In insert mode a screen update is skipped when characters
* are still available. But when those available characters
* are part of a mapping, and we are going to do a blocking
* wait here. Need to update the screen to display the
* changed text so far. Also for when 'lazyredraw' is set and
* redrawing was postponed because there was something in the
* input buffer (e.g., termresponse). */
if (((State & INSERT) != 0 || p_lz) && (State & CMDLINE) == 0
&& advance && must_redraw != 0 && !need_wait_return)
{
update_screen(0);
setcursor(); /* put cursor back where it belongs */
}
/*
* If we have a partial match (and are going to wait for more
* input from the user), show the partially matched characters
* to the user with showcmd.
*/
#ifdef FEAT_CMDL_INFO
i = 0;
#endif
c1 = 0;
if (typebuf.tb_len > 0 && advance && !exmode_active)
{
if (((State & (NORMAL | INSERT)) || State == LANGMAP)
&& State != HITRETURN)
{
/* this looks nice when typing a dead character map */
if (State & INSERT
&& ptr2cells(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len - 1) == 1)
{
edit_putchar(typebuf.tb_buf[typebuf.tb_off
+ typebuf.tb_len - 1], FALSE);
setcursor(); /* put cursor back where it belongs */
c1 = 1;
}
#ifdef FEAT_CMDL_INFO
/* need to use the col and row from above here */
old_wcol = curwin->w_wcol;
old_wrow = curwin->w_wrow;
curwin->w_wcol = new_wcol;
curwin->w_wrow = new_wrow;
push_showcmd();
if (typebuf.tb_len > SHOWCMD_COLS)
i = typebuf.tb_len - SHOWCMD_COLS;
while (i < typebuf.tb_len)
(void)add_to_showcmd(typebuf.tb_buf[typebuf.tb_off
+ i++]);
curwin->w_wcol = old_wcol;
curwin->w_wrow = old_wrow;
#endif
}
/* this looks nice when typing a dead character map */
if ((State & CMDLINE)
#if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
&& cmdline_star == 0
#endif
&& ptr2cells(typebuf.tb_buf + typebuf.tb_off
+ typebuf.tb_len - 1) == 1)
{
putcmdline(typebuf.tb_buf[typebuf.tb_off
+ typebuf.tb_len - 1], FALSE);
c1 = 1;
}
}
/*
* get a character: 3. from the user - get it
*/
if (typebuf.tb_len == 0)
// timedout may have been set while waiting for a mapping
// that has a <Nop> RHS.
timedout = FALSE;
if (advance)
{
if (typebuf.tb_len == 0
|| !(p_timeout
|| (p_ttimeout && keylen == KEYLEN_PART_KEY)))
// blocking wait
wait_time = -1L;
else if (keylen == KEYLEN_PART_KEY && p_ttm >= 0)
wait_time = p_ttm;
else
wait_time = p_tm;
}
else
wait_time = 0;
wait_tb_len = typebuf.tb_len;
c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len,
typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1,
wait_time);
#ifdef FEAT_CMDL_INFO
if (i != 0)
pop_showcmd();
#endif
if (c1 == 1)
{
if (State & INSERT)
edit_unputchar();
if (State & CMDLINE)
unputcmdline();
else
setcursor(); /* put cursor back where it belongs */
}
if (c < 0)
continue; /* end of input script reached */
if (c == NUL) /* no character available */
{
if (!advance)
break;
if (wait_tb_len > 0) /* timed out */
{
timedout = TRUE;
continue;
}
}
else
{ /* allow mapping for just typed characters */
while (typebuf.tb_buf[typebuf.tb_off
+ typebuf.tb_len] != NUL)
typebuf.tb_noremap[typebuf.tb_off
+ typebuf.tb_len++] = RM_YES;
#ifdef HAVE_INPUT_METHOD
/* Get IM status right after getting keys, not after the
* timeout for a mapping (focus may be lost by then). */
vgetc_im_active = im_get_status();
#endif
}
} /* for (;;) */
} /* if (!character from stuffbuf) */
/* if advance is FALSE don't loop on NULs */
} while ((c < 0 && c != K_CANCEL) || (advance && c == NUL));
/*
* The "INSERT" message is taken care of here:
* if we return an ESC to exit insert mode, the message is deleted
* if we don't return an ESC but deleted the message before, redisplay it
*/
if (advance && p_smd && msg_silent == 0 && (State & INSERT))
{
if (c == ESC && !mode_deleted && !no_mapping && mode_displayed)
{
if (typebuf.tb_len && !KeyTyped)
redraw_cmdline = TRUE; /* delete mode later */
else
unshowmode(FALSE);
}
else if (c != ESC && mode_deleted)
{
if (typebuf.tb_len && !KeyTyped)
redraw_cmdline = TRUE; /* show mode later */
else
showmode();
}
}
#ifdef FEAT_GUI
/* may unshow different cursor shape */
if (gui.in_use && shape_changed)
gui_update_cursor(TRUE, FALSE);
#endif
if (timedout && c == ESC)
{
char_u nop_buf[3];
// When recording there will be no timeout. Add a <Nop> after the ESC
// to avoid that it forms a key code with following characters.
nop_buf[0] = K_SPECIAL;
nop_buf[1] = KS_EXTRA;
nop_buf[2] = KE_NOP;
gotchars(nop_buf, 3);
}
--vgetc_busy;
return c;
}
/*
* inchar() - get one character from
* 1. a scriptfile
* 2. the keyboard
*
* As much characters as we can get (upto 'maxlen') are put in "buf" and
* NUL terminated (buffer length must be 'maxlen' + 1).
* Minimum for "maxlen" is 3!!!!
*
* "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into
* it. When typebuf.tb_change_cnt changes (e.g., when a message is received
* from a remote client) "buf" can no longer be used. "tb_change_cnt" is 0
* otherwise.
*
* If we got an interrupt all input is read until none is available.
*
* If wait_time == 0 there is no waiting for the char.
* If wait_time == n we wait for n msec for a character to arrive.
* If wait_time == -1 we wait forever for a character to arrive.
*
* Return the number of obtained characters.
* Return -1 when end of input script reached.
*/
static int
inchar(
char_u *buf,
int maxlen,
long wait_time) /* milli seconds */
{
int len = 0; /* init for GCC */
int retesc = FALSE; /* return ESC with gotint */
int script_char;
int tb_change_cnt = typebuf.tb_change_cnt;
if (wait_time == -1L || wait_time > 100L) /* flush output before waiting */
{
cursor_on();
out_flush_cursor(FALSE, FALSE);
#if defined(FEAT_GUI) && defined(FEAT_MOUSESHAPE)
if (gui.in_use && postponed_mouseshape)
update_mouseshape(-1);
#endif
}
/*
* Don't reset these when at the hit-return prompt, otherwise a endless
* recursive loop may result (write error in swapfile, hit-return, timeout
* on char wait, flush swapfile, write error....).
*/
if (State != HITRETURN)
{
did_outofmem_msg = FALSE; /* display out of memory message (again) */
did_swapwrite_msg = FALSE; /* display swap file write error again */
}
undo_off = FALSE; /* restart undo now */
/*
* Get a character from a script file if there is one.
* If interrupted: Stop reading script files, close them all.
*/
script_char = -1;
while (scriptin[curscript] != NULL && script_char < 0
#ifdef FEAT_EVAL
&& !ignore_script
#endif
)
{
#ifdef MESSAGE_QUEUE
parse_queued_messages();
#endif
if (got_int || (script_char = getc(scriptin[curscript])) < 0)
{
/* Reached EOF.
* Careful: closescript() frees typebuf.tb_buf[] and buf[] may
* point inside typebuf.tb_buf[]. Don't use buf[] after this! */
closescript();
/*
* When reading script file is interrupted, return an ESC to get
* back to normal mode.
* Otherwise return -1, because typebuf.tb_buf[] has changed.
*/
if (got_int)
retesc = TRUE;
else
return -1;
}
else
{
buf[0] = script_char;
len = 1;
}
}
if (script_char < 0) /* did not get a character from script */
{
/*
* If we got an interrupt, skip all previously typed characters and
* return TRUE if quit reading script file.
* Stop reading typeahead when a single CTRL-C was read,
* fill_input_buf() returns this when not able to read from stdin.
* Don't use buf[] here, closescript() may have freed typebuf.tb_buf[]
* and buf may be pointing inside typebuf.tb_buf[].
*/
if (got_int)
{
#define DUM_LEN MAXMAPLEN * 3 + 3
char_u dum[DUM_LEN + 1];
for (;;)
{
len = ui_inchar(dum, DUM_LEN, 0L, 0);
if (len == 0 || (len == 1 && dum[0] == 3))
break;
}
return retesc;
}
/*
* Always flush the output characters when getting input characters
* from the user and not just peeking.
*/
if (wait_time == -1L || wait_time > 10L)
out_flush();
/*
* Fill up to a third of the buffer, because each character may be
* tripled below.
*/
len = ui_inchar(buf, maxlen / 3, wait_time, tb_change_cnt);
}
/* If the typebuf was changed further down, it is like nothing was added by
* this call. */
if (typebuf_changed(tb_change_cnt))
return 0;
/* Note the change in the typeahead buffer, this matters for when
* vgetorpeek() is called recursively, e.g. using getchar(1) in a timer
* function. */
if (len > 0 && ++typebuf.tb_change_cnt == 0)
typebuf.tb_change_cnt = 1;
return fix_input_buffer(buf, len);
}
/*
* Fix typed characters for use by vgetc() and check_termcode().
* "buf[]" must have room to triple the number of bytes!
* Returns the new length.
*/
int
fix_input_buffer(char_u *buf, int len)
{
int i;
char_u *p = buf;
/*
* Two characters are special: NUL and K_SPECIAL.
* When compiled With the GUI CSI is also special.
* Replace NUL by K_SPECIAL KS_ZERO KE_FILLER
* Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
* Replace CSI by K_SPECIAL KS_EXTRA KE_CSI
*/
for (i = len; --i >= 0; ++p)
{
#ifdef FEAT_GUI
/* When the GUI is used any character can come after a CSI, don't
* escape it. */
if (gui.in_use && p[0] == CSI && i >= 2)
{
p += 2;
i -= 2;
}
# ifndef MSWIN
/* When the GUI is not used CSI needs to be escaped. */
else if (!gui.in_use && p[0] == CSI)
{
mch_memmove(p + 3, p + 1, (size_t)i);
*p++ = K_SPECIAL;
*p++ = KS_EXTRA;
*p = (int)KE_CSI;
len += 2;
}
# endif
else
#endif
if (p[0] == NUL || (p[0] == K_SPECIAL
// timeout may generate K_CURSORHOLD
&& (i < 2 || p[1] != KS_EXTRA || p[2] != (int)KE_CURSORHOLD)
#if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
// Win32 console passes modifiers
&& (
# ifdef VIMDLL
gui.in_use ||
# endif
(i < 2 || p[1] != KS_MODIFIER))
#endif
))
{
mch_memmove(p + 3, p + 1, (size_t)i);
p[2] = K_THIRD(p[0]);
p[1] = K_SECOND(p[0]);
p[0] = K_SPECIAL;
p += 2;
len += 2;
}
}
*p = NUL; // add trailing NUL
return len;
}
#if defined(USE_INPUT_BUF) || defined(PROTO)
/*
* Return TRUE when bytes are in the input buffer or in the typeahead buffer.
* Normally the input buffer would be sufficient, but the server_to_input_buf()
* or feedkeys() may insert characters in the typeahead buffer while we are
* waiting for input to arrive.
*/
int
input_available(void)
{
return (!vim_is_input_buf_empty()
# if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
|| typebuf_was_filled
# endif
);
}
#endif
/*
* map[!] : show all key mappings
* map[!] {lhs} : show key mapping for {lhs}
* map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
* noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
* unmap[!] {lhs} : remove key mapping for {lhs}
* abbr : show all abbreviations
* abbr {lhs} : show abbreviations for {lhs}
* abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
* noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
* unabbr {lhs} : remove abbreviation for {lhs}
*
* maptype: 0 for :map, 1 for :unmap, 2 for noremap.
*
* arg is pointer to any arguments. Note: arg cannot be a read-only string,
* it will be modified.
*
* for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
* for :map! mode is INSERT + CMDLINE
* for :cmap mode is CMDLINE
* for :imap mode is INSERT
* for :lmap mode is LANGMAP
* for :nmap mode is NORMAL
* for :vmap mode is VISUAL + SELECTMODE
* for :xmap mode is VISUAL
* for :smap mode is SELECTMODE
* for :omap mode is OP_PENDING
* for :tmap mode is TERMINAL
*
* for :abbr mode is INSERT + CMDLINE
* for :iabbr mode is INSERT
* for :cabbr mode is CMDLINE
*
* Return 0 for success
* 1 for invalid arguments
* 2 for no match
* 4 for out of mem
* 5 for entry not unique
*/
int
do_map(
int maptype,
char_u *arg,
int mode,
int abbrev) /* not a mapping but an abbreviation */
{
char_u *keys;
mapblock_T *mp, **mpp;
char_u *rhs;
char_u *p;
int n;
int len = 0; /* init for GCC */
char_u *newstr;
int hasarg;
int haskey;
int did_it = FALSE;
#ifdef FEAT_LOCALMAP
int did_local = FALSE;
#endif
int round;
char_u *keys_buf = NULL;
char_u *arg_buf = NULL;
int retval = 0;
int do_backslash;
int hash;
int new_hash;
mapblock_T **abbr_table;
mapblock_T **map_table;
int unique = FALSE;
int nowait = FALSE;
int silent = FALSE;
int special = FALSE;
#ifdef FEAT_EVAL
int expr = FALSE;
#endif
int noremap;
char_u *orig_rhs;
keys = arg;
map_table = maphash;
abbr_table = &first_abbr;
/* For ":noremap" don't remap, otherwise do remap. */
if (maptype == 2)
noremap = REMAP_NONE;
else
noremap = REMAP_YES;
/* Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
* any order. */
for (;;)
{
#ifdef FEAT_LOCALMAP
/*
* Check for "<buffer>": mapping local to buffer.
*/
if (STRNCMP(keys, "<buffer>", 8) == 0)
{
keys = skipwhite(keys + 8);
map_table = curbuf->b_maphash;
abbr_table = &curbuf->b_first_abbr;
continue;
}
#endif
/*
* Check for "<nowait>": don't wait for more characters.
*/
if (STRNCMP(keys, "<nowait>", 8) == 0)
{
keys = skipwhite(keys + 8);
nowait = TRUE;
continue;
}
/*
* Check for "<silent>": don't echo commands.
*/
if (STRNCMP(keys, "<silent>", 8) == 0)
{
keys = skipwhite(keys + 8);
silent = TRUE;
continue;
}
/*
* Check for "<special>": accept special keys in <>
*/
if (STRNCMP(keys, "<special>", 9) == 0)
{
keys = skipwhite(keys + 9);
special = TRUE;
continue;
}
#ifdef FEAT_EVAL
/*
* Check for "<script>": remap script-local mappings only
*/
if (STRNCMP(keys, "<script>", 8) == 0)
{
keys = skipwhite(keys + 8);
noremap = REMAP_SCRIPT;
continue;
}
/*
* Check for "<expr>": {rhs} is an expression.
*/
if (STRNCMP(keys, "<expr>", 6) == 0)
{
keys = skipwhite(keys + 6);
expr = TRUE;
continue;
}
#endif
/*
* Check for "<unique>": don't overwrite an existing mapping.
*/
if (STRNCMP(keys, "<unique>", 8) == 0)
{
keys = skipwhite(keys + 8);
unique = TRUE;
continue;
}
break;
}
validate_maphash();
/*
* Find end of keys and skip CTRL-Vs (and backslashes) in it.
* Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
* with :unmap white space is included in the keys, no argument possible.
*/
p = keys;
do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
while (*p && (maptype == 1 || !VIM_ISWHITE(*p)))
{
if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
p[1] != NUL)
++p; /* skip CTRL-V or backslash */
++p;
}
if (*p != NUL)
*p++ = NUL;
p = skipwhite(p);
rhs = p;
hasarg = (*rhs != NUL);
haskey = (*keys != NUL);
/* check for :unmap without argument */
if (maptype == 1 && !haskey)
{
retval = 1;
goto theend;
}
/*
* If mapping has been given as ^V<C_UP> say, then replace the term codes
* with the appropriate two bytes. If it is a shifted special key, unshift
* it too, giving another two bytes.
* replace_termcodes() may move the result to allocated memory, which
* needs to be freed later (*keys_buf and *arg_buf).
* replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
*/
if (haskey)
keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, special);
orig_rhs = rhs;
if (hasarg)
{
if (STRICMP(rhs, "<nop>") == 0) /* "<Nop>" means nothing */
rhs = (char_u *)"";
else
rhs = replace_termcodes(rhs, &arg_buf, FALSE, TRUE, special);
}
/*
* check arguments and translate function keys
*/
if (haskey)
{
len = (int)STRLEN(keys);
if (len > MAXMAPLEN) /* maximum length of MAXMAPLEN chars */
{
retval = 1;
goto theend;
}
if (abbrev && maptype != 1)
{
/*
* If an abbreviation ends in a keyword character, the
* rest must be all keyword-char or all non-keyword-char.
* Otherwise we won't be able to find the start of it in a
* vi-compatible way.
*/
if (has_mbyte)
{
int first, last;
int same = -1;
first = vim_iswordp(keys);
last = first;
p = keys + (*mb_ptr2len)(keys);
n = 1;
while (p < keys + len)
{
++n; /* nr of (multi-byte) chars */
last = vim_iswordp(p); /* type of last char */
if (same == -1 && last != first)
same = n - 1; /* count of same char type */
p += (*mb_ptr2len)(p);
}
if (last && n > 2 && same >= 0 && same < n - 1)
{
retval = 1;
goto theend;
}
}
else if (vim_iswordc(keys[len - 1])) // ends in keyword char
for (n = 0; n < len - 2; ++n)
if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
{
retval = 1;
goto theend;
}
/* An abbreviation cannot contain white space. */
for (n = 0; n < len; ++n)
if (VIM_ISWHITE(keys[n]))
{
retval = 1;
goto theend;
}
}
}
if (haskey && hasarg && abbrev) /* if we will add an abbreviation */
no_abbr = FALSE; /* reset flag that indicates there are
no abbreviations */
if (!haskey || (maptype != 1 && !hasarg))
msg_start();
#ifdef FEAT_LOCALMAP
/*
* Check if a new local mapping wasn't already defined globally.
*/
if (map_table == curbuf->b_maphash && haskey && hasarg && maptype != 1)
{
/* need to loop over all global hash lists */
for (hash = 0; hash < 256 && !got_int; ++hash)
{
if (abbrev)
{
if (hash != 0) /* there is only one abbreviation list */
break;
mp = first_abbr;
}
else
mp = maphash[hash];
for ( ; mp != NULL && !got_int; mp = mp->m_next)
{
/* check entries with the same mode */
if ((mp->m_mode & mode) != 0
&& mp->m_keylen == len
&& unique
&& STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
{
if (abbrev)
semsg(_("E224: global abbreviation already exists for %s"),
mp->m_keys);
else
semsg(_("E225: global mapping already exists for %s"),
mp->m_keys);
retval = 5;
goto theend;
}
}
}
}
/*
* When listing global mappings, also list buffer-local ones here.
*/
if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
{
/* need to loop over all global hash lists */
for (hash = 0; hash < 256 && !got_int; ++hash)
{
if (abbrev)
{
if (hash != 0) /* there is only one abbreviation list */
break;
mp = curbuf->b_first_abbr;
}
else
mp = curbuf->b_maphash[hash];
for ( ; mp != NULL && !got_int; mp = mp->m_next)
{
/* check entries with the same mode */
if ((mp->m_mode & mode) != 0)
{
if (!haskey) /* show all entries */
{
showmap(mp, TRUE);
did_local = TRUE;
}
else
{
n = mp->m_keylen;
if (STRNCMP(mp->m_keys, keys,
(size_t)(n < len ? n : len)) == 0)
{
showmap(mp, TRUE);
did_local = TRUE;
}
}
}
}
}
}
#endif
/*
* Find an entry in the maphash[] list that matches.
* For :unmap we may loop two times: once to try to unmap an entry with a
* matching 'from' part, a second time, if the first fails, to unmap an
* entry with a matching 'to' part. This was done to allow ":ab foo bar"
* to be unmapped by typing ":unab foo", where "foo" will be replaced by
* "bar" because of the abbreviation.
*/
for (round = 0; (round == 0 || maptype == 1) && round <= 1
&& !did_it && !got_int; ++round)
{
/* need to loop over all hash lists */
for (hash = 0; hash < 256 && !got_int; ++hash)
{
if (abbrev)
{
if (hash > 0) /* there is only one abbreviation list */
break;
mpp = abbr_table;
}
else
mpp = &(map_table[hash]);
for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
{
if (!(mp->m_mode & mode)) /* skip entries with wrong mode */
{
mpp = &(mp->m_next);
continue;
}
if (!haskey) /* show all entries */
{
showmap(mp, map_table != maphash);
did_it = TRUE;
}
else /* do we have a match? */
{
if (round) /* second round: Try unmap "rhs" string */
{
n = (int)STRLEN(mp->m_str);
p = mp->m_str;
}
else
{
n = mp->m_keylen;
p = mp->m_keys;
}
if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
{
if (maptype == 1) /* delete entry */
{
/* Only accept a full match. For abbreviations we
* ignore trailing space when matching with the
* "lhs", since an abbreviation can't have
* trailing space. */
if (n != len && (!abbrev || round || n > len
|| *skipwhite(keys + n) != NUL))
{
mpp = &(mp->m_next);
continue;
}
/*
* We reset the indicated mode bits. If nothing is
* left the entry is deleted below.
*/
mp->m_mode &= ~mode;
did_it = TRUE; /* remember we did something */
}
else if (!hasarg) /* show matching entry */
{
showmap(mp, map_table != maphash);
did_it = TRUE;
}
else if (n != len) /* new entry is ambiguous */
{
mpp = &(mp->m_next);
continue;
}
else if (unique)
{
if (abbrev)
semsg(_("E226: abbreviation already exists for %s"),
p);
else
semsg(_("E227: mapping already exists for %s"), p);
retval = 5;
goto theend;
}
else /* new rhs for existing entry */
{
mp->m_mode &= ~mode; /* remove mode bits */
if (mp->m_mode == 0 && !did_it) /* reuse entry */
{
newstr = vim_strsave(rhs);
if (newstr == NULL)
{
retval = 4; /* no mem */
goto theend;
}
vim_free(mp->m_str);
mp->m_str = newstr;
vim_free(mp->m_orig_str);
mp->m_orig_str = vim_strsave(orig_rhs);
mp->m_noremap = noremap;
mp->m_nowait = nowait;
mp->m_silent = silent;
mp->m_mode = mode;
#ifdef FEAT_EVAL
mp->m_expr = expr;
mp->m_script_ctx = current_sctx;
mp->m_script_ctx.sc_lnum += sourcing_lnum;
#endif
did_it = TRUE;
}
}
if (mp->m_mode == 0) /* entry can be deleted */
{
map_free(mpp);
continue; /* continue with *mpp */
}
/*
* May need to put this entry into another hash list.
*/
new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
if (!abbrev && new_hash != hash)
{
*mpp = mp->m_next;
mp->m_next = map_table[new_hash];
map_table[new_hash] = mp;
continue; /* continue with *mpp */
}
}
}
mpp = &(mp->m_next);
}
}
}
if (maptype == 1) /* delete entry */
{
if (!did_it)
retval = 2; /* no match */
else if (*keys == Ctrl_C)
{
/* If CTRL-C has been unmapped, reuse it for Interrupting. */
#ifdef FEAT_LOCALMAP
if (map_table == curbuf->b_maphash)
curbuf->b_mapped_ctrl_c &= ~mode;
else
#endif
mapped_ctrl_c &= ~mode;
}
goto theend;
}
if (!haskey || !hasarg) /* print entries */
{
if (!did_it
#ifdef FEAT_LOCALMAP
&& !did_local
#endif
)
{
if (abbrev)
msg(_("No abbreviation found"));
else
msg(_("No mapping found"));
}
goto theend; /* listing finished */
}
if (did_it) /* have added the new entry already */
goto theend;
/*
* Get here when adding a new entry to the maphash[] list or abbrlist.
*/
mp = (mapblock_T *)alloc((unsigned)sizeof(mapblock_T));
if (mp == NULL)
{
retval = 4; /* no mem */
goto theend;
}
/* If CTRL-C has been mapped, don't always use it for Interrupting. */
if (*keys == Ctrl_C)
{
#ifdef FEAT_LOCALMAP
if (map_table == curbuf->b_maphash)
curbuf->b_mapped_ctrl_c |= mode;
else
#endif
mapped_ctrl_c |= mode;
}
mp->m_keys = vim_strsave(keys);
mp->m_str = vim_strsave(rhs);
mp->m_orig_str = vim_strsave(orig_rhs);
if (mp->m_keys == NULL || mp->m_str == NULL)
{
vim_free(mp->m_keys);
vim_free(mp->m_str);
vim_free(mp->m_orig_str);
vim_free(mp);
retval = 4; /* no mem */
goto theend;
}
mp->m_keylen = (int)STRLEN(mp->m_keys);
mp->m_noremap = noremap;
mp->m_nowait = nowait;
mp->m_silent = silent;
mp->m_mode = mode;
#ifdef FEAT_EVAL
mp->m_expr = expr;
mp->m_script_ctx = current_sctx;
mp->m_script_ctx.sc_lnum += sourcing_lnum;
#endif
/* add the new entry in front of the abbrlist or maphash[] list */
if (abbrev)
{
mp->m_next = *abbr_table;
*abbr_table = mp;
}
else
{
n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
mp->m_next = map_table[n];
map_table[n] = mp;
}
theend:
vim_free(keys_buf);
vim_free(arg_buf);
return retval;
}
/*
* Delete one entry from the abbrlist or maphash[].
* "mpp" is a pointer to the m_next field of the PREVIOUS entry!
*/
static void
map_free(mapblock_T **mpp)
{
mapblock_T *mp;
mp = *mpp;
vim_free(mp->m_keys);
vim_free(mp->m_str);
vim_free(mp->m_orig_str);
*mpp = mp->m_next;
vim_free(mp);
}
/*
* Initialize maphash[] for first use.
*/
static void
validate_maphash(void)
{
if (!maphash_valid)
{
vim_memset(maphash, 0, sizeof(maphash));
maphash_valid = TRUE;
}
}
/*
* Get the mapping mode from the command name.
*/
int
get_map_mode(char_u **cmdp, int forceit)
{
char_u *p;
int modec;
int mode;
p = *cmdp;
modec = *p++;
if (modec == 'i')
mode = INSERT; /* :imap */
else if (modec == 'l')
mode = LANGMAP; /* :lmap */
else if (modec == 'c')
mode = CMDLINE; /* :cmap */
else if (modec == 'n' && *p != 'o') /* avoid :noremap */
mode = NORMAL; /* :nmap */
else if (modec == 'v')
mode = VISUAL + SELECTMODE; /* :vmap */
else if (modec == 'x')
mode = VISUAL; /* :xmap */
else if (modec == 's')
mode = SELECTMODE; /* :smap */
else if (modec == 'o')
mode = OP_PENDING; /* :omap */
else if (modec == 't')
mode = TERMINAL; /* :tmap */
else
{
--p;
if (forceit)
mode = INSERT + CMDLINE; /* :map ! */
else
mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;/* :map */
}
*cmdp = p;
return mode;
}
/*
* Clear all mappings or abbreviations.
* 'abbr' should be FALSE for mappings, TRUE for abbreviations.
*/
void
map_clear(
char_u *cmdp,
char_u *arg UNUSED,
int forceit,
int abbr)
{
int mode;
#ifdef FEAT_LOCALMAP
int local;
local = (STRCMP(arg, "<buffer>") == 0);
if (!local && *arg != NUL)
{
emsg(_(e_invarg));
return;
}
#endif
mode = get_map_mode(&cmdp, forceit);
map_clear_int(curbuf, mode,
#ifdef FEAT_LOCALMAP
local,
#else
FALSE,
#endif
abbr);
}
/*
* Clear all mappings in "mode".
*/
void
map_clear_int(
buf_T *buf UNUSED, /* buffer for local mappings */
int mode, /* mode in which to delete */
int local UNUSED, /* TRUE for buffer-local mappings */
int abbr) /* TRUE for abbreviations */
{
mapblock_T *mp, **mpp;
int hash;
int new_hash;
validate_maphash();
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one abbrlist */
break;
#ifdef FEAT_LOCALMAP
if (local)
mpp = &buf->b_first_abbr;
else
#endif
mpp = &first_abbr;
}
else
{
#ifdef FEAT_LOCALMAP
if (local)
mpp = &buf->b_maphash[hash];
else
#endif
mpp = &maphash[hash];
}
while (*mpp != NULL)
{
mp = *mpp;
if (mp->m_mode & mode)
{
mp->m_mode &= ~mode;
if (mp->m_mode == 0) /* entry can be deleted */
{
map_free(mpp);
continue;
}
/*
* May need to put this entry into another hash list.
*/
new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
if (!abbr && new_hash != hash)
{
*mpp = mp->m_next;
#ifdef FEAT_LOCALMAP
if (local)
{
mp->m_next = buf->b_maphash[new_hash];
buf->b_maphash[new_hash] = mp;
}
else
#endif
{
mp->m_next = maphash[new_hash];
maphash[new_hash] = mp;
}
continue; /* continue with *mpp */
}
}
mpp = &(mp->m_next);
}
}
}
/*
* Return characters to represent the map mode in an allocated string.
* Returns NULL when out of memory.
*/
char_u *
map_mode_to_chars(int mode)
{
garray_T mapmode;
ga_init2(&mapmode, 1, 7);
if ((mode & (INSERT + CMDLINE)) == INSERT + CMDLINE)
ga_append(&mapmode, '!'); /* :map! */
else if (mode & INSERT)
ga_append(&mapmode, 'i'); /* :imap */
else if (mode & LANGMAP)
ga_append(&mapmode, 'l'); /* :lmap */
else if (mode & CMDLINE)
ga_append(&mapmode, 'c'); /* :cmap */
else if ((mode & (NORMAL + VISUAL + SELECTMODE + OP_PENDING))
== NORMAL + VISUAL + SELECTMODE + OP_PENDING)
ga_append(&mapmode, ' '); /* :map */
else
{
if (mode & NORMAL)
ga_append(&mapmode, 'n'); /* :nmap */
if (mode & OP_PENDING)
ga_append(&mapmode, 'o'); /* :omap */
if ((mode & (VISUAL + SELECTMODE)) == VISUAL + SELECTMODE)
ga_append(&mapmode, 'v'); /* :vmap */
else
{
if (mode & VISUAL)
ga_append(&mapmode, 'x'); /* :xmap */
if (mode & SELECTMODE)
ga_append(&mapmode, 's'); /* :smap */
}
}
ga_append(&mapmode, NUL);
return (char_u *)mapmode.ga_data;
}
static void
showmap(
mapblock_T *mp,
int local) /* TRUE for buffer-local map */
{
int len = 1;
char_u *mapchars;
if (message_filtered(mp->m_keys) && message_filtered(mp->m_str))
return;
if (msg_didout || msg_silent != 0)
{
msg_putchar('\n');
if (got_int) /* 'q' typed at MORE prompt */
return;
}
mapchars = map_mode_to_chars(mp->m_mode);
if (mapchars != NULL)
{
msg_puts((char *)mapchars);
len = (int)STRLEN(mapchars);
vim_free(mapchars);
}
while (++len <= 3)
msg_putchar(' ');
/* Display the LHS. Get length of what we write. */
len = msg_outtrans_special(mp->m_keys, TRUE, 0);
do
{
msg_putchar(' '); /* padd with blanks */
++len;
} while (len < 12);
if (mp->m_noremap == REMAP_NONE)
msg_puts_attr("*", HL_ATTR(HLF_8));
else if (mp->m_noremap == REMAP_SCRIPT)
msg_puts_attr("&", HL_ATTR(HLF_8));
else
msg_putchar(' ');
if (local)
msg_putchar('@');
else
msg_putchar(' ');
/* Use FALSE below if we only want things like <Up> to show up as such on
* the rhs, and not M-x etc, TRUE gets both -- webb */
if (*mp->m_str == NUL)
msg_puts_attr("<Nop>", HL_ATTR(HLF_8));
else
{
/* Remove escaping of CSI, because "m_str" is in a format to be used
* as typeahead. */
char_u *s = vim_strsave(mp->m_str);
if (s != NULL)
{
vim_unescape_csi(s);
msg_outtrans_special(s, FALSE, 0);
vim_free(s);
}
}
#ifdef FEAT_EVAL
if (p_verbose > 0)
last_set_msg(mp->m_script_ctx);
#endif
out_flush(); /* show one line at a time */
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
* Recognize termcap codes in "str".
* Also checks mappings local to the current buffer.
*/
int
map_to_exists(char_u *str, char_u *modechars, int abbr)
{
int mode = 0;
char_u *rhs;
char_u *buf;
int retval;
rhs = replace_termcodes(str, &buf, FALSE, TRUE, FALSE);
if (vim_strchr(modechars, 'n') != NULL)
mode |= NORMAL;
if (vim_strchr(modechars, 'v') != NULL)
mode |= VISUAL + SELECTMODE;
if (vim_strchr(modechars, 'x') != NULL)
mode |= VISUAL;
if (vim_strchr(modechars, 's') != NULL)
mode |= SELECTMODE;
if (vim_strchr(modechars, 'o') != NULL)
mode |= OP_PENDING;
if (vim_strchr(modechars, 'i') != NULL)
mode |= INSERT;
if (vim_strchr(modechars, 'l') != NULL)
mode |= LANGMAP;
if (vim_strchr(modechars, 'c') != NULL)
mode |= CMDLINE;
retval = map_to_exists_mode(rhs, mode, abbr);
vim_free(buf);
return retval;
}
#endif
/*
* Return TRUE if a map exists that has "str" in the rhs for mode "mode".
* Also checks mappings local to the current buffer.
*/
int
map_to_exists_mode(char_u *rhs, int mode, int abbr)
{
mapblock_T *mp;
int hash;
# ifdef FEAT_LOCALMAP
int exp_buffer = FALSE;
validate_maphash();
/* Do it twice: once for global maps and once for local maps. */
for (;;)
{
# endif
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one abbr list */
break;
#ifdef FEAT_LOCALMAP
if (exp_buffer)
mp = curbuf->b_first_abbr;
else
#endif
mp = first_abbr;
}
# ifdef FEAT_LOCALMAP
else if (exp_buffer)
mp = curbuf->b_maphash[hash];
# endif
else
mp = maphash[hash];
for (; mp; mp = mp->m_next)
{
if ((mp->m_mode & mode)
&& strstr((char *)mp->m_str, (char *)rhs) != NULL)
return TRUE;
}
}
# ifdef FEAT_LOCALMAP
if (exp_buffer)
break;
exp_buffer = TRUE;
}
# endif
return FALSE;
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Used below when expanding mapping/abbreviation names.
*/
static int expand_mapmodes = 0;
static int expand_isabbrev = 0;
#ifdef FEAT_LOCALMAP
static int expand_buffer = FALSE;
#endif
/*
* Work out what to complete when doing command line completion of mapping
* or abbreviation names.
*/
char_u *
set_context_in_map_cmd(
expand_T *xp,
char_u *cmd,
char_u *arg,
int forceit, /* TRUE if '!' given */
int isabbrev, /* TRUE if abbreviation */
int isunmap, /* TRUE if unmap/unabbrev command */
cmdidx_T cmdidx)
{
if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
xp->xp_context = EXPAND_NOTHING;
else
{
if (isunmap)
expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
else
{
expand_mapmodes = INSERT + CMDLINE;
if (!isabbrev)
expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
}
expand_isabbrev = isabbrev;
xp->xp_context = EXPAND_MAPPINGS;
#ifdef FEAT_LOCALMAP
expand_buffer = FALSE;
#endif
for (;;)
{
#ifdef FEAT_LOCALMAP
if (STRNCMP(arg, "<buffer>", 8) == 0)
{
expand_buffer = TRUE;
arg = skipwhite(arg + 8);
continue;
}
#endif
if (STRNCMP(arg, "<unique>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<nowait>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<silent>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<special>", 9) == 0)
{
arg = skipwhite(arg + 9);
continue;
}
#ifdef FEAT_EVAL
if (STRNCMP(arg, "<script>", 8) == 0)
{
arg = skipwhite(arg + 8);
continue;
}
if (STRNCMP(arg, "<expr>", 6) == 0)
{
arg = skipwhite(arg + 6);
continue;
}
#endif
break;
}
xp->xp_pattern = arg;
}
return NULL;
}
/*
* Find all mapping/abbreviation names that match regexp "regmatch"'.
* For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
* Return OK if matches found, FAIL otherwise.
*/
int
ExpandMappings(
regmatch_T *regmatch,
int *num_file,
char_u ***file)
{
mapblock_T *mp;
int hash;
int count;
int round;
char_u *p;
int i;
validate_maphash();
*num_file = 0; /* return values in case of FAIL */
*file = NULL;
/*
* round == 1: Count the matches.
* round == 2: Build the array to keep the matches.
*/
for (round = 1; round <= 2; ++round)
{
count = 0;
for (i = 0; i < 7; ++i)
{
if (i == 0)
p = (char_u *)"<silent>";
else if (i == 1)
p = (char_u *)"<unique>";
#ifdef FEAT_EVAL
else if (i == 2)
p = (char_u *)"<script>";
else if (i == 3)
p = (char_u *)"<expr>";
#endif
#ifdef FEAT_LOCALMAP
else if (i == 4 && !expand_buffer)
p = (char_u *)"<buffer>";
#endif
else if (i == 5)
p = (char_u *)"<nowait>";
else if (i == 6)
p = (char_u *)"<special>";
else
continue;
if (vim_regexec(regmatch, p, (colnr_T)0))
{
if (round == 1)
++count;
else
(*file)[count++] = vim_strsave(p);
}
}
for (hash = 0; hash < 256; ++hash)
{
if (expand_isabbrev)
{
if (hash > 0) /* only one abbrev list */
break; /* for (hash) */
mp = first_abbr;
}
#ifdef FEAT_LOCALMAP
else if (expand_buffer)
mp = curbuf->b_maphash[hash];
#endif
else
mp = maphash[hash];
for (; mp; mp = mp->m_next)
{
if (mp->m_mode & expand_mapmodes)
{
p = translate_mapping(mp->m_keys);
if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
{
if (round == 1)
++count;
else
{
(*file)[count++] = p;
p = NULL;
}
}
vim_free(p);
}
} /* for (mp) */
} /* for (hash) */
if (count == 0) /* no match found */
break; /* for (round) */
if (round == 1)
{
*file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
if (*file == NULL)
return FAIL;
}
} /* for (round) */
if (count > 1)
{
char_u **ptr1;
char_u **ptr2;
char_u **ptr3;
/* Sort the matches */
sort_strings(*file, count);
/* Remove multiple entries */
ptr1 = *file;
ptr2 = ptr1 + 1;
ptr3 = ptr1 + count;
while (ptr2 < ptr3)
{
if (STRCMP(*ptr1, *ptr2))
*++ptr1 = *ptr2++;
else
{
vim_free(*ptr2++);
count--;
}
}
}
*num_file = count;
return (count == 0 ? FAIL : OK);
}
#endif /* FEAT_CMDL_COMPL */
/*
* Check for an abbreviation.
* Cursor is at ptr[col].
* When inserting, mincol is where insert started.
* For the command line, mincol is what is to be skipped over.
* "c" is the character typed before check_abbr was called. It may have
* ABBR_OFF added to avoid prepending a CTRL-V to it.
*
* Historic vi practice: The last character of an abbreviation must be an id
* character ([a-zA-Z0-9_]). The characters in front of it must be all id
* characters or all non-id characters. This allows for abbr. "#i" to
* "#include".
*
* Vim addition: Allow for abbreviations that end in a non-keyword character.
* Then there must be white space before the abbr.
*
* return TRUE if there is an abbreviation, FALSE if not
*/
int
check_abbr(
int c,
char_u *ptr,
int col,
int mincol)
{
int len;
int scol; /* starting column of the abbr. */
int j;
char_u *s;
char_u tb[MB_MAXBYTES + 4];
mapblock_T *mp;
#ifdef FEAT_LOCALMAP
mapblock_T *mp2;
#endif
int clen = 0; /* length in characters */
int is_id = TRUE;
int vim_abbr;
if (typebuf.tb_no_abbr_cnt) /* abbrev. are not recursive */
return FALSE;
/* no remapping implies no abbreviation, except for CTRL-] */
if ((KeyNoremap & (RM_NONE|RM_SCRIPT)) != 0 && c != Ctrl_RSB)
return FALSE;
/*
* Check for word before the cursor: If it ends in a keyword char all
* chars before it must be keyword chars or non-keyword chars, but not
* white space. If it ends in a non-keyword char we accept any characters
* before it except white space.
*/
if (col == 0) /* cannot be an abbr. */
return FALSE;
if (has_mbyte)
{
char_u *p;
p = mb_prevptr(ptr, ptr + col);
if (!vim_iswordp(p))
vim_abbr = TRUE; /* Vim added abbr. */
else
{
vim_abbr = FALSE; /* vi compatible abbr. */
if (p > ptr)
is_id = vim_iswordp(mb_prevptr(ptr, p));
}
clen = 1;
while (p > ptr + mincol)
{
p = mb_prevptr(ptr, p);
if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
{
p += (*mb_ptr2len)(p);
break;
}
++clen;
}
scol = (int)(p - ptr);
}
else
{
if (!vim_iswordc(ptr[col - 1]))
vim_abbr = TRUE; /* Vim added abbr. */
else
{
vim_abbr = FALSE; /* vi compatible abbr. */
if (col > 1)
is_id = vim_iswordc(ptr[col - 2]);
}
for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
&& (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
;
}
if (scol < mincol)
scol = mincol;
if (scol < col) /* there is a word in front of the cursor */
{
ptr += scol;
len = col - scol;
#ifdef FEAT_LOCALMAP
mp = curbuf->b_first_abbr;
mp2 = first_abbr;
if (mp == NULL)
{
mp = mp2;
mp2 = NULL;
}
#else
mp = first_abbr;
#endif
for ( ; mp;
#ifdef FEAT_LOCALMAP
mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
#endif
(mp = mp->m_next))
{
int qlen = mp->m_keylen;
char_u *q = mp->m_keys;
int match;
if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
{
char_u *qe = vim_strsave(mp->m_keys);
/* might have CSI escaped mp->m_keys */
if (qe != NULL)
{
q = qe;
vim_unescape_csi(q);
qlen = (int)STRLEN(q);
}
}
/* find entries with right mode and keys */
match = (mp->m_mode & State)
&& qlen == len
&& !STRNCMP(q, ptr, (size_t)len);
if (q != mp->m_keys)
vim_free(q);
if (match)
break;
}
if (mp != NULL)
{
/*
* Found a match:
* Insert the rest of the abbreviation in typebuf.tb_buf[].
* This goes from end to start.
*
* Characters 0x000 - 0x100: normal chars, may need CTRL-V,
* except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
* Characters where IS_SPECIAL() == TRUE: key codes, need
* K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
*
* Character CTRL-] is treated specially - it completes the
* abbreviation, but is not inserted into the input stream.
*/
j = 0;
if (c != Ctrl_RSB)
{
/* special key code, split up */
if (IS_SPECIAL(c) || c == K_SPECIAL)
{
tb[j++] = K_SPECIAL;
tb[j++] = K_SECOND(c);
tb[j++] = K_THIRD(c);
}
else
{
if (c < ABBR_OFF && (c < ' ' || c > '~'))
tb[j++] = Ctrl_V; /* special char needs CTRL-V */
if (has_mbyte)
{
/* if ABBR_OFF has been added, remove it here */
if (c >= ABBR_OFF)
c -= ABBR_OFF;
j += (*mb_char2bytes)(c, tb + j);
}
else
tb[j++] = c;
}
tb[j] = NUL;
/* insert the last typed char */
(void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
}
#ifdef FEAT_EVAL
if (mp->m_expr)
s = eval_map_expr(mp->m_str, c);
else
#endif
s = mp->m_str;
if (s != NULL)
{
/* insert the to string */
(void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent);
/* no abbrev. for these chars */
typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
#ifdef FEAT_EVAL
if (mp->m_expr)
vim_free(s);
#endif
}
tb[0] = Ctrl_H;
tb[1] = NUL;
if (has_mbyte)
len = clen; /* Delete characters instead of bytes */
while (len-- > 0) /* delete the from string */
(void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
return TRUE;
}
}
return FALSE;
}
#ifdef FEAT_EVAL
/*
* Evaluate the RHS of a mapping or abbreviations and take care of escaping
* special characters.
*/
static char_u *
eval_map_expr(
char_u *str,
int c) /* NUL or typed character for abbreviation */
{
char_u *res;
char_u *p;
char_u *expr;
pos_T save_cursor;
int save_msg_col;
int save_msg_row;
/* Remove escaping of CSI, because "str" is in a format to be used as
* typeahead. */
expr = vim_strsave(str);
if (expr == NULL)
return NULL;
vim_unescape_csi(expr);
/* Forbid changing text or using ":normal" to avoid most of the bad side
* effects. Also restore the cursor position. */
++textlock;
++ex_normal_lock;
set_vim_var_char(c); /* set v:char to the typed character */
save_cursor = curwin->w_cursor;
save_msg_col = msg_col;
save_msg_row = msg_row;
p = eval_to_string(expr, NULL, FALSE);
--textlock;
--ex_normal_lock;
curwin->w_cursor = save_cursor;
msg_col = save_msg_col;
msg_row = save_msg_row;
vim_free(expr);
if (p == NULL)
return NULL;
/* Escape CSI in the result to be able to use the string as typeahead. */
res = vim_strsave_escape_csi(p);
vim_free(p);
return res;
}
#endif
/*
* Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
* can be put in the typeahead buffer.
* Returns NULL when out of memory.
*/
char_u *
vim_strsave_escape_csi(
char_u *p)
{
char_u *res;
char_u *s, *d;
/* Need a buffer to hold up to three times as much. Four in case of an
* illegal utf-8 byte:
* 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER */
res = alloc((unsigned)(STRLEN(p) * 4) + 1);
if (res != NULL)
{
d = res;
for (s = p; *s != NUL; )
{
if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
{
/* Copy special key unmodified. */
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
}
else
{
/* Add character, possibly multi-byte to destination, escaping
* CSI and K_SPECIAL. Be careful, it can be an illegal byte! */
d = add_char2buf(PTR2CHAR(s), d);
s += MB_CPTR2LEN(s);
}
}
*d = NUL;
}
return res;
}
/*
* Remove escaping from CSI and K_SPECIAL characters. Reverse of
* vim_strsave_escape_csi(). Works in-place.
*/
void
vim_unescape_csi(char_u *p)
{
char_u *s = p, *d = p;
while (*s != NUL)
{
if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
{
*d++ = K_SPECIAL;
s += 3;
}
else if ((s[0] == K_SPECIAL || s[0] == CSI)
&& s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
{
*d++ = CSI;
s += 3;
}
else
*d++ = *s++;
}
*d = NUL;
}
/*
* Write map commands for the current mappings to an .exrc file.
* Return FAIL on error, OK otherwise.
*/
int
makemap(
FILE *fd,
buf_T *buf) /* buffer for local mappings or NULL */
{
mapblock_T *mp;
char_u c1, c2, c3;
char_u *p;
char *cmd;
int abbr;
int hash;
int did_cpo = FALSE;
int i;
validate_maphash();
/*
* Do the loop twice: Once for mappings, once for abbreviations.
* Then loop over all map hash lists.
*/
for (abbr = 0; abbr < 2; ++abbr)
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one abbr list */
break;
#ifdef FEAT_LOCALMAP
if (buf != NULL)
mp = buf->b_first_abbr;
else
#endif
mp = first_abbr;
}
else
{
#ifdef FEAT_LOCALMAP
if (buf != NULL)
mp = buf->b_maphash[hash];
else
#endif
mp = maphash[hash];
}
for ( ; mp; mp = mp->m_next)
{
/* skip script-local mappings */
if (mp->m_noremap == REMAP_SCRIPT)
continue;
/* skip mappings that contain a <SNR> (script-local thing),
* they probably don't work when loaded again */
for (p = mp->m_str; *p != NUL; ++p)
if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
&& p[2] == (int)KE_SNR)
break;
if (*p != NUL)
continue;
/* It's possible to create a mapping and then ":unmap" certain
* modes. We recreate this here by mapping the individual
* modes, which requires up to three of them. */
c1 = NUL;
c2 = NUL;
c3 = NUL;
if (abbr)
cmd = "abbr";
else
cmd = "map";
switch (mp->m_mode)
{
case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
break;
case NORMAL:
c1 = 'n';
break;
case VISUAL:
c1 = 'x';
break;
case SELECTMODE:
c1 = 's';
break;
case OP_PENDING:
c1 = 'o';
break;
case NORMAL + VISUAL:
c1 = 'n';
c2 = 'x';
break;
case NORMAL + SELECTMODE:
c1 = 'n';
c2 = 's';
break;
case NORMAL + OP_PENDING:
c1 = 'n';
c2 = 'o';
break;
case VISUAL + SELECTMODE:
c1 = 'v';
break;
case VISUAL + OP_PENDING:
c1 = 'x';
c2 = 'o';
break;
case SELECTMODE + OP_PENDING:
c1 = 's';
c2 = 'o';
break;
case NORMAL + VISUAL + SELECTMODE:
c1 = 'n';
c2 = 'v';
break;
case NORMAL + VISUAL + OP_PENDING:
c1 = 'n';
c2 = 'x';
c3 = 'o';
break;
case NORMAL + SELECTMODE + OP_PENDING:
c1 = 'n';
c2 = 's';
c3 = 'o';
break;
case VISUAL + SELECTMODE + OP_PENDING:
c1 = 'v';
c2 = 'o';
break;
case CMDLINE + INSERT:
if (!abbr)
cmd = "map!";
break;
case CMDLINE:
c1 = 'c';
break;
case INSERT:
c1 = 'i';
break;
case LANGMAP:
c1 = 'l';
break;
case TERMINAL:
c1 = 't';
break;
default:
iemsg(_("E228: makemap: Illegal mode"));
return FAIL;
}
do /* do this twice if c2 is set, 3 times with c3 */
{
/* When outputting <> form, need to make sure that 'cpo'
* is set to the Vim default. */
if (!did_cpo)
{
if (*mp->m_str == NUL) /* will use <Nop> */
did_cpo = TRUE;
else
for (i = 0; i < 2; ++i)
for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
if (*p == K_SPECIAL || *p == NL)
did_cpo = TRUE;
if (did_cpo)
{
if (fprintf(fd, "let s:cpo_save=&cpo") < 0
|| put_eol(fd) < 0
|| fprintf(fd, "set cpo&vim") < 0
|| put_eol(fd) < 0)
return FAIL;
}
}
if (c1 && putc(c1, fd) < 0)
return FAIL;
if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
return FAIL;
if (fputs(cmd, fd) < 0)
return FAIL;
if (buf != NULL && fputs(" <buffer>", fd) < 0)
return FAIL;
if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
return FAIL;
if (mp->m_silent && fputs(" <silent>", fd) < 0)
return FAIL;
#ifdef FEAT_EVAL
if (mp->m_noremap == REMAP_SCRIPT
&& fputs("<script>", fd) < 0)
return FAIL;
if (mp->m_expr && fputs(" <expr>", fd) < 0)
return FAIL;
#endif
if ( putc(' ', fd) < 0
|| put_escstr(fd, mp->m_keys, 0) == FAIL
|| putc(' ', fd) < 0
|| put_escstr(fd, mp->m_str, 1) == FAIL
|| put_eol(fd) < 0)
return FAIL;
c1 = c2;
c2 = c3;
c3 = NUL;
} while (c1 != NUL);
}
}
if (did_cpo)
if (fprintf(fd, "let &cpo=s:cpo_save") < 0
|| put_eol(fd) < 0
|| fprintf(fd, "unlet s:cpo_save") < 0
|| put_eol(fd) < 0)
return FAIL;
return OK;
}
/*
* write escape string to file
* "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
*
* return FAIL for failure, OK otherwise
*/
int
put_escstr(FILE *fd, char_u *strstart, int what)
{
char_u *str = strstart;
int c;
int modifiers;
/* :map xx <Nop> */
if (*str == NUL && what == 1)
{
if (fprintf(fd, "<Nop>") < 0)
return FAIL;
return OK;
}
for ( ; *str != NUL; ++str)
{
char_u *p;
/* Check for a multi-byte character, which may contain escaped
* K_SPECIAL and CSI bytes */
p = mb_unescape(&str);
if (p != NULL)
{
while (*p != NUL)
if (fputc(*p++, fd) < 0)
return FAIL;
--str;
continue;
}
c = *str;
/*
* Special key codes have to be translated to be able to make sense
* when they are read back.
*/
if (c == K_SPECIAL && what != 2)
{
modifiers = 0x0;
if (str[1] == KS_MODIFIER)
{
modifiers = str[2];
str += 3;
c = *str;
}
if (c == K_SPECIAL)
{
c = TO_SPECIAL(str[1], str[2]);
str += 2;
}
if (IS_SPECIAL(c) || modifiers) /* special key */
{
if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
return FAIL;
continue;
}
}
/*
* A '\n' in a map command should be written as <NL>.
* A '\n' in a set command should be written as \^V^J.
*/
if (c == NL)
{
if (what == 2)
{
if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
return FAIL;
}
else
{
if (fprintf(fd, "<NL>") < 0)
return FAIL;
}
continue;
}
/*
* Some characters have to be escaped with CTRL-V to
* prevent them from misinterpreted in DoOneCmd().
* A space, Tab and '"' has to be escaped with a backslash to
* prevent it to be misinterpreted in do_set().
* A space has to be escaped with a CTRL-V when it's at the start of a
* ":map" rhs.
* A '<' has to be escaped with a CTRL-V to prevent it being
* interpreted as the start of a special key name.
* A space in the lhs of a :map needs a CTRL-V.
*/
if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
{
if (putc('\\', fd) < 0)
return FAIL;
}
else if (c < ' ' || c > '~' || c == '|'
|| (what == 0 && c == ' ')
|| (what == 1 && str == strstart && c == ' ')
|| (what != 2 && c == '<'))
{
if (putc(Ctrl_V, fd) < 0)
return FAIL;
}
if (putc(c, fd) < 0)
return FAIL;
}
return OK;
}
/*
* Check all mappings for the presence of special key codes.
* Used after ":set term=xxx".
*/
void
check_map_keycodes(void)
{
mapblock_T *mp;
char_u *p;
int i;
char_u buf[3];
char_u *save_name;
int abbr;
int hash;
#ifdef FEAT_LOCALMAP
buf_T *bp;
#endif
validate_maphash();
save_name = sourcing_name;
sourcing_name = (char_u *)"mappings"; /* avoids giving error messages */
#ifdef FEAT_LOCALMAP
/* This this once for each buffer, and then once for global
* mappings/abbreviations with bp == NULL */
for (bp = firstbuf; ; bp = bp->b_next)
{
#endif
/*
* Do the loop twice: Once for mappings, once for abbreviations.
* Then loop over all map hash lists.
*/
for (abbr = 0; abbr <= 1; ++abbr)
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash) /* there is only one abbr list */
break;
#ifdef FEAT_LOCALMAP
if (bp != NULL)
mp = bp->b_first_abbr;
else
#endif
mp = first_abbr;
}
else
{
#ifdef FEAT_LOCALMAP
if (bp != NULL)
mp = bp->b_maphash[hash];
else
#endif
mp = maphash[hash];
}
for ( ; mp != NULL; mp = mp->m_next)
{
for (i = 0; i <= 1; ++i) /* do this twice */
{
if (i == 0)
p = mp->m_keys; /* once for the "from" part */
else
p = mp->m_str; /* and once for the "to" part */
while (*p)
{
if (*p == K_SPECIAL)
{
++p;
if (*p < 128) /* for "normal" tcap entries */
{
buf[0] = p[0];
buf[1] = p[1];
buf[2] = NUL;
(void)add_termcap_entry(buf, FALSE);
}
++p;
}
++p;
}
}
}
}
#ifdef FEAT_LOCALMAP
if (bp == NULL)
break;
}
#endif
sourcing_name = save_name;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Check the string "keys" against the lhs of all mappings.
* Return pointer to rhs of mapping (mapblock->m_str).
* NULL when no mapping found.
*/
char_u *
check_map(
char_u *keys,
int mode,
int exact, /* require exact match */
int ign_mod, /* ignore preceding modifier */
int abbr, /* do abbreviations */
mapblock_T **mp_ptr, /* return: pointer to mapblock or NULL */
int *local_ptr) /* return: buffer-local mapping or NULL */
{
int hash;
int len, minlen;
mapblock_T *mp;
char_u *s;
#ifdef FEAT_LOCALMAP
int local;
#endif
validate_maphash();
len = (int)STRLEN(keys);
#ifdef FEAT_LOCALMAP
for (local = 1; local >= 0; --local)
#endif
/* loop over all hash lists */
for (hash = 0; hash < 256; ++hash)
{
if (abbr)
{
if (hash > 0) /* there is only one list. */
break;
#ifdef FEAT_LOCALMAP
if (local)
mp = curbuf->b_first_abbr;
else
#endif
mp = first_abbr;
}
#ifdef FEAT_LOCALMAP
else if (local)
mp = curbuf->b_maphash[hash];
#endif
else
mp = maphash[hash];
for ( ; mp != NULL; mp = mp->m_next)
{
/* skip entries with wrong mode, wrong length and not matching
* ones */
if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
{
if (len > mp->m_keylen)
minlen = mp->m_keylen;
else
minlen = len;
s = mp->m_keys;
if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
&& s[2] != NUL)
{
s += 3;
if (len > mp->m_keylen - 3)
minlen = mp->m_keylen - 3;
}
if (STRNCMP(s, keys, minlen) == 0)
{
if (mp_ptr != NULL)
*mp_ptr = mp;
if (local_ptr != NULL)
#ifdef FEAT_LOCALMAP
*local_ptr = local;
#else
*local_ptr = 0;
#endif
return mp->m_str;
}
}
}
}
return NULL;
}
#endif
#if defined(MSWIN) || defined(MACOS_X)
# define VIS_SEL (VISUAL+SELECTMODE) /* abbreviation */
/*
* Default mappings for some often used keys.
*/
struct initmap
{
char_u *arg;
int mode;
};
# ifdef FEAT_GUI_MSWIN
/* Use the Windows (CUA) keybindings. (GUI) */
static struct initmap initmappings[] =
{
/* paste, copy and cut */
{(char_u *)"<S-Insert> \"*P", NORMAL},
{(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
{(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
{(char_u *)"<C-Insert> \"*y", VIS_SEL},
{(char_u *)"<S-Del> \"*d", VIS_SEL},
{(char_u *)"<C-Del> \"*d", VIS_SEL},
{(char_u *)"<C-X> \"*d", VIS_SEL},
/* Missing: CTRL-C (cancel) and CTRL-V (block selection) */
};
# endif
# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
/* Use the Windows (CUA) keybindings. (Console) */
static struct initmap cinitmappings[] =
{
{(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
{(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
{(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
{(char_u *)"\316u <C-End>", INSERT+CMDLINE},
/* paste, copy and cut */
# ifdef FEAT_CLIPBOARD
{(char_u *)"\316\324 \"*P", NORMAL}, /* SHIFT-Insert is "*P */
{(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, /* SHIFT-Insert is "-d"*P */
{(char_u *)"\316\324 \022\017*", INSERT}, /* SHIFT-Insert is ^R^O* */
{(char_u *)"\316\325 \"*y", VIS_SEL}, /* CTRL-Insert is "*y */
{(char_u *)"\316\327 \"*d", VIS_SEL}, /* SHIFT-Del is "*d */
{(char_u *)"\316\330 \"*d", VIS_SEL}, /* CTRL-Del is "*d */
{(char_u *)"\030 \"*d", VIS_SEL}, /* CTRL-X is "*d */
# else
{(char_u *)"\316\324 P", NORMAL}, /* SHIFT-Insert is P */
{(char_u *)"\316\324 \"-dP", VIS_SEL}, /* SHIFT-Insert is "-dP */
{(char_u *)"\316\324 \022\017\"", INSERT}, /* SHIFT-Insert is ^R^O" */
{(char_u *)"\316\325 y", VIS_SEL}, /* CTRL-Insert is y */
{(char_u *)"\316\327 d", VIS_SEL}, /* SHIFT-Del is d */
{(char_u *)"\316\330 d", VIS_SEL}, /* CTRL-Del is d */
# endif
};
# endif
# if defined(MACOS_X)
static struct initmap initmappings[] =
{
/* Use the Standard MacOS binding. */
/* paste, copy and cut */
{(char_u *)"<D-v> \"*P", NORMAL},
{(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
{(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
{(char_u *)"<D-c> \"*y", VIS_SEL},
{(char_u *)"<D-x> \"*d", VIS_SEL},
{(char_u *)"<Backspace> \"-d", VIS_SEL},
};
# endif
# undef VIS_SEL
#endif
/*
* Set up default mappings.
*/
void
init_mappings(void)
{
#if defined(MSWIN) || defined(MACOS_X)
int i;
# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
# ifdef VIMDLL
if (!gui.starting)
# endif
{
for (i = 0;
i < (int)(sizeof(cinitmappings) / sizeof(struct initmap)); ++i)
add_map(cinitmappings[i].arg, cinitmappings[i].mode);
}
# endif
# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
for (i = 0; i < (int)(sizeof(initmappings) / sizeof(struct initmap)); ++i)
add_map(initmappings[i].arg, initmappings[i].mode);
# endif
#endif
}
#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
|| defined(PROTO)
/*
* Add a mapping "map" for mode "mode".
* Need to put string in allocated memory, because do_map() will modify it.
*/
void
add_map(char_u *map, int mode)
{
char_u *s;
char_u *cpo_save = p_cpo;
p_cpo = (char_u *)""; /* Allow <> notation */
s = vim_strsave(map);
if (s != NULL)
{
(void)do_map(0, s, mode, FALSE);
vim_free(s);
}
p_cpo = cpo_save;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-78/c/good_882_0 |
crossvul-cpp_data_bad_882_2 | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
#include "vim.h"
#ifdef AMIGA
# include <time.h> /* for time() */
#endif
/*
* Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)
* It has been changed beyond recognition since then.
*
* Differences between version 7.4 and 8.x can be found with ":help version8".
* Differences between version 6.4 and 7.x can be found with ":help version7".
* Differences between version 5.8 and 6.x can be found with ":help version6".
* Differences between version 4.x and 5.x can be found with ":help version5".
* Differences between version 3.0 and 4.x can be found with ":help version4".
* All the remarks about older versions have been removed, they are not very
* interesting.
*/
#include "version.h"
char *Version = VIM_VERSION_SHORT;
static char *mediumVersion = VIM_VERSION_MEDIUM;
#if defined(HAVE_DATE_TIME) || defined(PROTO)
# if (defined(VMS) && defined(VAXC)) || defined(PROTO)
char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)
+ sizeof(__TIME__) + 3];
void
init_longVersion(void)
{
/*
* Construct the long version string. Necessary because
* VAX C can't concatenate strings in the preprocessor.
*/
strcpy(longVersion, VIM_VERSION_LONG_DATE);
strcat(longVersion, __DATE__);
strcat(longVersion, " ");
strcat(longVersion, __TIME__);
strcat(longVersion, ")");
}
# else
void
init_longVersion(void)
{
char *date_time = __DATE__ " " __TIME__;
char *msg = _("%s (%s, compiled %s)");
size_t len = strlen(msg)
+ strlen(VIM_VERSION_LONG_ONLY)
+ strlen(VIM_VERSION_DATE_ONLY)
+ strlen(date_time);
longVersion = (char *)alloc((unsigned)len);
if (longVersion == NULL)
longVersion = VIM_VERSION_LONG;
else
vim_snprintf(longVersion, len, msg,
VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);
}
# endif
#else
char *longVersion = VIM_VERSION_LONG;
void
init_longVersion(void)
{
// nothing to do
}
#endif
static char *(features[]) =
{
#ifdef HAVE_ACL
"+acl",
#else
"-acl",
#endif
#ifdef AMIGA /* only for Amiga systems */
# ifdef FEAT_ARP
"+ARP",
# else
"-ARP",
# endif
#endif
#ifdef FEAT_ARABIC
"+arabic",
#else
"-arabic",
#endif
"+autocmd",
#ifdef FEAT_AUTOCHDIR
"+autochdir",
#else
"-autochdir",
#endif
#ifdef FEAT_AUTOSERVERNAME
"+autoservername",
#else
"-autoservername",
#endif
#ifdef FEAT_BEVAL_GUI
"+balloon_eval",
#else
"-balloon_eval",
#endif
#ifdef FEAT_BEVAL_TERM
"+balloon_eval_term",
#else
"-balloon_eval_term",
#endif
#ifdef FEAT_BROWSE
"+browse",
#else
"-browse",
#endif
#ifdef NO_BUILTIN_TCAPS
"-builtin_terms",
#endif
#ifdef SOME_BUILTIN_TCAPS
"+builtin_terms",
#endif
#ifdef ALL_BUILTIN_TCAPS
"++builtin_terms",
#endif
#ifdef FEAT_BYTEOFF
"+byte_offset",
#else
"-byte_offset",
#endif
#ifdef FEAT_JOB_CHANNEL
"+channel",
#else
"-channel",
#endif
#ifdef FEAT_CINDENT
"+cindent",
#else
"-cindent",
#endif
#ifdef FEAT_CLIENTSERVER
"+clientserver",
#else
"-clientserver",
#endif
#ifdef FEAT_CLIPBOARD
"+clipboard",
#else
"-clipboard",
#endif
#ifdef FEAT_CMDL_COMPL
"+cmdline_compl",
#else
"-cmdline_compl",
#endif
#ifdef FEAT_CMDHIST
"+cmdline_hist",
#else
"-cmdline_hist",
#endif
#ifdef FEAT_CMDL_INFO
"+cmdline_info",
#else
"-cmdline_info",
#endif
#ifdef FEAT_COMMENTS
"+comments",
#else
"-comments",
#endif
#ifdef FEAT_CONCEAL
"+conceal",
#else
"-conceal",
#endif
#ifdef FEAT_CRYPT
"+cryptv",
#else
"-cryptv",
#endif
#ifdef FEAT_CSCOPE
"+cscope",
#else
"-cscope",
#endif
"+cursorbind",
#ifdef CURSOR_SHAPE
"+cursorshape",
#else
"-cursorshape",
#endif
#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)
"+dialog_con_gui",
#else
# if defined(FEAT_CON_DIALOG)
"+dialog_con",
# else
# if defined(FEAT_GUI_DIALOG)
"+dialog_gui",
# else
"-dialog",
# endif
# endif
#endif
#ifdef FEAT_DIFF
"+diff",
#else
"-diff",
#endif
#ifdef FEAT_DIGRAPHS
"+digraphs",
#else
"-digraphs",
#endif
#ifdef FEAT_GUI_MSWIN
# ifdef FEAT_DIRECTX
"+directx",
# else
"-directx",
# endif
#endif
#ifdef FEAT_DND
"+dnd",
#else
"-dnd",
#endif
#ifdef EBCDIC
"+ebcdic",
#else
"-ebcdic",
#endif
#ifdef FEAT_EMACS_TAGS
"+emacs_tags",
#else
"-emacs_tags",
#endif
#ifdef FEAT_EVAL
"+eval",
#else
"-eval",
#endif
"+ex_extra",
#ifdef FEAT_SEARCH_EXTRA
"+extra_search",
#else
"-extra_search",
#endif
"-farsi",
#ifdef FEAT_SEARCHPATH
"+file_in_path",
#else
"-file_in_path",
#endif
#ifdef FEAT_FIND_ID
"+find_in_path",
#else
"-find_in_path",
#endif
#ifdef FEAT_FLOAT
"+float",
#else
"-float",
#endif
#ifdef FEAT_FOLDING
"+folding",
#else
"-folding",
#endif
#ifdef FEAT_FOOTER
"+footer",
#else
"-footer",
#endif
/* only interesting on Unix systems */
#if !defined(USE_SYSTEM) && defined(UNIX)
"+fork()",
#endif
#ifdef FEAT_GETTEXT
# ifdef DYNAMIC_GETTEXT
"+gettext/dyn",
# else
"+gettext",
# endif
#else
"-gettext",
#endif
#ifdef FEAT_HANGULIN
"+hangul_input",
#else
"-hangul_input",
#endif
#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)
# ifdef DYNAMIC_ICONV
"+iconv/dyn",
# else
"+iconv",
# endif
#else
"-iconv",
#endif
#ifdef FEAT_INS_EXPAND
"+insert_expand",
#else
"-insert_expand",
#endif
#ifdef FEAT_JOB_CHANNEL
"+job",
#else
"-job",
#endif
#ifdef FEAT_JUMPLIST
"+jumplist",
#else
"-jumplist",
#endif
#ifdef FEAT_KEYMAP
"+keymap",
#else
"-keymap",
#endif
#ifdef FEAT_EVAL
"+lambda",
#else
"-lambda",
#endif
#ifdef FEAT_LANGMAP
"+langmap",
#else
"-langmap",
#endif
#ifdef FEAT_LIBCALL
"+libcall",
#else
"-libcall",
#endif
#ifdef FEAT_LINEBREAK
"+linebreak",
#else
"-linebreak",
#endif
#ifdef FEAT_LISP
"+lispindent",
#else
"-lispindent",
#endif
"+listcmds",
#ifdef FEAT_LOCALMAP
"+localmap",
#else
"-localmap",
#endif
#ifdef FEAT_LUA
# ifdef DYNAMIC_LUA
"+lua/dyn",
# else
"+lua",
# endif
#else
"-lua",
#endif
#ifdef FEAT_MENU
"+menu",
#else
"-menu",
#endif
#ifdef FEAT_SESSION
"+mksession",
#else
"-mksession",
#endif
#ifdef FEAT_MODIFY_FNAME
"+modify_fname",
#else
"-modify_fname",
#endif
#ifdef FEAT_MOUSE
"+mouse",
# ifdef FEAT_MOUSESHAPE
"+mouseshape",
# else
"-mouseshape",
# endif
# else
"-mouse",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_MOUSE_DEC
"+mouse_dec",
# else
"-mouse_dec",
# endif
# ifdef FEAT_MOUSE_GPM
"+mouse_gpm",
# else
"-mouse_gpm",
# endif
# ifdef FEAT_MOUSE_JSB
"+mouse_jsbterm",
# else
"-mouse_jsbterm",
# endif
# ifdef FEAT_MOUSE_NET
"+mouse_netterm",
# else
"-mouse_netterm",
# endif
#endif
#ifdef __QNX__
# ifdef FEAT_MOUSE_PTERM
"+mouse_pterm",
# else
"-mouse_pterm",
# endif
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_MOUSE_XTERM
"+mouse_sgr",
# else
"-mouse_sgr",
# endif
# ifdef FEAT_SYSMOUSE
"+mouse_sysmouse",
# else
"-mouse_sysmouse",
# endif
# ifdef FEAT_MOUSE_URXVT
"+mouse_urxvt",
# else
"-mouse_urxvt",
# endif
# ifdef FEAT_MOUSE_XTERM
"+mouse_xterm",
# else
"-mouse_xterm",
# endif
#endif
#ifdef FEAT_MBYTE_IME
# ifdef DYNAMIC_IME
"+multi_byte_ime/dyn",
# else
"+multi_byte_ime",
# endif
#else
"+multi_byte",
#endif
#ifdef FEAT_MULTI_LANG
"+multi_lang",
#else
"-multi_lang",
#endif
#ifdef FEAT_MZSCHEME
# ifdef DYNAMIC_MZSCHEME
"+mzscheme/dyn",
# else
"+mzscheme",
# endif
#else
"-mzscheme",
#endif
#ifdef FEAT_NETBEANS_INTG
"+netbeans_intg",
#else
"-netbeans_intg",
#endif
#ifdef FEAT_NUM64
"+num64",
#else
"-num64",
#endif
#ifdef FEAT_GUI_MSWIN
# ifdef FEAT_OLE
"+ole",
# else
"-ole",
# endif
#endif
#ifdef FEAT_EVAL
"+packages",
#else
"-packages",
#endif
#ifdef FEAT_PATH_EXTRA
"+path_extra",
#else
"-path_extra",
#endif
#ifdef FEAT_PERL
# ifdef DYNAMIC_PERL
"+perl/dyn",
# else
"+perl",
# endif
#else
"-perl",
#endif
#ifdef FEAT_PERSISTENT_UNDO
"+persistent_undo",
#else
"-persistent_undo",
#endif
#ifdef FEAT_PRINTER
# ifdef FEAT_POSTSCRIPT
"+postscript",
# else
"-postscript",
# endif
"+printer",
#else
"-printer",
#endif
#ifdef FEAT_PROFILE
"+profile",
#else
"-profile",
#endif
#ifdef FEAT_PYTHON
# ifdef DYNAMIC_PYTHON
"+python/dyn",
# else
"+python",
# endif
#else
"-python",
#endif
#ifdef FEAT_PYTHON3
# ifdef DYNAMIC_PYTHON3
"+python3/dyn",
# else
"+python3",
# endif
#else
"-python3",
#endif
#ifdef FEAT_QUICKFIX
"+quickfix",
#else
"-quickfix",
#endif
#ifdef FEAT_RELTIME
"+reltime",
#else
"-reltime",
#endif
#ifdef FEAT_RIGHTLEFT
"+rightleft",
#else
"-rightleft",
#endif
#ifdef FEAT_RUBY
# ifdef DYNAMIC_RUBY
"+ruby/dyn",
# else
"+ruby",
# endif
#else
"-ruby",
#endif
"+scrollbind",
#ifdef FEAT_SIGNS
"+signs",
#else
"-signs",
#endif
#ifdef FEAT_SMARTINDENT
"+smartindent",
#else
"-smartindent",
#endif
#ifdef STARTUPTIME
"+startuptime",
#else
"-startuptime",
#endif
#ifdef FEAT_STL_OPT
"+statusline",
#else
"-statusline",
#endif
"-sun_workshop",
#ifdef FEAT_SYN_HL
"+syntax",
#else
"-syntax",
#endif
/* only interesting on Unix systems */
#if defined(USE_SYSTEM) && defined(UNIX)
"+system()",
#endif
#ifdef FEAT_TAG_BINS
"+tag_binary",
#else
"-tag_binary",
#endif
"-tag_old_static",
"-tag_any_white",
#ifdef FEAT_TCL
# ifdef DYNAMIC_TCL
"+tcl/dyn",
# else
"+tcl",
# endif
#else
"-tcl",
#endif
#ifdef FEAT_TERMGUICOLORS
"+termguicolors",
#else
"-termguicolors",
#endif
#ifdef FEAT_TERMINAL
"+terminal",
#else
"-terminal",
#endif
#if defined(UNIX)
/* only Unix can have terminfo instead of termcap */
# ifdef TERMINFO
"+terminfo",
# else
"-terminfo",
# endif
#endif
#ifdef FEAT_TERMRESPONSE
"+termresponse",
#else
"-termresponse",
#endif
#ifdef FEAT_TEXTOBJ
"+textobjects",
#else
"-textobjects",
#endif
#ifdef FEAT_TEXT_PROP
"+textprop",
#else
"-textprop",
#endif
#if !defined(UNIX)
/* unix always includes termcap support */
# ifdef HAVE_TGETENT
"+tgetent",
# else
"-tgetent",
# endif
#endif
#ifdef FEAT_TIMERS
"+timers",
#else
"-timers",
#endif
#ifdef FEAT_TITLE
"+title",
#else
"-title",
#endif
#ifdef FEAT_TOOLBAR
"+toolbar",
#else
"-toolbar",
#endif
"+user_commands",
#ifdef FEAT_VARTABS
"+vartabs",
#else
"-vartabs",
#endif
"+vertsplit",
"+virtualedit",
"+visual",
"+visualextra",
#ifdef FEAT_VIMINFO
"+viminfo",
#else
"-viminfo",
#endif
"+vreplace",
#ifdef MSWIN
# ifdef FEAT_VTP
"+vtp",
# else
"-vtp",
# endif
#endif
#ifdef FEAT_WILDIGN
"+wildignore",
#else
"-wildignore",
#endif
#ifdef FEAT_WILDMENU
"+wildmenu",
#else
"-wildmenu",
#endif
"+windows",
#ifdef FEAT_WRITEBACKUP
"+writebackup",
#else
"-writebackup",
#endif
#if defined(UNIX) || defined(VMS)
# ifdef FEAT_X11
"+X11",
# else
"-X11",
# endif
#endif
#ifdef FEAT_XFONTSET
"+xfontset",
#else
"-xfontset",
#endif
#ifdef FEAT_XIM
"+xim",
#else
"-xim",
#endif
#ifdef MSWIN
# ifdef FEAT_XPM_W32
"+xpm_w32",
# else
"-xpm_w32",
# endif
#else
# ifdef HAVE_XPM
"+xpm",
# else
"-xpm",
# endif
#endif
#if defined(UNIX) || defined(VMS)
# ifdef USE_XSMP_INTERACT
"+xsmp_interact",
# else
# ifdef USE_XSMP
"+xsmp",
# else
"-xsmp",
# endif
# endif
# ifdef FEAT_XCLIPBOARD
"+xterm_clipboard",
# else
"-xterm_clipboard",
# endif
#endif
#ifdef FEAT_XTERM_SAVE
"+xterm_save",
#else
"-xterm_save",
#endif
NULL
};
static int included_patches[] =
{ /* Add new patch number below this line */
/**/
1364,
/**/
1363,
/**/
1362,
/**/
1361,
/**/
1360,
/**/
1359,
/**/
1358,
/**/
1357,
/**/
1356,
/**/
1355,
/**/
1354,
/**/
1353,
/**/
1352,
/**/
1351,
/**/
1350,
/**/
1349,
/**/
1348,
/**/
1347,
/**/
1346,
/**/
1345,
/**/
1344,
/**/
1343,
/**/
1342,
/**/
1341,
/**/
1340,
/**/
1339,
/**/
1338,
/**/
1337,
/**/
1336,
/**/
1335,
/**/
1334,
/**/
1333,
/**/
1332,
/**/
1331,
/**/
1330,
/**/
1329,
/**/
1328,
/**/
1327,
/**/
1326,
/**/
1325,
/**/
1324,
/**/
1323,
/**/
1322,
/**/
1321,
/**/
1320,
/**/
1319,
/**/
1318,
/**/
1317,
/**/
1316,
/**/
1315,
/**/
1314,
/**/
1313,
/**/
1312,
/**/
1311,
/**/
1310,
/**/
1309,
/**/
1308,
/**/
1307,
/**/
1306,
/**/
1305,
/**/
1304,
/**/
1303,
/**/
1302,
/**/
1301,
/**/
1300,
/**/
1299,
/**/
1298,
/**/
1297,
/**/
1296,
/**/
1295,
/**/
1294,
/**/
1293,
/**/
1292,
/**/
1291,
/**/
1290,
/**/
1289,
/**/
1288,
/**/
1287,
/**/
1286,
/**/
1285,
/**/
1284,
/**/
1283,
/**/
1282,
/**/
1281,
/**/
1280,
/**/
1279,
/**/
1278,
/**/
1277,
/**/
1276,
/**/
1275,
/**/
1274,
/**/
1273,
/**/
1272,
/**/
1271,
/**/
1270,
/**/
1269,
/**/
1268,
/**/
1267,
/**/
1266,
/**/
1265,
/**/
1264,
/**/
1263,
/**/
1262,
/**/
1261,
/**/
1260,
/**/
1259,
/**/
1258,
/**/
1257,
/**/
1256,
/**/
1255,
/**/
1254,
/**/
1253,
/**/
1252,
/**/
1251,
/**/
1250,
/**/
1249,
/**/
1248,
/**/
1247,
/**/
1246,
/**/
1245,
/**/
1244,
/**/
1243,
/**/
1242,
/**/
1241,
/**/
1240,
/**/
1239,
/**/
1238,
/**/
1237,
/**/
1236,
/**/
1235,
/**/
1234,
/**/
1233,
/**/
1232,
/**/
1231,
/**/
1230,
/**/
1229,
/**/
1228,
/**/
1227,
/**/
1226,
/**/
1225,
/**/
1224,
/**/
1223,
/**/
1222,
/**/
1221,
/**/
1220,
/**/
1219,
/**/
1218,
/**/
1217,
/**/
1216,
/**/
1215,
/**/
1214,
/**/
1213,
/**/
1212,
/**/
1211,
/**/
1210,
/**/
1209,
/**/
1208,
/**/
1207,
/**/
1206,
/**/
1205,
/**/
1204,
/**/
1203,
/**/
1202,
/**/
1201,
/**/
1200,
/**/
1199,
/**/
1198,
/**/
1197,
/**/
1196,
/**/
1195,
/**/
1194,
/**/
1193,
/**/
1192,
/**/
1191,
/**/
1190,
/**/
1189,
/**/
1188,
/**/
1187,
/**/
1186,
/**/
1185,
/**/
1184,
/**/
1183,
/**/
1182,
/**/
1181,
/**/
1180,
/**/
1179,
/**/
1178,
/**/
1177,
/**/
1176,
/**/
1175,
/**/
1174,
/**/
1173,
/**/
1172,
/**/
1171,
/**/
1170,
/**/
1169,
/**/
1168,
/**/
1167,
/**/
1166,
/**/
1165,
/**/
1164,
/**/
1163,
/**/
1162,
/**/
1161,
/**/
1160,
/**/
1159,
/**/
1158,
/**/
1157,
/**/
1156,
/**/
1155,
/**/
1154,
/**/
1153,
/**/
1152,
/**/
1151,
/**/
1150,
/**/
1149,
/**/
1148,
/**/
1147,
/**/
1146,
/**/
1145,
/**/
1144,
/**/
1143,
/**/
1142,
/**/
1141,
/**/
1140,
/**/
1139,
/**/
1138,
/**/
1137,
/**/
1136,
/**/
1135,
/**/
1134,
/**/
1133,
/**/
1132,
/**/
1131,
/**/
1130,
/**/
1129,
/**/
1128,
/**/
1127,
/**/
1126,
/**/
1125,
/**/
1124,
/**/
1123,
/**/
1122,
/**/
1121,
/**/
1120,
/**/
1119,
/**/
1118,
/**/
1117,
/**/
1116,
/**/
1115,
/**/
1114,
/**/
1113,
/**/
1112,
/**/
1111,
/**/
1110,
/**/
1109,
/**/
1108,
/**/
1107,
/**/
1106,
/**/
1105,
/**/
1104,
/**/
1103,
/**/
1102,
/**/
1101,
/**/
1100,
/**/
1099,
/**/
1098,
/**/
1097,
/**/
1096,
/**/
1095,
/**/
1094,
/**/
1093,
/**/
1092,
/**/
1091,
/**/
1090,
/**/
1089,
/**/
1088,
/**/
1087,
/**/
1086,
/**/
1085,
/**/
1084,
/**/
1083,
/**/
1082,
/**/
1081,
/**/
1080,
/**/
1079,
/**/
1078,
/**/
1077,
/**/
1076,
/**/
1075,
/**/
1074,
/**/
1073,
/**/
1072,
/**/
1071,
/**/
1070,
/**/
1069,
/**/
1068,
/**/
1067,
/**/
1066,
/**/
1065,
/**/
1064,
/**/
1063,
/**/
1062,
/**/
1061,
/**/
1060,
/**/
1059,
/**/
1058,
/**/
1057,
/**/
1056,
/**/
1055,
/**/
1054,
/**/
1053,
/**/
1052,
/**/
1051,
/**/
1050,
/**/
1049,
/**/
1048,
/**/
1047,
/**/
1046,
/**/
1045,
/**/
1044,
/**/
1043,
/**/
1042,
/**/
1041,
/**/
1040,
/**/
1039,
/**/
1038,
/**/
1037,
/**/
1036,
/**/
1035,
/**/
1034,
/**/
1033,
/**/
1032,
/**/
1031,
/**/
1030,
/**/
1029,
/**/
1028,
/**/
1027,
/**/
1026,
/**/
1025,
/**/
1024,
/**/
1023,
/**/
1022,
/**/
1021,
/**/
1020,
/**/
1019,
/**/
1018,
/**/
1017,
/**/
1016,
/**/
1015,
/**/
1014,
/**/
1013,
/**/
1012,
/**/
1011,
/**/
1010,
/**/
1009,
/**/
1008,
/**/
1007,
/**/
1006,
/**/
1005,
/**/
1004,
/**/
1003,
/**/
1002,
/**/
1001,
/**/
1000,
/**/
999,
/**/
998,
/**/
997,
/**/
996,
/**/
995,
/**/
994,
/**/
993,
/**/
992,
/**/
991,
/**/
990,
/**/
989,
/**/
988,
/**/
987,
/**/
986,
/**/
985,
/**/
984,
/**/
983,
/**/
982,
/**/
981,
/**/
980,
/**/
979,
/**/
978,
/**/
977,
/**/
976,
/**/
975,
/**/
974,
/**/
973,
/**/
972,
/**/
971,
/**/
970,
/**/
969,
/**/
968,
/**/
967,
/**/
966,
/**/
965,
/**/
964,
/**/
963,
/**/
962,
/**/
961,
/**/
960,
/**/
959,
/**/
958,
/**/
957,
/**/
956,
/**/
955,
/**/
954,
/**/
953,
/**/
952,
/**/
951,
/**/
950,
/**/
949,
/**/
948,
/**/
947,
/**/
946,
/**/
945,
/**/
944,
/**/
943,
/**/
942,
/**/
941,
/**/
940,
/**/
939,
/**/
938,
/**/
937,
/**/
936,
/**/
935,
/**/
934,
/**/
933,
/**/
932,
/**/
931,
/**/
930,
/**/
929,
/**/
928,
/**/
927,
/**/
926,
/**/
925,
/**/
924,
/**/
923,
/**/
922,
/**/
921,
/**/
920,
/**/
919,
/**/
918,
/**/
917,
/**/
916,
/**/
915,
/**/
914,
/**/
913,
/**/
912,
/**/
911,
/**/
910,
/**/
909,
/**/
908,
/**/
907,
/**/
906,
/**/
905,
/**/
904,
/**/
903,
/**/
902,
/**/
901,
/**/
900,
/**/
899,
/**/
898,
/**/
897,
/**/
896,
/**/
895,
/**/
894,
/**/
893,
/**/
892,
/**/
891,
/**/
890,
/**/
889,
/**/
888,
/**/
887,
/**/
886,
/**/
885,
/**/
884,
/**/
883,
/**/
882,
/**/
881,
/**/
880,
/**/
879,
/**/
878,
/**/
877,
/**/
876,
/**/
875,
/**/
874,
/**/
873,
/**/
872,
/**/
871,
/**/
870,
/**/
869,
/**/
868,
/**/
867,
/**/
866,
/**/
865,
/**/
864,
/**/
863,
/**/
862,
/**/
861,
/**/
860,
/**/
859,
/**/
858,
/**/
857,
/**/
856,
/**/
855,
/**/
854,
/**/
853,
/**/
852,
/**/
851,
/**/
850,
/**/
849,
/**/
848,
/**/
847,
/**/
846,
/**/
845,
/**/
844,
/**/
843,
/**/
842,
/**/
841,
/**/
840,
/**/
839,
/**/
838,
/**/
837,
/**/
836,
/**/
835,
/**/
834,
/**/
833,
/**/
832,
/**/
831,
/**/
830,
/**/
829,
/**/
828,
/**/
827,
/**/
826,
/**/
825,
/**/
824,
/**/
823,
/**/
822,
/**/
821,
/**/
820,
/**/
819,
/**/
818,
/**/
817,
/**/
816,
/**/
815,
/**/
814,
/**/
813,
/**/
812,
/**/
811,
/**/
810,
/**/
809,
/**/
808,
/**/
807,
/**/
806,
/**/
805,
/**/
804,
/**/
803,
/**/
802,
/**/
801,
/**/
800,
/**/
799,
/**/
798,
/**/
797,
/**/
796,
/**/
795,
/**/
794,
/**/
793,
/**/
792,
/**/
791,
/**/
790,
/**/
789,
/**/
788,
/**/
787,
/**/
786,
/**/
785,
/**/
784,
/**/
783,
/**/
782,
/**/
781,
/**/
780,
/**/
779,
/**/
778,
/**/
777,
/**/
776,
/**/
775,
/**/
774,
/**/
773,
/**/
772,
/**/
771,
/**/
770,
/**/
769,
/**/
768,
/**/
767,
/**/
766,
/**/
765,
/**/
764,
/**/
763,
/**/
762,
/**/
761,
/**/
760,
/**/
759,
/**/
758,
/**/
757,
/**/
756,
/**/
755,
/**/
754,
/**/
753,
/**/
752,
/**/
751,
/**/
750,
/**/
749,
/**/
748,
/**/
747,
/**/
746,
/**/
745,
/**/
744,
/**/
743,
/**/
742,
/**/
741,
/**/
740,
/**/
739,
/**/
738,
/**/
737,
/**/
736,
/**/
735,
/**/
734,
/**/
733,
/**/
732,
/**/
731,
/**/
730,
/**/
729,
/**/
728,
/**/
727,
/**/
726,
/**/
725,
/**/
724,
/**/
723,
/**/
722,
/**/
721,
/**/
720,
/**/
719,
/**/
718,
/**/
717,
/**/
716,
/**/
715,
/**/
714,
/**/
713,
/**/
712,
/**/
711,
/**/
710,
/**/
709,
/**/
708,
/**/
707,
/**/
706,
/**/
705,
/**/
704,
/**/
703,
/**/
702,
/**/
701,
/**/
700,
/**/
699,
/**/
698,
/**/
697,
/**/
696,
/**/
695,
/**/
694,
/**/
693,
/**/
692,
/**/
691,
/**/
690,
/**/
689,
/**/
688,
/**/
687,
/**/
686,
/**/
685,
/**/
684,
/**/
683,
/**/
682,
/**/
681,
/**/
680,
/**/
679,
/**/
678,
/**/
677,
/**/
676,
/**/
675,
/**/
674,
/**/
673,
/**/
672,
/**/
671,
/**/
670,
/**/
669,
/**/
668,
/**/
667,
/**/
666,
/**/
665,
/**/
664,
/**/
663,
/**/
662,
/**/
661,
/**/
660,
/**/
659,
/**/
658,
/**/
657,
/**/
656,
/**/
655,
/**/
654,
/**/
653,
/**/
652,
/**/
651,
/**/
650,
/**/
649,
/**/
648,
/**/
647,
/**/
646,
/**/
645,
/**/
644,
/**/
643,
/**/
642,
/**/
641,
/**/
640,
/**/
639,
/**/
638,
/**/
637,
/**/
636,
/**/
635,
/**/
634,
/**/
633,
/**/
632,
/**/
631,
/**/
630,
/**/
629,
/**/
628,
/**/
627,
/**/
626,
/**/
625,
/**/
624,
/**/
623,
/**/
622,
/**/
621,
/**/
620,
/**/
619,
/**/
618,
/**/
617,
/**/
616,
/**/
615,
/**/
614,
/**/
613,
/**/
612,
/**/
611,
/**/
610,
/**/
609,
/**/
608,
/**/
607,
/**/
606,
/**/
605,
/**/
604,
/**/
603,
/**/
602,
/**/
601,
/**/
600,
/**/
599,
/**/
598,
/**/
597,
/**/
596,
/**/
595,
/**/
594,
/**/
593,
/**/
592,
/**/
591,
/**/
590,
/**/
589,
/**/
588,
/**/
587,
/**/
586,
/**/
585,
/**/
584,
/**/
583,
/**/
582,
/**/
581,
/**/
580,
/**/
579,
/**/
578,
/**/
577,
/**/
576,
/**/
575,
/**/
574,
/**/
573,
/**/
572,
/**/
571,
/**/
570,
/**/
569,
/**/
568,
/**/
567,
/**/
566,
/**/
565,
/**/
564,
/**/
563,
/**/
562,
/**/
561,
/**/
560,
/**/
559,
/**/
558,
/**/
557,
/**/
556,
/**/
555,
/**/
554,
/**/
553,
/**/
552,
/**/
551,
/**/
550,
/**/
549,
/**/
548,
/**/
547,
/**/
546,
/**/
545,
/**/
544,
/**/
543,
/**/
542,
/**/
541,
/**/
540,
/**/
539,
/**/
538,
/**/
537,
/**/
536,
/**/
535,
/**/
534,
/**/
533,
/**/
532,
/**/
531,
/**/
530,
/**/
529,
/**/
528,
/**/
527,
/**/
526,
/**/
525,
/**/
524,
/**/
523,
/**/
522,
/**/
521,
/**/
520,
/**/
519,
/**/
518,
/**/
517,
/**/
516,
/**/
515,
/**/
514,
/**/
513,
/**/
512,
/**/
511,
/**/
510,
/**/
509,
/**/
508,
/**/
507,
/**/
506,
/**/
505,
/**/
504,
/**/
503,
/**/
502,
/**/
501,
/**/
500,
/**/
499,
/**/
498,
/**/
497,
/**/
496,
/**/
495,
/**/
494,
/**/
493,
/**/
492,
/**/
491,
/**/
490,
/**/
489,
/**/
488,
/**/
487,
/**/
486,
/**/
485,
/**/
484,
/**/
483,
/**/
482,
/**/
481,
/**/
480,
/**/
479,
/**/
478,
/**/
477,
/**/
476,
/**/
475,
/**/
474,
/**/
473,
/**/
472,
/**/
471,
/**/
470,
/**/
469,
/**/
468,
/**/
467,
/**/
466,
/**/
465,
/**/
464,
/**/
463,
/**/
462,
/**/
461,
/**/
460,
/**/
459,
/**/
458,
/**/
457,
/**/
456,
/**/
455,
/**/
454,
/**/
453,
/**/
452,
/**/
451,
/**/
450,
/**/
449,
/**/
448,
/**/
447,
/**/
446,
/**/
445,
/**/
444,
/**/
443,
/**/
442,
/**/
441,
/**/
440,
/**/
439,
/**/
438,
/**/
437,
/**/
436,
/**/
435,
/**/
434,
/**/
433,
/**/
432,
/**/
431,
/**/
430,
/**/
429,
/**/
428,
/**/
427,
/**/
426,
/**/
425,
/**/
424,
/**/
423,
/**/
422,
/**/
421,
/**/
420,
/**/
419,
/**/
418,
/**/
417,
/**/
416,
/**/
415,
/**/
414,
/**/
413,
/**/
412,
/**/
411,
/**/
410,
/**/
409,
/**/
408,
/**/
407,
/**/
406,
/**/
405,
/**/
404,
/**/
403,
/**/
402,
/**/
401,
/**/
400,
/**/
399,
/**/
398,
/**/
397,
/**/
396,
/**/
395,
/**/
394,
/**/
393,
/**/
392,
/**/
391,
/**/
390,
/**/
389,
/**/
388,
/**/
387,
/**/
386,
/**/
385,
/**/
384,
/**/
383,
/**/
382,
/**/
381,
/**/
380,
/**/
379,
/**/
378,
/**/
377,
/**/
376,
/**/
375,
/**/
374,
/**/
373,
/**/
372,
/**/
371,
/**/
370,
/**/
369,
/**/
368,
/**/
367,
/**/
366,
/**/
365,
/**/
364,
/**/
363,
/**/
362,
/**/
361,
/**/
360,
/**/
359,
/**/
358,
/**/
357,
/**/
356,
/**/
355,
/**/
354,
/**/
353,
/**/
352,
/**/
351,
/**/
350,
/**/
349,
/**/
348,
/**/
347,
/**/
346,
/**/
345,
/**/
344,
/**/
343,
/**/
342,
/**/
341,
/**/
340,
/**/
339,
/**/
338,
/**/
337,
/**/
336,
/**/
335,
/**/
334,
/**/
333,
/**/
332,
/**/
331,
/**/
330,
/**/
329,
/**/
328,
/**/
327,
/**/
326,
/**/
325,
/**/
324,
/**/
323,
/**/
322,
/**/
321,
/**/
320,
/**/
319,
/**/
318,
/**/
317,
/**/
316,
/**/
315,
/**/
314,
/**/
313,
/**/
312,
/**/
311,
/**/
310,
/**/
309,
/**/
308,
/**/
307,
/**/
306,
/**/
305,
/**/
304,
/**/
303,
/**/
302,
/**/
301,
/**/
300,
/**/
299,
/**/
298,
/**/
297,
/**/
296,
/**/
295,
/**/
294,
/**/
293,
/**/
292,
/**/
291,
/**/
290,
/**/
289,
/**/
288,
/**/
287,
/**/
286,
/**/
285,
/**/
284,
/**/
283,
/**/
282,
/**/
281,
/**/
280,
/**/
279,
/**/
278,
/**/
277,
/**/
276,
/**/
275,
/**/
274,
/**/
273,
/**/
272,
/**/
271,
/**/
270,
/**/
269,
/**/
268,
/**/
267,
/**/
266,
/**/
265,
/**/
264,
/**/
263,
/**/
262,
/**/
261,
/**/
260,
/**/
259,
/**/
258,
/**/
257,
/**/
256,
/**/
255,
/**/
254,
/**/
253,
/**/
252,
/**/
251,
/**/
250,
/**/
249,
/**/
248,
/**/
247,
/**/
246,
/**/
245,
/**/
244,
/**/
243,
/**/
242,
/**/
241,
/**/
240,
/**/
239,
/**/
238,
/**/
237,
/**/
236,
/**/
235,
/**/
234,
/**/
233,
/**/
232,
/**/
231,
/**/
230,
/**/
229,
/**/
228,
/**/
227,
/**/
226,
/**/
225,
/**/
224,
/**/
223,
/**/
222,
/**/
221,
/**/
220,
/**/
219,
/**/
218,
/**/
217,
/**/
216,
/**/
215,
/**/
214,
/**/
213,
/**/
212,
/**/
211,
/**/
210,
/**/
209,
/**/
208,
/**/
207,
/**/
206,
/**/
205,
/**/
204,
/**/
203,
/**/
202,
/**/
201,
/**/
200,
/**/
199,
/**/
198,
/**/
197,
/**/
196,
/**/
195,
/**/
194,
/**/
193,
/**/
192,
/**/
191,
/**/
190,
/**/
189,
/**/
188,
/**/
187,
/**/
186,
/**/
185,
/**/
184,
/**/
183,
/**/
182,
/**/
181,
/**/
180,
/**/
179,
/**/
178,
/**/
177,
/**/
176,
/**/
175,
/**/
174,
/**/
173,
/**/
172,
/**/
171,
/**/
170,
/**/
169,
/**/
168,
/**/
167,
/**/
166,
/**/
165,
/**/
164,
/**/
163,
/**/
162,
/**/
161,
/**/
160,
/**/
159,
/**/
158,
/**/
157,
/**/
156,
/**/
155,
/**/
154,
/**/
153,
/**/
152,
/**/
151,
/**/
150,
/**/
149,
/**/
148,
/**/
147,
/**/
146,
/**/
145,
/**/
144,
/**/
143,
/**/
142,
/**/
141,
/**/
140,
/**/
139,
/**/
138,
/**/
137,
/**/
136,
/**/
135,
/**/
134,
/**/
133,
/**/
132,
/**/
131,
/**/
130,
/**/
129,
/**/
128,
/**/
127,
/**/
126,
/**/
125,
/**/
124,
/**/
123,
/**/
122,
/**/
121,
/**/
120,
/**/
119,
/**/
118,
/**/
117,
/**/
116,
/**/
115,
/**/
114,
/**/
113,
/**/
112,
/**/
111,
/**/
110,
/**/
109,
/**/
108,
/**/
107,
/**/
106,
/**/
105,
/**/
104,
/**/
103,
/**/
102,
/**/
101,
/**/
100,
/**/
99,
/**/
98,
/**/
97,
/**/
96,
/**/
95,
/**/
94,
/**/
93,
/**/
92,
/**/
91,
/**/
90,
/**/
89,
/**/
88,
/**/
87,
/**/
86,
/**/
85,
/**/
84,
/**/
83,
/**/
82,
/**/
81,
/**/
80,
/**/
79,
/**/
78,
/**/
77,
/**/
76,
/**/
75,
/**/
74,
/**/
73,
/**/
72,
/**/
71,
/**/
70,
/**/
69,
/**/
68,
/**/
67,
/**/
66,
/**/
65,
/**/
64,
/**/
63,
/**/
62,
/**/
61,
/**/
60,
/**/
59,
/**/
58,
/**/
57,
/**/
56,
/**/
55,
/**/
54,
/**/
53,
/**/
52,
/**/
51,
/**/
50,
/**/
49,
/**/
48,
/**/
47,
/**/
46,
/**/
45,
/**/
44,
/**/
43,
/**/
42,
/**/
41,
/**/
40,
/**/
39,
/**/
38,
/**/
37,
/**/
36,
/**/
35,
/**/
34,
/**/
33,
/**/
32,
/**/
31,
/**/
30,
/**/
29,
/**/
28,
/**/
27,
/**/
26,
/**/
25,
/**/
24,
/**/
23,
/**/
22,
/**/
21,
/**/
20,
/**/
19,
/**/
18,
/**/
17,
/**/
16,
/**/
15,
/**/
14,
/**/
13,
/**/
12,
/**/
11,
/**/
10,
/**/
9,
/**/
8,
/**/
7,
/**/
6,
/**/
5,
/**/
4,
/**/
3,
/**/
2,
/**/
1,
/**/
0
};
/*
* Place to put a short description when adding a feature with a patch.
* Keep it short, e.g.,: "relative numbers", "persistent undo".
* Also add a comment marker to separate the lines.
* See the official Vim patches for the diff format: It must use a context of
* one line only. Create it by hand or use "diff -C2" and edit the patch.
*/
static char *(extra_patches[]) =
{ /* Add your patch description below this line */
/**/
NULL
};
int
highest_patch(void)
{
int i;
int h = 0;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] > h)
h = included_patches[i];
return h;
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Return TRUE if patch "n" has been included.
*/
int
has_patch(int n)
{
int i;
for (i = 0; included_patches[i] != 0; ++i)
if (included_patches[i] == n)
return TRUE;
return FALSE;
}
#endif
void
ex_version(exarg_T *eap)
{
/*
* Ignore a ":version 9.99" command.
*/
if (*eap->arg == NUL)
{
msg_putchar('\n');
list_version();
}
}
/*
* Output a string for the version message. If it's going to wrap, output a
* newline, unless the message is too long to fit on the screen anyway.
* When "wrap" is TRUE wrap the string in [].
*/
static void
version_msg_wrap(char_u *s, int wrap)
{
int len = (int)vim_strsize(s) + (wrap ? 2 : 0);
if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns
&& *s != '\n')
msg_putchar('\n');
if (!got_int)
{
if (wrap)
msg_puts("[");
msg_puts((char *)s);
if (wrap)
msg_puts("]");
}
}
static void
version_msg(char *s)
{
version_msg_wrap((char_u *)s, FALSE);
}
/*
* List all features aligned in columns, dictionary style.
*/
static void
list_features(void)
{
list_in_columns((char_u **)features, -1, -1);
}
/*
* List string items nicely aligned in columns.
* When "size" is < 0 then the last entry is marked with NULL.
* The entry with index "current" is inclosed in [].
*/
void
list_in_columns(char_u **items, int size, int current)
{
int i;
int ncol;
int nrow;
int item_count = 0;
int width = 0;
#ifdef FEAT_SYN_HL
int use_highlight = (items == (char_u **)features);
#endif
/* Find the length of the longest item, use that + 1 as the column
* width. */
for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)
{
int l = (int)vim_strsize(items[i]) + (i == current ? 2 : 0);
if (l > width)
width = l;
++item_count;
}
width += 1;
if (Columns < width)
{
/* Not enough screen columns - show one per line */
for (i = 0; i < item_count; ++i)
{
version_msg_wrap(items[i], i == current);
if (msg_col > 0)
msg_putchar('\n');
}
return;
}
/* The rightmost column doesn't need a separator.
* Sacrifice it to fit in one more column if possible. */
ncol = (int) (Columns + 1) / width;
nrow = item_count / ncol + (item_count % ncol ? 1 : 0);
/* i counts columns then rows. idx counts rows then columns. */
for (i = 0; !got_int && i < nrow * ncol; ++i)
{
int idx = (i / ncol) + (i % ncol) * nrow;
if (idx < item_count)
{
int last_col = (i + 1) % ncol == 0;
if (idx == current)
msg_putchar('[');
#ifdef FEAT_SYN_HL
if (use_highlight && items[idx][0] == '-')
msg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));
else
#endif
msg_puts((char *)items[idx]);
if (idx == current)
msg_putchar(']');
if (last_col)
{
if (msg_col > 0)
msg_putchar('\n');
}
else
{
while (msg_col % width)
msg_putchar(' ');
}
}
else
{
if (msg_col > 0)
msg_putchar('\n');
}
}
}
void
list_version(void)
{
int i;
int first;
char *s = "";
/*
* When adding features here, don't forget to update the list of
* internal variables in eval.c!
*/
init_longVersion();
msg(longVersion);
#ifdef MSWIN
# ifdef FEAT_GUI_MSWIN
# ifdef VIMDLL
# ifdef _WIN64
msg_puts(_("\nMS-Windows 64-bit GUI/console version"));
# else
msg_puts(_("\nMS-Windows 32-bit GUI/console version"));
# endif
# else
# ifdef _WIN64
msg_puts(_("\nMS-Windows 64-bit GUI version"));
# else
msg_puts(_("\nMS-Windows 32-bit GUI version"));
# endif
# endif
# ifdef FEAT_OLE
msg_puts(_(" with OLE support"));
# endif
# else
# ifdef _WIN64
msg_puts(_("\nMS-Windows 64-bit console version"));
# else
msg_puts(_("\nMS-Windows 32-bit console version"));
# endif
# endif
#endif
#if defined(MACOS_X)
# if defined(MACOS_X_DARWIN)
msg_puts(_("\nmacOS version"));
# else
msg_puts(_("\nmacOS version w/o darwin feat."));
# endif
#endif
#ifdef VMS
msg_puts(_("\nOpenVMS version"));
# ifdef HAVE_PATHDEF
if (*compiled_arch != NUL)
{
msg_puts(" - ");
msg_puts((char *)compiled_arch);
}
# endif
#endif
/* Print the list of patch numbers if there is at least one. */
/* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */
if (included_patches[0] != 0)
{
msg_puts(_("\nIncluded patches: "));
first = -1;
/* find last one */
for (i = 0; included_patches[i] != 0; ++i)
;
while (--i >= 0)
{
if (first < 0)
first = included_patches[i];
if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)
{
msg_puts(s);
s = ", ";
msg_outnum((long)first);
if (first != included_patches[i])
{
msg_puts("-");
msg_outnum((long)included_patches[i]);
}
first = -1;
}
}
}
/* Print the list of extra patch descriptions if there is at least one. */
if (extra_patches[0] != NULL)
{
msg_puts(_("\nExtra patches: "));
s = "";
for (i = 0; extra_patches[i] != NULL; ++i)
{
msg_puts(s);
s = ", ";
msg_puts(extra_patches[i]);
}
}
#ifdef MODIFIED_BY
msg_puts("\n");
msg_puts(_("Modified by "));
msg_puts(MODIFIED_BY);
#endif
#ifdef HAVE_PATHDEF
if (*compiled_user != NUL || *compiled_sys != NUL)
{
msg_puts(_("\nCompiled "));
if (*compiled_user != NUL)
{
msg_puts(_("by "));
msg_puts((char *)compiled_user);
}
if (*compiled_sys != NUL)
{
msg_puts("@");
msg_puts((char *)compiled_sys);
}
}
#endif
#ifdef FEAT_HUGE
msg_puts(_("\nHuge version "));
#else
# ifdef FEAT_BIG
msg_puts(_("\nBig version "));
# else
# ifdef FEAT_NORMAL
msg_puts(_("\nNormal version "));
# else
# ifdef FEAT_SMALL
msg_puts(_("\nSmall version "));
# else
msg_puts(_("\nTiny version "));
# endif
# endif
# endif
#endif
#ifndef FEAT_GUI
msg_puts(_("without GUI."));
#else
# ifdef FEAT_GUI_GTK
# ifdef USE_GTK3
msg_puts(_("with GTK3 GUI."));
# else
# ifdef FEAT_GUI_GNOME
msg_puts(_("with GTK2-GNOME GUI."));
# else
msg_puts(_("with GTK2 GUI."));
# endif
# endif
# else
# ifdef FEAT_GUI_MOTIF
msg_puts(_("with X11-Motif GUI."));
# else
# ifdef FEAT_GUI_ATHENA
# ifdef FEAT_GUI_NEXTAW
msg_puts(_("with X11-neXtaw GUI."));
# else
msg_puts(_("with X11-Athena GUI."));
# endif
# else
# ifdef FEAT_GUI_PHOTON
msg_puts(_("with Photon GUI."));
# else
# if defined(MSWIN)
msg_puts(_("with GUI."));
# else
# if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON
msg_puts(_("with Carbon GUI."));
# else
# if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX
msg_puts(_("with Cocoa GUI."));
# else
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
version_msg(_(" Features included (+) or not (-):\n"));
list_features();
#ifdef SYS_VIMRC_FILE
version_msg(_(" system vimrc file: \""));
version_msg(SYS_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE
version_msg(_(" user vimrc file: \""));
version_msg(USR_VIMRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE2
version_msg(_(" 2nd user vimrc file: \""));
version_msg(USR_VIMRC_FILE2);
version_msg("\"\n");
#endif
#ifdef USR_VIMRC_FILE3
version_msg(_(" 3rd user vimrc file: \""));
version_msg(USR_VIMRC_FILE3);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE
version_msg(_(" user exrc file: \""));
version_msg(USR_EXRC_FILE);
version_msg("\"\n");
#endif
#ifdef USR_EXRC_FILE2
version_msg(_(" 2nd user exrc file: \""));
version_msg(USR_EXRC_FILE2);
version_msg("\"\n");
#endif
#ifdef FEAT_GUI
# ifdef SYS_GVIMRC_FILE
version_msg(_(" system gvimrc file: \""));
version_msg(SYS_GVIMRC_FILE);
version_msg("\"\n");
# endif
version_msg(_(" user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE);
version_msg("\"\n");
# ifdef USR_GVIMRC_FILE2
version_msg(_("2nd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE2);
version_msg("\"\n");
# endif
# ifdef USR_GVIMRC_FILE3
version_msg(_("3rd user gvimrc file: \""));
version_msg(USR_GVIMRC_FILE3);
version_msg("\"\n");
# endif
#endif
version_msg(_(" defaults file: \""));
version_msg(VIM_DEFAULTS_FILE);
version_msg("\"\n");
#ifdef FEAT_GUI
# ifdef SYS_MENU_FILE
version_msg(_(" system menu file: \""));
version_msg(SYS_MENU_FILE);
version_msg("\"\n");
# endif
#endif
#ifdef HAVE_PATHDEF
if (*default_vim_dir != NUL)
{
version_msg(_(" fall-back for $VIM: \""));
version_msg((char *)default_vim_dir);
version_msg("\"\n");
}
if (*default_vimruntime_dir != NUL)
{
version_msg(_(" f-b for $VIMRUNTIME: \""));
version_msg((char *)default_vimruntime_dir);
version_msg("\"\n");
}
version_msg(_("Compilation: "));
version_msg((char *)all_cflags);
version_msg("\n");
#ifdef VMS
if (*compiler_version != NUL)
{
version_msg(_("Compiler: "));
version_msg((char *)compiler_version);
version_msg("\n");
}
#endif
version_msg(_("Linking: "));
version_msg((char *)all_lflags);
#endif
#ifdef DEBUG
version_msg("\n");
version_msg(_(" DEBUG BUILD"));
#endif
}
static void do_intro_line(int row, char_u *mesg, int add_version, int attr);
/*
* Show the intro message when not editing a file.
*/
void
maybe_intro_message(void)
{
if (BUFEMPTY()
&& curbuf->b_fname == NULL
&& firstwin->w_next == NULL
&& vim_strchr(p_shm, SHM_INTRO) == NULL)
intro_message(FALSE);
}
/*
* Give an introductory message about Vim.
* Only used when starting Vim on an empty file, without a file name.
* Or with the ":intro" command (for Sven :-).
*/
void
intro_message(
int colon) /* TRUE for ":intro" */
{
int i;
int row;
int blanklines;
int sponsor;
char *p;
static char *(lines[]) =
{
N_("VIM - Vi IMproved"),
"",
N_("version "),
N_("by Bram Moolenaar et al."),
#ifdef MODIFIED_BY
" ",
#endif
N_("Vim is open source and freely distributable"),
"",
N_("Help poor children in Uganda!"),
N_("type :help iccf<Enter> for information "),
"",
N_("type :q<Enter> to exit "),
N_("type :help<Enter> or <F1> for on-line help"),
N_("type :help version8<Enter> for version info"),
NULL,
"",
N_("Running in Vi compatible mode"),
N_("type :set nocp<Enter> for Vim defaults"),
N_("type :help cp-default<Enter> for info on this"),
};
#ifdef FEAT_GUI
static char *(gui_lines[]) =
{
NULL,
NULL,
NULL,
NULL,
#ifdef MODIFIED_BY
NULL,
#endif
NULL,
NULL,
NULL,
N_("menu Help->Orphans for information "),
NULL,
N_("Running modeless, typed text is inserted"),
N_("menu Edit->Global Settings->Toggle Insert Mode "),
N_(" for two modes "),
NULL,
NULL,
NULL,
N_("menu Edit->Global Settings->Toggle Vi Compatible"),
N_(" for Vim defaults "),
};
#endif
/* blanklines = screen height - # message lines */
blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1);
if (!p_cp)
blanklines += 4; /* add 4 for not showing "Vi compatible" message */
/* Don't overwrite a statusline. Depends on 'cmdheight'. */
if (p_ls > 1)
blanklines -= Rows - topframe->fr_height;
if (blanklines < 0)
blanklines = 0;
/* Show the sponsor and register message one out of four times, the Uganda
* message two out of four times. */
sponsor = (int)time(NULL);
sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);
/* start displaying the message lines after half of the blank lines */
row = blanklines / 2;
if ((row >= 2 && Columns >= 50) || colon)
{
for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i)
{
p = lines[i];
#ifdef FEAT_GUI
if (p_im && gui.in_use && gui_lines[i] != NULL)
p = gui_lines[i];
#endif
if (p == NULL)
{
if (!p_cp)
break;
continue;
}
if (sponsor != 0)
{
if (strstr(p, "children") != NULL)
p = sponsor < 0
? N_("Sponsor Vim development!")
: N_("Become a registered Vim user!");
else if (strstr(p, "iccf") != NULL)
p = sponsor < 0
? N_("type :help sponsor<Enter> for information ")
: N_("type :help register<Enter> for information ");
else if (strstr(p, "Orphans") != NULL)
p = N_("menu Help->Sponsor/Register for information ");
}
if (*p != NUL)
do_intro_line(row, (char_u *)_(p), i == 2, 0);
++row;
}
}
/* Make the wait-return message appear just below the text. */
if (colon)
msg_row = row;
}
static void
do_intro_line(
int row,
char_u *mesg,
int add_version,
int attr)
{
char_u vers[20];
int col;
char_u *p;
int l;
int clen;
#ifdef MODIFIED_BY
# define MODBY_LEN 150
char_u modby[MODBY_LEN];
if (*mesg == ' ')
{
vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1);
l = (int)STRLEN(modby);
vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);
mesg = modby;
}
#endif
/* Center the message horizontally. */
col = vim_strsize(mesg);
if (add_version)
{
STRCPY(vers, mediumVersion);
if (highest_patch())
{
/* Check for 9.9x or 9.9xx, alpha/beta version */
if (isalpha((int)vers[3]))
{
int len = (isalpha((int)vers[4])) ? 5 : 4;
sprintf((char *)vers + len, ".%d%s", highest_patch(),
mediumVersion + len);
}
else
sprintf((char *)vers + 3, ".%d", highest_patch());
}
col += (int)STRLEN(vers);
}
col = (Columns - col) / 2;
if (col < 0)
col = 0;
/* Split up in parts to highlight <> items differently. */
for (p = mesg; *p != NUL; p += l)
{
clen = 0;
for (l = 0; p[l] != NUL
&& (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)
{
if (has_mbyte)
{
clen += ptr2cells(p + l);
l += (*mb_ptr2len)(p + l) - 1;
}
else
clen += byte2cells(p[l]);
}
screen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);
col += clen;
}
/* Add the version number to the version line. */
if (add_version)
screen_puts(vers, row, col, 0);
}
/*
* ":intro": clear screen, display intro screen and wait for return.
*/
void
ex_intro(exarg_T *eap UNUSED)
{
screenclear();
intro_message(TRUE);
wait_return(TRUE);
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/bad_882_2 |
crossvul-cpp_data_bad_1103_0 | /* radare - LGPL - Copyright 2011-2019 - earada, pancake */
#include <r_core.h>
#include <r_config.h>
#include "r_util.h"
#include "r_util/r_time.h"
#define is_in_range(at, from, sz) ((at) >= (from) && (at) < ((from) + (sz)))
#define VA_FALSE 0
#define VA_TRUE 1
#define VA_NOREBASE 2
#define LOAD_BSS_MALLOC 0
#define IS_MODE_SET(mode) ((mode) & R_MODE_SET)
#define IS_MODE_SIMPLE(mode) ((mode) & R_MODE_SIMPLE)
#define IS_MODE_SIMPLEST(mode) ((mode) & R_MODE_SIMPLEST)
#define IS_MODE_JSON(mode) ((mode) & R_MODE_JSON)
#define IS_MODE_RAD(mode) ((mode) & R_MODE_RADARE)
#define IS_MODE_EQUAL(mode) ((mode) & R_MODE_EQUAL)
#define IS_MODE_NORMAL(mode) (!(mode))
#define IS_MODE_CLASSDUMP(mode) ((mode) & R_MODE_CLASSDUMP)
// dup from cmd_info
#define PAIR_WIDTH 9
#define bprintf if (binfile && binfile->rbin && binfile->rbin->verbose) eprintf
static void pair(const char *key, const char *val, int mode, bool last) {
if (!val || !*val) {
return;
}
if (IS_MODE_JSON (mode)) {
const char *lst = last ? "" : ",";
r_cons_printf ("\"%s\":%s%s", key, val, lst);
} else {
char ws[16];
const int keyl = strlen (key);
const int wl = (keyl > PAIR_WIDTH) ? 0 : PAIR_WIDTH - keyl;
memset (ws, ' ', wl);
ws[wl] = 0;
r_cons_printf ("%s%s%s\n", key, ws, val);
}
}
static void pair_bool(const char *key, bool val, int mode, bool last) {
pair (key, r_str_bool (val), mode, last);
}
static void pair_int(const char *key, int val, int mode, bool last) {
pair (key, sdb_fmt ("%d", val), mode, last);
}
static void pair_ut64(const char *key, ut64 val, int mode, bool last) {
pair (key, sdb_fmt ("%"PFMT64d, val), mode, last);
}
static char *__filterQuotedShell(const char *arg) {
r_return_val_if_fail (arg, NULL);
char *a = malloc (strlen (arg) + 1);
if (!a) {
return NULL;
}
char *b = a;
while (*arg) {
switch (*arg) {
case ' ':
case '=':
case '\r':
case '\n':
break;
default:
*b++ = *arg;
break;
}
arg++;
}
*b = 0;
return a;
}
// TODO: move into libr/util/name.c
static char *__filterShell(const char *arg) {
r_return_val_if_fail (arg, NULL);
char *a = malloc (strlen (arg) + 1);
if (!a) {
return NULL;
}
char *b = a;
while (*arg) {
switch (*arg) {
case '@':
case '`':
case '|':
case ';':
case '\n':
break;
default:
*b++ = *arg;
break;
}
arg++;
}
*b = 0;
return a;
}
static void pair_ut64x(const char *key, ut64 val, int mode, bool last) {
const char *str_val = IS_MODE_JSON (mode) ? sdb_fmt ("%"PFMT64d, val) : sdb_fmt ("0x%"PFMT64x, val);
pair (key, str_val, mode, last);
}
static void pair_str(const char *key, const char *val, int mode, int last) {
if (IS_MODE_JSON (mode)) {
if (!val) {
val = "";
}
char *encval = r_str_escape_utf8_for_json (val, -1);
if (encval) {
char *qs = r_str_newf ("\"%s\"", encval);
pair (key, qs, mode, last);
free (encval);
free (qs);
}
} else {
pair (key, val, mode, last);
}
}
#define STR(x) (x)? (x): ""
R_API int r_core_bin_set_cur(RCore *core, RBinFile *binfile);
static ut64 rva(RBin *bin, ut64 paddr, ut64 vaddr, int va) {
if (va == VA_TRUE) {
if (paddr != UT64_MAX) {
return r_bin_get_vaddr (bin, paddr, vaddr);
}
}
if (va == VA_NOREBASE) {
return vaddr;
}
return paddr;
}
R_API int r_core_bin_set_by_fd(RCore *core, ut64 bin_fd) {
if (r_bin_file_set_cur_by_fd (core->bin, bin_fd)) {
r_core_bin_set_cur (core, r_bin_cur (core->bin));
return true;
}
return false;
}
R_API int r_core_bin_set_by_name(RCore *core, const char * name) {
if (r_bin_file_set_cur_by_name (core->bin, name)) {
r_core_bin_set_cur (core, r_bin_cur (core->bin));
return true;
}
return false;
}
R_API int r_core_bin_set_env(RCore *r, RBinFile *binfile) {
r_return_val_if_fail (r, false);
RBinObject *binobj = binfile? binfile->o: NULL;
RBinInfo *info = binobj? binobj->info: NULL;
if (info) {
int va = info->has_va;
const char *arch = info->arch;
ut16 bits = info->bits;
ut64 baseaddr = r_bin_get_baddr (r->bin);
r_config_set_i (r->config, "bin.baddr", baseaddr);
sdb_num_add (r->sdb, "orig_baddr", baseaddr, 0);
r_config_set (r->config, "asm.arch", arch);
r_config_set_i (r->config, "asm.bits", bits);
r_config_set (r->config, "anal.arch", arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "anal.cpu", info->cpu);
} else {
r_config_set (r->config, "anal.cpu", arch);
}
r_asm_use (r->assembler, arch);
r_core_bin_info (r, R_CORE_BIN_ACC_ALL, R_MODE_SET, va, NULL, NULL);
r_core_bin_set_cur (r, binfile);
return true;
}
return false;
}
R_API int r_core_bin_set_cur(RCore *core, RBinFile *binfile) {
if (!core->bin) {
return false;
}
if (!binfile) {
// Find first available binfile
ut32 fd = r_core_file_cur_fd (core);
binfile = fd != (ut32)-1
? r_bin_file_find_by_fd (core->bin, fd)
: NULL;
if (!binfile) {
return false;
}
}
r_bin_file_set_cur_binfile (core->bin, binfile);
return true;
}
R_API int r_core_bin_refresh_strings(RCore *r) {
return r_bin_reset_strings (r->bin)? true: false;
}
static void _print_strings(RCore *r, RList *list, int mode, int va) {
bool b64str = r_config_get_i (r->config, "bin.b64str");
int minstr = r_config_get_i (r->config, "bin.minstr");
int maxstr = r_config_get_i (r->config, "bin.maxstr");
RBin *bin = r->bin;
RBinObject *obj = r_bin_cur_object (bin);
RListIter *iter;
RListIter *last_processed = NULL;
RBinString *string;
RBinSection *section;
char *q;
bin->minstrlen = minstr;
bin->maxstrlen = maxstr;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
if (IS_MODE_RAD (mode)) {
r_cons_println ("fs strings");
}
if (IS_MODE_SET (mode) && r_config_get_i (r->config, "bin.strings")) {
r_flag_space_set (r->flags, R_FLAGS_FS_STRINGS);
r_cons_break_push (NULL, NULL);
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("[Strings]\n");
r_cons_printf ("Num Paddr Vaddr Len Size Section Type String\n");
}
RBinString b64 = { 0 };
r_list_foreach (list, iter, string) {
const char *section_name, *type_string;
ut64 paddr, vaddr;
paddr = string->paddr;
vaddr = rva (r->bin, paddr, string->vaddr, va);
if (!r_bin_string_filter (bin, string->string, vaddr)) {
continue;
}
if (string->length < minstr) {
continue;
}
if (maxstr && string->length > maxstr) {
continue;
}
section = obj? r_bin_get_section_at (obj, paddr, 0): NULL;
section_name = section ? section->name : "";
type_string = r_bin_string_type (string->type);
if (b64str) {
ut8 *s = r_base64_decode_dyn (string->string, -1);
if (s && *s && IS_PRINTABLE (*s)) {
// TODO: add more checks
free (b64.string);
memcpy (&b64, string, sizeof (b64));
b64.string = (char *)s;
b64.size = strlen (b64.string);
string = &b64;
}
}
if (IS_MODE_SET (mode)) {
char *f_name, *f_realname, *str;
if (r_cons_is_breaked ()) {
break;
}
r_meta_add (r->anal, R_META_TYPE_STRING, vaddr, vaddr + string->size, string->string);
f_name = strdup (string->string);
r_name_filter (f_name, -1);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
f_realname = r_str_newf ("%s.\"%s\"", r->bin->prefix, string->string);
} else {
str = r_str_newf ("str.%s", f_name);
f_realname = r_str_newf ("\"%s\"", string->string);
}
RFlagItem *flag = r_flag_set (r->flags, str, vaddr, string->size);
r_flag_item_set_realname (flag, f_realname);
free (str);
free (f_name);
free (f_realname);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%"PFMT64x" %d %d %s\n", vaddr,
string->size, string->length, string->string);
} else if (IS_MODE_SIMPLEST (mode)) {
r_cons_println (string->string);
} else if (IS_MODE_JSON (mode)) {
int *block_list;
q = r_base64_encode_dyn (string->string, -1);
r_cons_printf ("%s{\"vaddr\":%"PFMT64u
",\"paddr\":%"PFMT64u",\"ordinal\":%d"
",\"size\":%d,\"length\":%d,\"section\":\"%s\","
"\"type\":\"%s\",\"string\":\"%s\"",
last_processed ? ",": "",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string, q);
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string, -1, NULL);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't include block list if
just Basic Latin (0x00 - 0x7F) */
R_FREE (block_list);
break;
}
int *block_ptr = block_list;
r_cons_printf (",\"blocks\":[");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *utfName = r_utf_block_name (*block_ptr);
r_cons_printf ("\"%s\"", utfName? utfName: "");
}
r_cons_printf ("]");
R_FREE (block_list);
}
}
r_cons_printf ("}");
free (q);
} else if (IS_MODE_RAD (mode)) {
char *f_name = strdup (string->string);
r_name_filter (f_name, R_FLAG_NAME_SIZE);
char *str = (r->bin->prefix)
? r_str_newf ("%s.str.%s", r->bin->prefix, f_name)
: r_str_newf ("str.%s", f_name);
r_cons_printf ("f %s %"PFMT64d" 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
str, string->size, vaddr,
string->size, vaddr);
free (str);
free (f_name);
} else {
int *block_list;
char *str = string->string;
char *no_dbl_bslash_str = NULL;
if (!r->print->esc_bslash) {
char *ptr;
for (ptr = str; *ptr; ptr++) {
if (*ptr != '\\') {
continue;
}
if (*(ptr + 1) == '\\') {
if (!no_dbl_bslash_str) {
no_dbl_bslash_str = strdup (str);
if (!no_dbl_bslash_str) {
break;
}
ptr = no_dbl_bslash_str + (ptr - str);
}
memmove (ptr + 1, ptr + 2, strlen (ptr + 2) + 1);
}
}
if (no_dbl_bslash_str) {
str = no_dbl_bslash_str;
}
}
r_cons_printf ("%03u 0x%08" PFMT64x " 0x%08" PFMT64x " %3u %3u (%s) %5s %s",
string->ordinal, paddr, vaddr,
string->length, string->size,
section_name, type_string, str);
if (str == no_dbl_bslash_str) {
R_FREE (str);
}
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string, -1, NULL);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't show block list if
just Basic Latin (0x00 - 0x7F) */
break;
}
int *block_ptr = block_list;
r_cons_printf (" blocks=");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *name = r_utf_block_name (*block_ptr);
r_cons_printf ("%s", name? name: "");
}
free (block_list);
}
break;
}
r_cons_printf ("\n");
}
last_processed = iter;
}
R_FREE (b64.string);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
}
if (IS_MODE_SET (mode)) {
r_cons_break_pop ();
}
}
static bool bin_raw_strings(RCore *r, int mode, int va) {
RBinFile *bf = r_bin_cur (r->bin);
bool new_bf = false;
if (bf && strstr (bf->file, "malloc://")) {
//sync bf->buf to search string on it
ut8 *tmp = R_NEWS (ut8, bf->size);
if (!tmp) {
return false;
}
r_io_read_at (r->io, 0, tmp, bf->size);
r_buf_write_at (bf->buf, 0, tmp, bf->size);
}
if (!r->file) {
eprintf ("Core file not open\n");
if (IS_MODE_JSON (mode)) {
r_cons_print ("[]");
}
return false;
}
if (!bf) {
bf = R_NEW0 (RBinFile);
if (!bf) {
return false;
}
RIODesc *desc = r_io_desc_get (r->io, r->file->fd);
if (!desc) {
free (bf);
return false;
}
bf->file = strdup (desc->name);
bf->size = r_io_desc_size (desc);
if (bf->size == UT64_MAX) {
free (bf);
return false;
}
bf->buf = r_buf_new_with_io (&r->bin->iob, r->file->fd);
bf->o = NULL;
bf->rbin = r->bin;
new_bf = true;
va = false;
}
RList *l = r_bin_raw_strings (bf, 0);
_print_strings (r, l, mode, va);
r_list_free (l);
if (new_bf) {
r_buf_free (bf->buf);
bf->buf = NULL;
bf->id = -1;
r_bin_file_free (bf);
}
return true;
}
static bool bin_strings(RCore *r, int mode, int va) {
RList *list;
RBinFile *binfile = r_bin_cur (r->bin);
RBinPlugin *plugin = r_bin_file_cur_plugin (binfile);
int rawstr = r_config_get_i (r->config, "bin.rawstr");
if (!binfile) {
return false;
}
if (!r_config_get_i (r->config, "bin.strings")) {
return false;
}
if (!plugin) {
return false;
}
if (plugin->info && plugin->name) {
if (strcmp (plugin->name, "any") == 0 && !rawstr) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
}
if (!(list = r_bin_get_strings (r->bin))) {
return false;
}
_print_strings (r, list, mode, va);
return true;
}
static const char* get_compile_time(Sdb *binFileSdb) {
Sdb *info_ns = sdb_ns (binFileSdb, "info", false);
const char *timeDateStamp_string = sdb_const_get (info_ns,
"image_file_header.TimeDateStamp_string", 0);
return timeDateStamp_string;
}
static bool is_executable(RBinObject *obj) {
RListIter *it;
RBinSection* sec;
r_return_val_if_fail (obj, false);
if (obj->info && obj->info->arch) {
return true;
}
r_list_foreach (obj->sections, it, sec) {
if (sec->perm & R_PERM_X) {
return true;
}
}
return false;
}
static void sdb_concat_by_path(Sdb *s, const char *path) {
Sdb *db = sdb_new (0, path, 0);
sdb_merge (s, db);
sdb_close (db);
sdb_free (db);
}
R_API void r_core_anal_type_init(RCore *core) {
r_return_if_fail (core && core->anal);
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
int bits = core->assembler->bits;
Sdb *types = core->anal->sdb_types;
// make sure they are empty this is initializing
sdb_reset (types);
const char *anal_arch = r_config_get (core->config, "anal.arch");
const char *os = r_config_get (core->config, "asm.os");
// spaguetti ahead
const char *dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types.sdb"), dir_prefix);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s.sdb"),
dir_prefix, anal_arch);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s.sdb"),
dir_prefix, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%d.sdb"),
dir_prefix, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%d.sdb"),
dir_prefix, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%d.sdb"),
dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%s.sdb"),
dir_prefix, anal_arch, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%s-%d.sdb"),
dir_prefix, anal_arch, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
}
static int save_ptr(void *p, const char *k, const char *v) {
Sdb *sdbs[2];
sdbs[0] = ((Sdb**) p)[0];
sdbs[1] = ((Sdb**) p)[1];
if (!strncmp (v, "cc", strlen ("cc") + 1)) {
const char *x = sdb_const_get (sdbs[1], sdb_fmt ("cc.%s.name", k), 0);
char *tmp = sdb_fmt ("%p", x);
sdb_set (sdbs[0], tmp, x, 0);
}
return 1;
}
R_API void r_core_anal_cc_init(RCore *core) {
Sdb *sdbs[2] = {
sdb_new0 (),
core->anal->sdb_cc
};
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
//save pointers and values stored inside them
//to recover from freeing heeps
const char *defaultcc = sdb_const_get (sdbs[1], "default.cc", 0);
sdb_set (sdbs[0], sdb_fmt ("0x%08"PFMT64x, r_num_get (NULL, defaultcc)), defaultcc, 0);
sdb_foreach (core->anal->sdb_cc, save_ptr, sdbs);
sdb_reset (core->anal->sdb_cc);
const char *anal_arch = r_config_get (core->config, "anal.arch");
int bits = core->anal->bits;
char *dbpath = sdb_fmt ("%s/"R2_SDB_FCNSIGN"/cc-%s-%d.sdb", dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (core->anal->sdb_cc, dbpath);
}
//restore all freed CC or replace with new default cc
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
const char *cc = NULL;
if (fcn->cc) {
char *ptr = sdb_fmt ("%p", fcn->cc);
cc = sdb_const_get (sdbs[0], ptr, 0);
}
if (!cc) {
cc = r_anal_cc_default (core->anal);
}
fcn->cc = r_str_const (cc);
}
sdb_close (sdbs[0]);
sdb_free (sdbs[0]);
}
static int bin_info(RCore *r, int mode, ut64 laddr) {
int i, j, v;
char str[R_FLAG_NAME_SIZE];
RBinInfo *info = r_bin_get_info (r->bin);
RBinFile *bf = r_bin_cur (r->bin);
if (!bf) {
return false;
}
RBinObject *obj = bf->o;
const char *compiled = NULL;
bool havecode;
if (!bf || !info || !obj) {
if (mode & R_MODE_JSON) {
r_cons_printf ("{}");
}
return false;
}
havecode = is_executable (obj) | (obj->entries != NULL);
compiled = get_compile_time (bf->sdb);
if (IS_MODE_SET (mode)) {
r_config_set (r->config, "file.type", info->rclass);
r_config_set (r->config, "cfg.bigendian",
info->big_endian ? "true" : "false");
if (info->rclass && !strcmp (info->rclass, "fs")) {
// r_config_set (r->config, "asm.arch", info->arch);
// r_core_seek (r, 0, 1);
// eprintf ("m /root %s 0", info->arch);
// r_core_cmdf (r, "m /root hfs @ 0", info->arch);
} else {
if (info->lang) {
r_config_set (r->config, "bin.lang", info->lang);
}
r_config_set (r->config, "asm.os", info->os);
if (info->rclass && !strcmp (info->rclass, "pe")) {
r_config_set (r->config, "anal.cpp.abi", "msvc");
} else {
r_config_set (r->config, "anal.cpp.abi", "itanium");
}
r_config_set (r->config, "asm.arch", info->arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "asm.cpu", info->cpu);
}
r_config_set (r->config, "anal.arch", info->arch);
snprintf (str, R_FLAG_NAME_SIZE, "%i", info->bits);
r_config_set (r->config, "asm.bits", str);
r_config_set (r->config, "asm.dwarf",
(R_BIN_DBG_STRIPPED & info->dbg_info) ? "false" : "true");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_config_set_i (r->config, "asm.pcalign", v);
}
}
r_core_anal_type_init (r);
r_core_anal_cc_init (r);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("arch %s\n", info->arch);
if (info->cpu && *info->cpu) {
r_cons_printf ("cpu %s\n", info->cpu);
}
r_cons_printf ("bits %d\n", info->bits);
r_cons_printf ("os %s\n", info->os);
r_cons_printf ("endian %s\n", info->big_endian? "big": "little");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
r_cons_printf ("minopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
r_cons_printf ("maxopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_cons_printf ("pcalign %d\n", v);
}
} else if (IS_MODE_RAD (mode)) {
if (info->type && !strcmp (info->type, "fs")) {
r_cons_printf ("e file.type=fs\n");
r_cons_printf ("m /root %s 0\n", info->arch);
} else {
r_cons_printf ("e cfg.bigendian=%s\n"
"e asm.bits=%i\n"
"e asm.dwarf=%s\n",
r_str_bool (info->big_endian),
info->bits,
r_str_bool (R_BIN_DBG_STRIPPED &info->dbg_info));
if (info->lang && *info->lang) {
r_cons_printf ("e bin.lang=%s\n", info->lang);
}
if (info->rclass && *info->rclass) {
r_cons_printf ("e file.type=%s\n",
info->rclass);
}
if (info->os) {
r_cons_printf ("e asm.os=%s\n", info->os);
}
if (info->arch) {
r_cons_printf ("e asm.arch=%s\n", info->arch);
}
if (info->cpu && *info->cpu) {
r_cons_printf ("e asm.cpu=%s\n", info->cpu);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_cons_printf ("e asm.pcalign=%d\n", v);
}
}
} else {
// XXX: if type is 'fs' show something different?
char *tmp_buf;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{");
}
pair_str ("arch", info->arch, mode, false);
if (info->cpu && *info->cpu) {
pair_str ("cpu", info->cpu, mode, false);
}
pair_ut64x ("baddr", r_bin_get_baddr (r->bin), mode, false);
pair_ut64 ("binsz", r_bin_get_size (r->bin), mode, false);
pair_str ("bintype", info->rclass, mode, false);
pair_int ("bits", info->bits, mode, false);
pair_bool ("canary", info->has_canary, mode, false);
if (info->has_retguard != -1) {
pair_bool ("retguard", info->has_retguard, mode, false);
}
pair_str ("class", info->bclass, mode, false);
if (info->actual_checksum) {
/* computed checksum */
pair_str ("cmp.csum", info->actual_checksum, mode, false);
}
pair_str ("compiled", compiled, mode, false);
pair_str ("compiler", info->compiler, mode, false);
pair_bool ("crypto", info->has_crypto, mode, false);
pair_str ("dbg_file", info->debug_file_name, mode, false);
pair_str ("endian", info->big_endian ? "big" : "little", mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
tmp_buf = sdb_get (bf->sdb, "mdmp.flags", 0);
if (tmp_buf) {
pair_str ("flags", tmp_buf, mode, false);
free (tmp_buf);
}
}
pair_bool ("havecode", havecode, mode, false);
if (info->claimed_checksum) {
/* checksum specified in header */
pair_str ("hdr.csum", info->claimed_checksum, mode, false);
}
pair_str ("guid", info->guid, mode, false);
pair_str ("intrp", info->intrp, mode, false);
pair_ut64x ("laddr", laddr, mode, false);
pair_str ("lang", info->lang, mode, false);
pair_bool ("linenum", R_BIN_DBG_LINENUMS & info->dbg_info, mode, false);
pair_bool ("lsyms", R_BIN_DBG_SYMS & info->dbg_info, mode, false);
pair_str ("machine", info->machine, mode, false);
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
pair_int ("maxopsz", v, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
pair_int ("minopsz", v, mode, false);
}
pair_bool ("nx", info->has_nx, mode, false);
pair_str ("os", info->os, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
pair_bool ("overlay", info->pe_overlay, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
pair_int ("pcalign", v, mode, false);
}
pair_bool ("pic", info->has_pi, mode, false);
pair_bool ("relocs", R_BIN_DBG_RELOCS & info->dbg_info, mode, false);
Sdb *sdb_info = sdb_ns (obj->kv, "info", false);
tmp_buf = sdb_get (sdb_info, "elf.relro", 0);
if (tmp_buf) {
pair_str ("relro", tmp_buf, mode, false);
free (tmp_buf);
}
pair_str ("rpath", info->rpath, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
//this should be moved if added to mach0 (or others)
pair_bool ("signed", info->signature, mode, false);
}
pair_bool ("sanitiz", info->has_sanitizers, mode, false);
pair_bool ("static", r_bin_is_static (r->bin), mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
v = sdb_num_get (bf->sdb, "mdmp.streams", 0);
if (v != -1) {
pair_int ("streams", v, mode, false);
}
}
pair_bool ("stripped", R_BIN_DBG_STRIPPED & info->dbg_info, mode, false);
pair_str ("subsys", info->subsystem, mode, false);
pair_bool ("va", info->has_va, mode, true);
if (IS_MODE_JSON (mode)) {
r_cons_printf (",\"checksums\":{");
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
ut8 *tmp = R_NEWS (ut8, h->to);
if (!tmp) {
return false;
}
r_buf_read_at (bf->buf, h->from, tmp, h->to);
int len = r_hash_calculate (rh, hash, tmp, h->to);
free (tmp);
if (len < 1) {
eprintf ("Invalid checksum length\n");
}
r_hash_free (rh);
r_cons_printf ("%s\"%s\":{\"hex\":\"", i?",": "", h->type);
// r_cons_printf ("%s\t%d-%dc\t", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_printf ("\"}");
}
r_cons_printf ("}");
} else {
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
ut8 *tmp = R_NEWS (ut8, h->to);
if (!tmp) {
return false;
}
r_buf_read_at (bf->buf, h->from, tmp, h->to);
int len = r_hash_calculate (rh, hash, tmp, h->to);
free (tmp);
if (len < 1) {
eprintf ("Invalid wtf\n");
}
r_hash_free (rh);
r_cons_printf ("%s %d-%dc ", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_newline ();
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("}");
}
}
const char *dir_prefix = r_config_get (r->config, "dir.prefix");
char *spath = sdb_fmt ("%s/"R2_SDB_FCNSIGN"/spec.sdb", dir_prefix);
if (r_file_exists (spath)) {
sdb_concat_by_path (r->anal->sdb_fmts, spath);
}
return true;
}
static int bin_dwarf(RCore *core, int mode) {
RBinDwarfRow *row;
RListIter *iter;
RList *list = NULL;
if (!r_config_get_i (core->config, "bin.dbginfo")) {
return false;
}
RBinFile *binfile = r_bin_cur (core->bin);
RBinPlugin * plugin = r_bin_file_cur_plugin (binfile);
if (!binfile) {
return false;
}
if (plugin && plugin->lines) {
list = plugin->lines (binfile);
} else if (core->bin) {
// TODO: complete and speed-up support for dwarf
RBinDwarfDebugAbbrev *da = NULL;
da = r_bin_dwarf_parse_abbrev (core->bin, mode);
r_bin_dwarf_parse_info (da, core->bin, mode);
r_bin_dwarf_parse_aranges (core->bin, mode);
list = r_bin_dwarf_parse_line (core->bin, mode);
r_bin_dwarf_free_debug_abbrev (da);
free (da);
}
if (!list) {
return false;
}
r_cons_break_push (NULL, NULL);
/* cache file:line contents */
const char *lastFile = NULL;
int *lastFileLines = NULL;
char *lastFileContents = NULL;
int lastFileLinesCount = 0;
/* ugly dupe for speedup */
const char *lastFile2 = NULL;
int *lastFileLines2 = NULL;
char *lastFileContents2 = NULL;
int lastFileLinesCount2 = 0;
const char *lf = NULL;
int *lfl = NULL;
char *lfc = NULL;
int lflc = 0;
//TODO we should need to store all this in sdb, or do a filecontentscache in libr/util
//XXX this whole thing has leaks
r_list_foreach (list, iter, row) {
if (r_cons_is_breaked ()) {
break;
}
if (mode) {
// TODO: use 'Cl' instead of CC
const char *path = row->file;
if (!lastFile || strcmp (path, lastFile)) {
if (lastFile && lastFile2 && !strcmp (path, lastFile2)) {
lf = lastFile;
lfl = lastFileLines;
lfc = lastFileContents;
lflc = lastFileLinesCount;
lastFile = lastFile2;
lastFileLines = lastFileLines2;
lastFileContents = lastFileContents2;
lastFileLinesCount = lastFileLinesCount2;
lastFile2 = lf;
lastFileLines2 = lfl;
lastFileContents2 = lfc;
lastFileLinesCount2 = lflc;
} else {
lastFile2 = lastFile;
lastFileLines2 = lastFileLines;
lastFileContents2 = lastFileContents;
lastFileLinesCount2 = lastFileLinesCount;
lastFile = path;
lastFileContents = r_file_slurp (path, NULL);
if (lastFileContents) {
lastFileLines = r_str_split_lines (lastFileContents, &lastFileLinesCount);
}
}
}
char *line = NULL;
//r_file_slurp_line (path, row->line - 1, 0);
if (lastFileLines && lastFileContents) {
int nl = row->line - 1;
if (nl >= 0 && nl < lastFileLinesCount) {
line = strdup (lastFileContents + lastFileLines[nl]);
}
} else {
line = NULL;
}
if (line) {
r_str_filter (line, strlen (line));
line = r_str_replace (line, "\"", "\\\"", 1);
line = r_str_replace (line, "\\\\", "\\", 1);
}
bool chopPath = !r_config_get_i (core->config, "dir.dwarf.abspath");
char *file = strdup (row->file);
if (chopPath) {
const char *slash = r_str_lchr (file, '/');
if (slash) {
memmove (file, slash + 1, strlen (slash));
}
}
// TODO: implement internal : if ((mode & R_MODE_SET))
if ((mode & R_MODE_SET)) {
// TODO: use CL here.. but its not necessary.. so better not do anything imho
// r_core_cmdf (core, "CL %s:%d 0x%08"PFMT64x, file, (int)row->line, row->address);
#if 0
char *cmt = r_str_newf ("%s:%d %s", file, (int)row->line, line? line: "");
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, row->address, cmt);
free (cmt);
#endif
} else {
r_cons_printf ("CL %s:%d 0x%08" PFMT64x "\n",
file, (int)row->line,
row->address);
r_cons_printf ("\"CC %s:%d %s\"@0x%" PFMT64x
"\n",
file, row->line,
line ? line : "", row->address);
}
free (file);
free (line);
} else {
r_cons_printf ("0x%08" PFMT64x "\t%s\t%d\n",
row->address, row->file, row->line);
}
}
r_cons_break_pop ();
R_FREE (lastFileContents);
R_FREE (lastFileContents2);
// this list is owned by rbin, not us, we shouldn't free it
// r_list_free (list);
free (lastFileLines);
return true;
}
R_API int r_core_pdb_info(RCore *core, const char *file, ut64 baddr, int mode) {
R_PDB pdb = R_EMPTY;
pdb.cb_printf = r_cons_printf;
if (!init_pdb_parser (&pdb, file)) {
return false;
}
if (!pdb.pdb_parse (&pdb)) {
eprintf ("pdb was not parsed\n");
pdb.finish_pdb_parse (&pdb);
return false;
}
if (mode == R_MODE_JSON) {
r_cons_printf ("[");
}
switch (mode) {
case R_MODE_SET:
mode = 's';
r_core_cmd0 (core, ".iP*");
return true;
case R_MODE_JSON:
mode = 'j';
break;
case '*':
case 1:
mode = 'r';
break;
default:
mode = 'd'; // default
break;
}
pdb.print_types (&pdb, mode);
if (mode == 'j') {
r_cons_printf (",");
}
pdb.print_gvars (&pdb, baddr, mode);
if (mode == 'j') {
r_cons_printf ("]");
}
pdb.finish_pdb_parse (&pdb);
return true;
}
static int bin_pdb(RCore *core, int mode) {
ut64 baddr = r_bin_get_baddr (core->bin);
return r_core_pdb_info (core, core->bin->file, baddr, mode);
}
static int srclineCmp(const void *a, const void *b) {
return r_str_cmp (a, b, -1);
}
static int bin_source(RCore *r, int mode) {
RList *final_list = r_list_new ();
RBinFile * binfile = r->bin->cur;
if (!binfile) {
bprintf ("[Error bin file]\n");
r_list_free (final_list);
return false;
}
SdbListIter *iter;
RListIter *iter2;
char* srcline;
SdbKv *kv;
SdbList *ls = sdb_foreach_list (binfile->sdb_addrinfo, false);
ls_foreach (ls, iter, kv) {
char *v = sdbkv_value (kv);
RList *list = r_str_split_list (v, "|", 0);
srcline = r_list_get_bottom (list);
if (srcline) {
if (!strstr (srcline, "0x")){
r_list_append (final_list, srcline);
}
}
r_list_free (list);
}
r_cons_printf ("[Source file]\n");
RList *uniqlist = r_list_uniq (final_list, srclineCmp);
r_list_foreach (uniqlist, iter2, srcline) {
r_cons_printf ("%s\n", srcline);
}
r_list_free (uniqlist);
r_list_free (final_list);
return true;
}
static int bin_main(RCore *r, int mode, int va) {
RBinAddr *binmain = r_bin_get_sym (r->bin, R_BIN_SYM_MAIN);
ut64 addr;
if (!binmain) {
return false;
}
addr = va ? r_bin_a2b (r->bin, binmain->vaddr) : binmain->paddr;
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
r_flag_set (r->flags, "main", addr, r->blocksize);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("%"PFMT64d, addr);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
r_cons_printf ("f main @ 0x%08"PFMT64x"\n", addr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"vaddr\":%" PFMT64d
",\"paddr\":%" PFMT64d "}", addr, binmain->paddr);
} else {
r_cons_printf ("[Main]\n");
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x"\n",
addr, binmain->paddr);
}
return true;
}
static inline bool is_initfini(RBinAddr *entry) {
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
return true;
default:
return false;
}
}
static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RListIter *last_processed = NULL;
RBinAddr *entry = NULL;
int i = 0, init_i = 0, fini_i = 0, preinit_i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 hpaddr = UT64_MAX;
ut64 hvaddr = UT64_MAX;
if (mode != R_MODE_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
if (entry->hpaddr) {
hpaddr = entry->hpaddr;
if (entry->hvaddr) {
hvaddr = rva (r->bin, hpaddr, entry->hvaddr, va);
}
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
const char *hpaddr_key = (entry->type == R_BIN_ENTRY_TYPE_PROGRAM)
? "haddr" : "hpaddr";
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry.init%i", init_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry.fini%i", fini_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry.preinit%i", preinit_i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
if (is_initfini (entry) && hvaddr != UT64_MAX) {
r_meta_add (r->anal, R_META_TYPE_DATA, hvaddr,
hvaddr + entry->bits / 8, NULL);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64u ","
"\"paddr\":%" PFMT64u ","
"\"baddr\":%" PFMT64u ","
"\"laddr\":%" PFMT64u ",",
last_processed ? "," : "", at, paddr, baddr, laddr);
if (hvaddr != UT64_MAX) {
r_cons_printf ("\"hvaddr\":%" PFMT64u ",", hvaddr);
}
r_cons_printf ("\"%s\":%" PFMT64u ","
"\"type\":\"%s\"}",
hpaddr_key, hpaddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry.init%i", init_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry.fini%i", fini_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry.preinit%i", preinit_i);
} else {
name = r_str_newf ("entry%i", i);
}
char *n = __filterQuotedShell (name);
r_cons_printf ("\"f %s 1 0x%08"PFMT64x"\"\n", n, at);
r_cons_printf ("\"f %s_%s 1 0x%08"PFMT64x"\"\n", n, hpaddr_key, hpaddr);
r_cons_printf ("\"s %s\"\n", n);
free (n);
free (name);
} else {
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x, at, paddr);
if (is_initfini (entry) && hvaddr != UT64_MAX) {
r_cons_printf (" hvaddr=0x%08"PFMT64x, hvaddr);
}
r_cons_printf (" %s=", hpaddr_key);
if (hpaddr == UT64_MAX) {
r_cons_printf ("%"PFMT64d, hpaddr);
} else {
r_cons_printf ("0x%08"PFMT64x, hpaddr);
}
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM && hvaddr != UT64_MAX) {
r_cons_printf (" hvaddr=0x%08"PFMT64x, hvaddr);
}
r_cons_printf (" type=%s\n", type);
}
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
init_i++;
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
fini_i++;
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
preinit_i++;
} else {
i++;
}
last_processed = iter;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", init_i + fini_i + preinit_i + i);
}
return true;
}
static const char *bin_reloc_type_name(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return reloc->additive ? "ADD_" #T : "SET_" #T
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return "UNKNOWN";
#undef CASE
}
static ut8 bin_reloc_size(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return (T) / 8
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return 0;
#undef CASE
}
static char *resolveModuleOrdinal(Sdb *sdb, const char *module, int ordinal) {
Sdb *db = sdb;
char *foo = sdb_get (db, sdb_fmt ("%d", ordinal), 0);
return (foo && *foo) ? foo : NULL;
}
static char *get_reloc_name(RCore *r, RBinReloc *reloc, ut64 addr) {
char *reloc_name = NULL;
char *demangled_name = NULL;
const char *lang = r_config_get (r->config, "bin.lang");
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
if (reloc->import && reloc->import->name) {
if (bin_demangle) {
demangled_name = r_bin_demangle (r->bin->cur, lang, reloc->import->name, addr, keep_lib);
}
reloc_name = sdb_fmt ("reloc.%s_%d", demangled_name ? demangled_name : reloc->import->name,
(int)(addr & 0xff));
if (!reloc_name) {
free (demangled_name);
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->symbol && reloc->symbol->name) {
if (bin_demangle) {
demangled_name = r_bin_demangle (r->bin->cur, lang, reloc->symbol->name, addr, keep_lib);
}
reloc_name = sdb_fmt ("reloc.%s_%d", demangled_name ? demangled_name : reloc->symbol->name,
(int)(addr & 0xff));
if (!reloc_name) {
free (demangled_name);
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->is_ifunc) {
// addend is the function pointer for the resolving ifunc
reloc_name = sdb_fmt ("reloc.ifunc_%"PFMT64x, reloc->addend);
} else {
// TODO(eddyb) implement constant relocs.
}
free (demangled_name);
return reloc_name;
}
static void set_bin_relocs(RCore *r, RBinReloc *reloc, ut64 addr, Sdb **db, char **sdb_module) {
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
const char *lang = r_config_get (r->config, "bin.lang");
char *reloc_name, *demname = NULL;
bool is_pe = true;
int is_sandbox = r_sandbox_enable (0);
if (reloc->import && reloc->import->name[0]) {
char str[R_FLAG_NAME_SIZE];
RFlagItem *fi;
if (is_pe && !is_sandbox && strstr (reloc->import->name, "Ordinal")) {
const char *TOKEN = ".dll_Ordinal_";
char *module = strdup (reloc->import->name);
char *import = strstr (module, TOKEN);
r_str_case (module, false);
if (import) {
char *filename = NULL;
int ordinal;
*import = 0;
import += strlen (TOKEN);
ordinal = atoi (import);
if (!*sdb_module || strcmp (module, *sdb_module)) {
sdb_free (*db);
*db = NULL;
free (*sdb_module);
*sdb_module = strdup (module);
/* always lowercase */
filename = sdb_fmt ("%s.sdb", module);
r_str_case (filename, false);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
} else {
const char *dirPrefix = r_sys_prefix (NULL);
filename = sdb_fmt (R_JOIN_4_PATHS ("%s", R2_SDB_FORMAT, "dll", "%s.sdb"),
dirPrefix, module);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
}
}
}
if (*db) {
// ordinal-1 because we enumerate starting at 0
char *symname = resolveModuleOrdinal (*db, module, ordinal - 1); // uses sdb_get
if (symname) {
if (r->bin->prefix) {
reloc->import->name = r_str_newf
("%s.%s.%s", r->bin->prefix, module, symname);
} else {
reloc->import->name = r_str_newf
("%s.%s", module, symname);
}
R_FREE (symname);
}
}
}
free (module);
r_anal_hint_set_size (r->anal, reloc->vaddr, 4);
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr+4, NULL);
}
reloc_name = reloc->import->name;
if (r->bin->prefix) {
snprintf (str, R_FLAG_NAME_SIZE, "%s.reloc.%s", r->bin->prefix, reloc_name);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "reloc.%s", reloc_name);
}
if (bin_demangle) {
demname = r_bin_demangle (r->bin->cur, lang, str, addr, keep_lib);
if (demname) {
snprintf (str, R_FLAG_NAME_SIZE, "reloc.%s", demname);
}
}
r_name_filter (str, 0);
fi = r_flag_set (r->flags, str, addr, bin_reloc_size (reloc));
if (demname) {
char *realname;
if (r->bin->prefix) {
realname = sdb_fmt ("%s.reloc.%s", r->bin->prefix, demname);
} else {
realname = sdb_fmt ("reloc.%s", demname);
}
r_flag_item_set_realname (fi, realname);
}
} else {
char *reloc_name = get_reloc_name (r, reloc, addr);
if (reloc_name) {
r_flag_set (r->flags, reloc_name, addr, bin_reloc_size (reloc));
} else {
// eprintf ("Cannot find a name for 0x%08"PFMT64x"\n", addr);
}
}
}
/* Define new data at relocation address if it's not in an executable section */
static void add_metadata(RCore *r, RBinReloc *reloc, ut64 addr, int mode) {
RBinFile * binfile = r->bin->cur;
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
int cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (cdsz == 0) {
return;
}
RIOMap *map = r_io_map_get (r->io, addr);
if (!map || map ->perm & R_PERM_X) {
return;
}
if (IS_MODE_SET (mode)) {
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr + cdsz, NULL);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("Cd %d @ 0x%08" PFMT64x "\n", cdsz, addr);
}
}
static bool is_section_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
if (!s || *s->name) {
return false;
}
return (s->type && !strcmp (s->type, R_BIN_TYPE_SECTION_STR));
}
static bool is_special_symbol(RBinSymbol *s) {
return s->type && !strcmp (s->type, R_BIN_TYPE_SPECIAL_SYM_STR);
}
static bool is_section_reloc(RBinReloc *r) {
return is_section_symbol (r->symbol);
}
static bool is_file_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
return (s && s->type && !strcmp (s->type, R_BIN_TYPE_FILE_STR));
}
static bool is_file_reloc(RBinReloc *r) {
return is_file_symbol (r->symbol);
}
static int bin_relocs(RCore *r, int mode, int va) {
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
const char *lang = r_config_get (r->config, "bin.lang");
RBIter iter;
RBinReloc *reloc = NULL;
Sdb *db = NULL;
PJ *pj = NULL;
char *sdb_module = NULL;
int i = 0;
R_TIME_BEGIN;
va = VA_TRUE; // XXX relocs always vaddr?
//this has been created for reloc object files
RBNode *relocs = r_bin_patch_relocs (r->bin);
if (!relocs) {
relocs = r_bin_get_relocs (r->bin);
}
if (IS_MODE_RAD (mode)) {
r_cons_println ("fs relocs");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Relocations]");
} else if (IS_MODE_JSON (mode)) {
// start a new JSON object
pj = pj_new ();
if (pj) {
pj_a (pj);
}
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_RELOCS);
}
r_rbtree_foreach (relocs, iter, reloc, RBinReloc, vrb) {
ut64 addr = rva (r->bin, reloc->paddr, reloc->vaddr, va);
if (IS_MODE_SET (mode) && (is_section_reloc (reloc) || is_file_reloc (reloc))) {
/*
* Skip section reloc because they will have their own flag.
* Skip also file reloc because not useful for now.
*/
} else if (IS_MODE_SET (mode)) {
set_bin_relocs (r, reloc, addr, &db, &sdb_module);
add_metadata (r, reloc, addr, mode);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" %s\n", addr, reloc->import ? reloc->import->name : "");
} else if (IS_MODE_RAD (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: (reloc->symbol ? strdup (reloc->symbol->name) : NULL);
if (name && bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr, keep_lib);
if (mn) {
free (name);
name = mn;
}
}
if (name) {
int reloc_size = 4;
char *n = __filterQuotedShell (name);
r_cons_printf ("\"f %s%s%s %d 0x%08"PFMT64x"\"\n",
r->bin->prefix ? r->bin->prefix : "reloc.",
r->bin->prefix ? "." : "", n, reloc_size, addr);
add_metadata (r, reloc, addr, mode);
free (n);
free (name);
}
} else if (IS_MODE_JSON (mode)) {
if (pj) {
pj_o (pj);
char *mn = NULL;
char *relname = NULL;
// take care with very long symbol names! do not use sdb_fmt or similar
if (reloc->import) {
mn = r_bin_demangle (r->bin->cur, lang, reloc->import->name, addr, keep_lib);
relname = strdup (reloc->import->name);
} else if (reloc->symbol) {
mn = r_bin_demangle (r->bin->cur, lang, reloc->symbol->name, addr, keep_lib);
relname = strdup (reloc->symbol->name);
}
// check if name is available
pj_ks (pj, "name", (relname && strcmp (relname, "")) ? relname : "N/A");
pj_ks (pj, "demname", mn ? mn : "");
pj_ks (pj, "type", bin_reloc_type_name (reloc));
pj_kn (pj, "vaddr", reloc->vaddr);
pj_kn (pj, "paddr", reloc->paddr);
if (reloc->symbol) {
pj_kn (pj, "sym_va", reloc->symbol->vaddr);
}
pj_kb (pj, "is_ifunc", reloc->is_ifunc);
// end reloc item
pj_end (pj);
free (mn);
if (relname) {
free (relname);
}
}
} else if (IS_MODE_NORMAL (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: reloc->symbol
? strdup (reloc->symbol->name)
: strdup ("null");
if (bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr, keep_lib);
if (mn && *mn) {
free (name);
name = mn;
}
}
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" type=%s",
addr, reloc->paddr, bin_reloc_type_name (reloc));
if (reloc->import && reloc->import->name[0]) {
r_cons_printf (" %s", name);
} else if (reloc->symbol && name && name[0]) {
r_cons_printf (" %s", name);
}
R_FREE (name);
if (reloc->addend) {
if ((reloc->import || (reloc->symbol && !R_STR_ISEMPTY (name))) && reloc->addend > 0) {
r_cons_printf (" +");
}
if (reloc->addend < 0) {
r_cons_printf (" - 0x%08"PFMT64x, -reloc->addend);
} else {
r_cons_printf (" 0x%08"PFMT64x, reloc->addend);
}
}
if (reloc->is_ifunc) {
r_cons_print (" (ifunc)");
}
r_cons_newline ();
}
i++;
}
if (IS_MODE_JSON (mode)) {
// close Json output
pj_end (pj);
r_cons_println (pj_string (pj));
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i relocations\n", i);
}
// free PJ object if used
if (pj) {
pj_free (pj);
}
R_FREE (sdb_module);
sdb_free (db);
db = NULL;
R_TIME_END;
return relocs != NULL;
}
#define MYDB 1
/* this is a hacky workaround that needs proper refactoring in Rbin to use Sdb */
#if MYDB
static Sdb *mydb = NULL;
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol, *res = NULL;
RListIter *iter;
if (mydb && symbols && symbols != osymbols) {
sdb_free (mydb);
mydb = NULL;
osymbols = symbols;
}
if (mydb) {
if (name) {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("%x", sdb_hash (name)), NULL);
} else {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("0x"PFMT64x, addr), NULL);
}
} else {
mydb = sdb_new0 ();
r_list_foreach (symbols, iter, symbol) {
if (!symbol->name) {
continue;
}
/* ${name}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("%x", sdb_hash (symbol->name)), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
/* 0x${vaddr}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("0x"PFMT64x, symbol->vaddr), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
if (name) {
if (!res && !strcmp (symbol->name, name)) {
res = symbol;
}
} else {
if (symbol->vaddr == addr) {
res = symbol;
}
}
}
osymbols = symbols;
}
return res;
}
#else
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol;
RListIter *iter;
// XXX this is slow, we should use a hashtable here
r_list_foreach (symbols, iter, symbol) {
if (name) {
if (!strcmp (symbol->name, name))
return symbol;
} else {
if (symbol->vaddr == addr) {
return symbol;
}
}
}
return NULL;
}
#endif
/* XXX: This is a hack to get PLT references in rabin2 -i */
/* imp. is a prefix that can be rewritten by the symbol table */
R_API ut64 r_core_bin_impaddr(RBin *bin, int va, const char *name) {
RList *symbols;
if (!name || !*name) {
return false;
}
if (!(symbols = r_bin_get_symbols (bin))) {
return false;
}
char *impname = r_str_newf ("imp.%s", name);
RBinSymbol *s = get_symbol (bin, symbols, impname, 0LL);
// maybe ut64_MAX to indicate import not found?
ut64 addr = 0LL;
if (s) {
if (va) {
if (s->paddr == UT64_MAX) {
addr = s->vaddr;
} else {
addr = r_bin_get_vaddr (bin, s->paddr, s->vaddr);
}
} else {
addr = s->paddr;
}
}
free (impname);
return addr;
}
static int bin_imports(RCore *r, int mode, int va, const char *name) {
RBinInfo *info = r_bin_get_info (r->bin);
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
RBinImport *import;
RListIter *iter;
bool lit = info ? info->has_lit: false;
char *str;
int i = 0;
if (!info) {
return false;
}
RList *imports = r_bin_get_imports (r->bin);
int cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs imports");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Imports]");
r_cons_println ("Num Vaddr Bind Type Name");
}
r_list_foreach (imports, iter, import) {
if (name && strcmp (import->name, name)) {
continue;
}
char *symname = strdup (import->name);
ut64 addr = lit ? r_core_bin_impaddr (r->bin, va, symname): 0;
if (bin_demangle) {
char *dname = r_bin_demangle (r->bin->cur, NULL, symname, addr, keep_lib);
if (dname) {
free (symname);
symname = r_str_newf ("sym.imp.%s", dname);
free (dname);
}
}
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, symname);
free (symname);
symname = prname;
}
if (IS_MODE_SET (mode)) {
// TODO(eddyb) symbols that are imports.
// Add a dword/qword for PE imports
if (strstr (symname, ".dll_") && cdsz) {
r_meta_add (r->anal, R_META_TYPE_DATA, addr, addr + cdsz, NULL);
}
} else if (IS_MODE_SIMPLE (mode) || IS_MODE_SIMPLEST (mode)) {
r_cons_println (symname);
} else if (IS_MODE_JSON (mode)) {
str = r_str_escape_utf8_for_json (symname, -1);
str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"type\":\"%s\",",
iter->p ? "," : "",
import->ordinal,
import->bind,
import->type);
if (import->classname && import->classname[0]) {
r_cons_printf ("\"classname\":\"%s\","
"\"descriptor\":\"%s\",",
import->classname,
import->descriptor);
}
r_cons_printf ("\"name\":\"%s\",\"plt\":%"PFMT64d"}",
str, addr);
free (str);
} else if (IS_MODE_RAD (mode)) {
// TODO(eddyb) symbols that are imports.
} else {
const char *bind = r_str_get (import->bind);
const char *type = r_str_get (import->type);
#if 0
r_cons_printf ("ordinal=%03d plt=0x%08"PFMT64x" bind=%s type=%s",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf (" classname=%s", import->classname);
}
r_cons_printf (" name=%s", symname);
if (import->descriptor && import->descriptor[0]) {
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#else
r_cons_printf ("%4d 0x%08"PFMT64x" %7s %7s ",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf ("%s.", import->classname);
}
r_cons_printf ("%s", symname);
if (import->descriptor && import->descriptor[0]) {
// Uh?
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#endif
}
R_FREE (symname);
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
// r_cons_printf ("# %i imports\n", i);
}
#if MYDB
// NOTE: if we comment out this, it will leak.. but it will be faster
// because it will keep the cache across multiple RBin calls
osymbols = NULL;
sdb_free (mydb);
mydb = NULL;
#endif
return true;
}
static const char *getPrefixFor(const char *s) {
if (s) {
// workaround for ELF
if (!strcmp (s, R_BIN_TYPE_NOTYPE_STR)) {
return "loc";
}
if (!strcmp (s, R_BIN_TYPE_OBJECT_STR)) {
return "obj";
}
}
return "sym";
}
#define MAXFLAG_LEN_DEFAULT 128
static char *construct_symbol_flagname(const char *pfx, const char *symname, int len) {
char *r = r_str_newf ("%s.%s", pfx, symname);
if (r) {
r_name_filter (r, len); // maybe unnecessary..
char *R = __filterQuotedShell (r);
free (r);
return R;
}
return NULL;
}
typedef struct {
const char *pfx; // prefix for flags
char *name; // raw symbol name
char *nameflag; // flag name for symbol
char *demname; // demangled raw symbol name
char *demflag; // flag name for demangled symbol
char *classname; // classname
char *classflag; // flag for classname
char *methname; // methods [class]::[method]
char *methflag; // methods flag sym.[class].[method]
} SymName;
static void snInit(RCore *r, SymName *sn, RBinSymbol *sym, const char *lang) {
int bin_demangle = lang != NULL;
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
if (!r || !sym || !sym->name) {
return;
}
sn->name = strdup (sym->name);
const char *pfx = getPrefixFor (sym->type);
sn->nameflag = construct_symbol_flagname (pfx, r_bin_symbol_name (sym), MAXFLAG_LEN_DEFAULT);
if (sym->classname && sym->classname[0]) {
sn->classname = strdup (sym->classname);
sn->classflag = r_str_newf ("sym.%s.%s", sn->classname, sn->name);
r_name_filter (sn->classflag, MAXFLAG_LEN_DEFAULT);
const char *name = sym->dname? sym->dname: sym->name;
sn->methname = r_str_newf ("%s::%s", sn->classname, name);
sn->methflag = r_str_newf ("sym.%s.%s", sn->classname, name);
r_name_filter (sn->methflag, strlen (sn->methflag));
} else {
sn->classname = NULL;
sn->classflag = NULL;
sn->methname = NULL;
sn->methflag = NULL;
}
sn->demname = NULL;
sn->demflag = NULL;
if (bin_demangle && sym->paddr) {
sn->demname = r_bin_demangle (r->bin->cur, lang, sn->name, sym->vaddr, keep_lib);
if (sn->demname) {
sn->demflag = construct_symbol_flagname (pfx, sn->demname, -1);
}
}
}
static void snFini(SymName *sn) {
R_FREE (sn->name);
R_FREE (sn->nameflag);
R_FREE (sn->demname);
R_FREE (sn->demflag);
R_FREE (sn->classname);
R_FREE (sn->classflag);
R_FREE (sn->methname);
R_FREE (sn->methflag);
}
static bool isAnExport(RBinSymbol *s) {
/* workaround for some bin plugs */
if (!strncmp (s->name, "imp.", 4)) {
return false;
}
return (s->bind && !strcmp (s->bind, R_BIN_BIND_GLOBAL_STR));
}
static ut64 compute_addr(RBin *bin, ut64 paddr, ut64 vaddr, int va) {
return paddr == UT64_MAX? vaddr: rva (bin, paddr, vaddr, va);
}
static void handle_arm_special_symbol(RCore *core, RBinSymbol *symbol, int va) {
ut64 addr = compute_addr (core->bin, symbol->paddr, symbol->vaddr, va);
if (!strcmp (symbol->name, "$a")) {
r_anal_hint_set_bits (core->anal, addr, 32);
} else if (!strcmp (symbol->name, "$t")) {
r_anal_hint_set_bits (core->anal, addr, 16);
} else if (!strcmp (symbol->name, "$d")) {
// TODO: we could add data meta type at addr, but sometimes $d
// is in the middle of the code and it would make the code less
// readable.
} else {
R_LOG_WARN ("Special symbol %s not handled\n", symbol->name);
}
}
static void handle_arm_hint(RCore *core, RBinInfo *info, ut64 paddr, ut64 vaddr, int bits, int va) {
if (info->bits > 32) { // we look at 16 or 32 bit only
return;
}
int force_bits = 0;
ut64 addr = compute_addr (core->bin, paddr, vaddr, va);
if (paddr & 1 || bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && bits == 32) {
force_bits = 32;
} else if (!(paddr & 1) && bits == 32) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (core->anal, addr, force_bits);
}
}
static void handle_arm_symbol(RCore *core, RBinSymbol *symbol, RBinInfo *info, int va) {
return handle_arm_hint (core, info, symbol->paddr, symbol->vaddr, symbol->bits, va);
}
static void handle_arm_entry(RCore *core, RBinAddr *entry, RBinInfo *info, int va) {
return handle_arm_hint (core, info, entry->paddr, entry->vaddr, entry->bits, va);
}
static void select_flag_space(RCore *core, RBinSymbol *symbol) {
if (!strncmp (symbol->name, "imp.", 4)) {
r_flag_space_push (core->flags, R_FLAGS_FS_IMPORTS);
} else if (symbol->type && !strcmp (symbol->type, R_BIN_TYPE_SECTION_STR)) {
r_flag_space_push (core->flags, R_FLAGS_FS_SYMBOLS_SECTIONS);
} else {
r_flag_space_push (core->flags, R_FLAGS_FS_SYMBOLS);
}
}
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) {
RBinInfo *info = r_bin_get_info (r->bin);
RList *entries = r_bin_get_entries (r->bin);
RBinSymbol *symbol;
RBinAddr *entry;
RListIter *iter;
bool firstexp = true;
bool printHere = false;
int i = 0, lastfs = 's';
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
if (!info) {
return 0;
}
if (args && *args == '.') {
printHere = true;
}
bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3);
const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL;
RList *symbols = r_bin_get_symbols (r->bin);
r_spaces_push (&r->anal->meta_spaces, "bin");
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
} else if (!at && exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs exports\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Exports]\n");
}
} else if (!at && !exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Symbols]\n");
}
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n");
}
size_t count = 0;
r_list_foreach (symbols, iter, symbol) {
if (!symbol->name) {
continue;
}
char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true);
ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va);
int len = symbol->size ? symbol->size : 32;
SymName sn = {0};
if (exponly && !isAnExport (symbol)) {
free (r_symbol_name);
continue;
}
if (name && strcmp (r_symbol_name, name)) {
free (r_symbol_name);
continue;
}
if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {
free (r_symbol_name);
continue;
}
if ((printHere && !is_in_range (r->offset, symbol->paddr, len))
&& (printHere && !is_in_range (r->offset, addr, len))) {
free (r_symbol_name);
continue;
}
count ++;
snInit (r, &sn, symbol, lang);
if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) {
/*
* Skip section symbols because they will have their own flag.
* Skip also file symbols because not useful for now.
*/
} else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) {
if (is_arm) {
handle_arm_special_symbol (r, symbol, va);
}
} else if (IS_MODE_SET (mode)) {
// TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata
if (is_arm) {
handle_arm_symbol (r, symbol, info, va);
}
select_flag_space (r, symbol);
/* If that's a Classed symbol (method or so) */
if (sn.classname) {
RFlagItem *fi = r_flag_get (r->flags, sn.methflag);
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag);
r_name_filter (sn.methflag, -1);
free (sn.methflag);
sn.methflag = prname;
}
if (fi) {
r_flag_item_set_realname (fi, sn.methname);
if ((fi->offset - r->flags->base) == addr) {
// char *comment = fi->comment ? strdup (fi->comment) : NULL;
r_flag_unset (r->flags, fi);
}
} else {
fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);
char *comment = fi->comment ? strdup (fi->comment) : NULL;
if (comment) {
r_flag_item_set_comment (fi, comment);
R_FREE (comment);
}
}
} else {
const char *n = sn.demname ? sn.demname : sn.name;
const char *fn = sn.demflag ? sn.demflag : sn.nameflag;
char *fnp = (r->bin->prefix) ?
r_str_newf ("%s.%s", r->bin->prefix, fn):
strdup (fn);
RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size);
if (fi) {
r_flag_item_set_realname (fi, n);
fi->demangled = (bool)(size_t)sn.demname;
} else {
if (fn) {
eprintf ("[Warning] Can't find flag (%s)\n", fn);
}
}
free (fnp);
}
if (sn.demname) {
r_meta_add (r->anal, R_META_TYPE_COMMENT,
addr, symbol->size, sn.demname);
}
r_flag_space_pop (r->flags);
} else if (IS_MODE_JSON (mode)) {
char *str = r_str_escape_utf8_for_json (r_symbol_name, -1);
// str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"name\":\"%s\","
"\"demname\":\"%s\","
"\"flagname\":\"%s\","
"\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"size\":%d,"
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d"}",
((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""),
str,
sn.demname? sn.demname: "",
sn.nameflag,
symbol->ordinal,
symbol->bind,
(int)symbol->size,
symbol->type,
(ut64)addr, (ut64)symbol->paddr);
free (str);
} else if (IS_MODE_SIMPLE (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("0x%08"PFMT64x" %d %s\n",
addr, (int)symbol->size, name);
} else if (IS_MODE_SIMPLEST (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("%s\n", name);
} else if (IS_MODE_RAD (mode)) {
/* Skip special symbols because we do not flag them and
* they shouldn't be printed in the rad format either */
if (is_special_symbol (symbol)) {
goto next;
}
RBinFile *binfile;
RBinPlugin *plugin;
const char *name = sn.demname? sn.demname: r_symbol_name;
if (!name) {
goto next;
}
if (!strncmp (name, "imp.", 4)) {
if (lastfs != 'i') {
r_cons_printf ("fs imports\n");
}
lastfs = 'i';
} else {
if (lastfs != 's') {
const char *fs = exponly? "exports": "symbols";
r_cons_printf ("fs %s\n", fs);
}
lastfs = 's';
}
if (r->bin->prefix || *name) { // we don't want unnamed symbol flags
char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT);
if (!flagname) {
goto next;
}
r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n",
r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "",
flagname, symbol->size, addr);
free (flagname);
}
binfile = r_bin_cur (r->bin);
plugin = r_bin_file_cur_plugin (binfile);
if (plugin && plugin->name) {
if (r_str_startswith (plugin->name, "pe")) {
char *module = strdup (r_symbol_name);
char *p = strstr (module, ".dll_");
if (p && strstr (module, "imp.")) {
char *symname = __filterShell (p + 5);
char *m = __filterShell (module);
*p = 0;
if (r->bin->prefix) {
r_cons_printf ("k bin/pe/%s/%d=%s.%s\n",
module, symbol->ordinal, r->bin->prefix, symname);
} else {
r_cons_printf ("k bin/pe/%s/%d=%s\n",
module, symbol->ordinal, symname);
}
free (symname);
free (m);
}
free (module);
}
}
} else {
const char *bind = symbol->bind? symbol->bind: "NONE";
const char *type = symbol->type? symbol->type: "NONE";
const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name);
// const char *fwd = r_str_get (symbol->forwarder);
r_cons_printf ("%03u", symbol->ordinal);
if (symbol->paddr == UT64_MAX) {
r_cons_printf (" ----------");
} else {
r_cons_printf (" 0x%08"PFMT64x, symbol->paddr);
}
r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n",
addr, bind, type, symbol->size, *name? " ": "", name);
}
next:
snFini (&sn);
i++;
free (r_symbol_name);
if (exponly && firstexp) {
firstexp = false;
}
if (printHere) {
break;
}
}
if (count == 0 && IS_MODE_JSON (mode)) {
r_cons_printf ("{}");
}
//handle thumb and arm for entry point since they are not present in symbols
if (is_arm) {
r_list_foreach (entries, iter, entry) {
if (IS_MODE_SET (mode)) {
handle_arm_entry (r, entry, info, va);
}
}
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("]");
}
r_spaces_pop (&r->anal->meta_spaces);
return true;
}
static char *build_hash_string(int mode, const char *chksum, ut8 *data, ut32 datalen) {
char *chkstr = NULL, *aux, *ret = NULL;
const char *ptr = chksum;
char tmp[128];
int i;
do {
for (i = 0; *ptr && *ptr != ',' && i < sizeof (tmp) -1; i++) {
tmp[i] = *ptr++;
}
tmp[i] = '\0';
r_str_trim_head_tail (tmp);
chkstr = r_hash_to_string (NULL, tmp, data, datalen);
if (!chkstr) {
if (*ptr && *ptr == ',') {
ptr++;
}
continue;
}
if (IS_MODE_SIMPLE (mode)) {
aux = r_str_newf ("%s ", chkstr);
} else if (IS_MODE_JSON (mode)) {
aux = r_str_newf ("\"%s\":\"%s\",", tmp, chkstr);
} else {
aux = r_str_newf ("%s=%s ", tmp, chkstr);
}
ret = r_str_append (ret, aux);
free (chkstr);
free (aux);
if (*ptr && *ptr == ',') {
ptr++;
}
} while (*ptr);
return ret;
}
typedef struct {
const char *uri;
int perm;
RIODesc *desc;
} FindFile;
static bool findFile(void *user, void *data, ut32 id) {
FindFile *res = (FindFile*)user;
RIODesc *desc = (RIODesc*)data;
if (desc->perm && res->perm && !strcmp (desc->uri, res->uri)) {
res->desc = desc;
return false;
}
return true;
}
static RIODesc *findReusableFile(RIO *io, const char *uri, int perm) {
FindFile arg = {
.uri = uri,
.perm = perm,
.desc = NULL,
};
r_id_storage_foreach (io->files, findFile, &arg);
return arg.desc;
}
static bool io_create_mem_map(RIO *io, RBinSection *sec, ut64 at) {
r_return_val_if_fail (io && sec, false);
bool reused = false;
ut64 gap = sec->vsize - sec->size;
char *uri = r_str_newf ("null://%"PFMT64u, gap);
RIODesc *desc = findReusableFile (io, uri, sec->perm);
if (desc) {
RIOMap *map = r_io_map_get (io, at);
if (!map) {
r_io_map_add_batch (io, desc->fd, desc->perm, 0LL, at, gap);
}
reused = true;
}
if (!desc) {
desc = r_io_open_at (io, uri, sec->perm, 0664, at);
}
free (uri);
if (!desc) {
return false;
}
// this works, because new maps are always born on the top
RIOMap *map = r_io_map_get (io, at);
// check if the mapping failed
if (!map) {
if (!reused) {
r_io_desc_close (desc);
}
return false;
}
// let the section refere to the map as a memory-map
map->name = r_str_newf ("mmap.%s", sec->name);
return true;
}
static void add_section(RCore *core, RBinSection *sec, ut64 addr, int fd) {
if (!r_io_desc_get (core->io, fd) || UT64_ADD_OVFCHK (sec->size, sec->paddr) ||
UT64_ADD_OVFCHK (sec->size, addr) || !sec->vsize) {
return;
}
ut64 size = sec->vsize;
// if there is some part of the section that needs to be zeroed by the loader
// we add a null map that takes care of it
if (sec->vsize > sec->size) {
if (!io_create_mem_map (core->io, sec, addr + sec->size)) {
return;
}
size = sec->size;
}
// then we map the part of the section that comes from the physical file
char *map_name = r_str_newf ("fmap.%s", sec->name);
if (!map_name) {
return;
}
int perm = sec->perm;
// workaround to force exec bit in text section
if (sec->name && strstr (sec->name, "text")) {
perm |= R_PERM_X;
}
RIOMap *map = r_io_map_add_batch (core->io, fd, perm, sec->paddr, addr, size);
if (!map) {
free (map_name);
return;
}
map->name = map_name;
return;
}
struct io_bin_section_info_t {
RBinSection *sec;
ut64 addr;
int fd;
};
static int bin_sections(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *chksum, bool print_segments) {
char *str = NULL;
RBinSection *section;
RBinInfo *info = NULL;
RList *sections;
RListIter *iter;
RListIter *last_processed = NULL;
int i = 0;
int fd = -1;
bool printHere = false;
sections = r_bin_get_sections (r->bin);
#if LOAD_BSS_MALLOC
bool inDebugger = r_config_get_i (r->config, "cfg.debug");
#endif
HtPP *dup_chk_ht = ht_pp_new0 ();
bool ret = false;
const char *type = print_segments ? "segment" : "section";
bool segments_only = true;
RList *io_section_info = NULL;
if (!dup_chk_ht) {
return false;
}
if (chksum && *chksum == '.') {
printHere = true;
}
if (IS_MODE_EQUAL (mode)) {
int cols = r_cons_get_size (NULL);
RList *list = r_list_newf ((RListFree) r_listinfo_free);
if (!list) {
return false;
}
RBinSection *s;
r_list_foreach (sections, iter, s) {
char humansz[8];
if (print_segments != s->is_segment) {
continue;
}
RInterval pitv = (RInterval){s->paddr, s->size};
RInterval vitv = (RInterval){s->vaddr, s->vsize};
r_num_units (humansz, sizeof (humansz), s->size);
RListInfo *info = r_listinfo_new (s->name, pitv, vitv, s->perm, strdup (humansz));
r_list_append (list, info);
}
r_core_visual_list (r, list, r->offset, -1, cols, r->print->flags & R_PRINT_FLAGS_COLOR);
r_list_free (list);
goto out;
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_RAD (mode) && !at) {
r_cons_printf ("fs %ss\n", type);
} else if (IS_MODE_NORMAL (mode) && !at && !printHere) {
r_cons_printf ("[%s]\n", print_segments ? "Segments" : "Sections");
} else if (IS_MODE_NORMAL (mode) && printHere) {
r_cons_printf ("Current section\n");
} else if (IS_MODE_SET (mode)) {
fd = r_core_file_cur_fd (r);
r_flag_space_set (r->flags, print_segments? R_FLAGS_FS_SEGMENTS: R_FLAGS_FS_SECTIONS);
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("Nm Paddr Size Vaddr Memsz Perms %sName\n",
chksum ? "Checksum " : "");
}
if (IS_MODE_SET (mode)) {
r_list_foreach (sections, iter, section) {
if (!section->is_segment) {
segments_only = false;
break;
}
}
io_section_info = r_list_newf ((RListFree)free);
}
r_list_foreach (sections, iter, section) {
char perms[] = "----";
int va_sect = va;
ut64 addr;
if (va && !(section->perm & R_PERM_R)) {
va_sect = VA_NOREBASE;
}
addr = rva (r->bin, section->paddr, section->vaddr, va_sect);
if (name && strcmp (section->name, name)) {
continue;
}
if ((printHere && !(section->paddr <= r->offset && r->offset < (section->paddr + section->size)))
&& (printHere && !(addr <= r->offset && r->offset < (addr + section->size)))) {
continue;
}
r_name_filter (section->name, strlen (section->name) + 1);
if (at && (!section->size || !is_in_range (at, addr, section->size))) {
continue;
}
if (section->is_segment != print_segments) {
continue;
}
if (section->perm & R_PERM_SHAR) {
perms[0] = 's';
}
if (section->perm & R_PERM_R) {
perms[1] = 'r';
}
if (section->perm & R_PERM_W) {
perms[2] = 'w';
}
if (section->perm & R_PERM_X) {
perms[3] = 'x';
}
const char *arch = NULL;
int bits = 0;
if (section->arch || section->bits) {
arch = section->arch;
bits = section->bits;
}
if (info) {
if (!arch) {
arch = info->arch;
}
if (!bits) {
bits = info->bits;
}
}
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
if (!bits) {
bits = R_SYS_BITS;
}
if (IS_MODE_RAD (mode)) {
char *n = __filterQuotedShell (section->name);
r_cons_printf ("\"f %s.%s 1 0x%08"PFMT64x"\"\n", type, n, section->vaddr);
free (n);
} else if (IS_MODE_SET (mode)) {
#if LOAD_BSS_MALLOC
if (!strcmp (section->name, ".bss")) {
// check if there's already a file opened there
int loaded = 0;
RListIter *iter;
RIOMap *m;
r_list_foreach (r->io->maps, iter, m) {
if (m->from == addr) {
loaded = 1;
}
}
if (!loaded && !inDebugger) {
r_core_cmdf (r, "on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
}
}
#endif
if (section->format) {
// This is damn slow if section vsize is HUGE
if (section->vsize < 1024 * 1024 * 2) {
r_core_cmdf (r, "%s @ 0x%"PFMT64x, section->format, section->vaddr);
}
}
if (r->bin->prefix) {
str = r_str_newf ("%s.%s.%s", r->bin->prefix, type, section->name);
} else {
str = r_str_newf ("%s.%s", type, section->name);
}
ut64 size = r->io->va? section->vsize: section->size;
r_flag_set (r->flags, str, addr, size);
R_FREE (str);
if (!section->is_segment || segments_only) {
char *pfx = r->bin->prefix;
str = r_str_newf ("[%02d] %s %s size %" PFMT64d" named %s%s%s",
i, perms, type, size,
pfx? pfx: "", pfx? ".": "", section->name);
r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, addr, str);
R_FREE (str);
}
if (section->add) {
bool found;
str = r_str_newf ("%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT32u".%s.%"PFMT32u".%d",
section->paddr, addr, section->size, section->vsize, section->perm, section->name, r->bin->cur->id, fd);
ht_pp_find (dup_chk_ht, str, &found);
if (!found) {
// can't directly add maps because they
// need to be reversed, otherwise for
// the way IO works maps would be shown
// in reverse order
struct io_bin_section_info_t *ibs = R_NEW (struct io_bin_section_info_t);
if (!ibs) {
eprintf ("Could not allocate memory\n");
goto out;
}
ibs->sec = section;
ibs->addr = addr;
ibs->fd = fd;
r_list_append (io_section_info, ibs);
ht_pp_insert (dup_chk_ht, str, NULL);
}
R_FREE (str);
}
} else if (IS_MODE_SIMPLE (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("0x%"PFMT64x" 0x%"PFMT64x" %s %s%s%s\n",
addr, addr + section->size,
perms,
hashstr ? hashstr : "", hashstr ? " " : "",
section->name
);
free (hashstr);
} else if (IS_MODE_JSON (mode)) {
char *hashstr = NULL;
if (chksum && section->size > 0) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("%s{\"name\":\"%s\","
"\"size\":%"PFMT64d","
"\"vsize\":%"PFMT64d","
"\"perm\":\"%s\","
"%s"
"\"paddr\":%"PFMT64d","
"\"vaddr\":%"PFMT64d"}",
(last_processed && !printHere) ? "," : "",
section->name,
section->size,
section->vsize,
perms,
hashstr ? hashstr : "",
section->paddr,
addr);
free (hashstr);
} else {
char *hashstr = NULL, str[128];
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
// VA READ IS BROKEN?
if (datalen > 0) {
r_io_pread_at (r->io, section->paddr, data, datalen);
}
hashstr = build_hash_string (mode, chksum, data, datalen);
free (data);
}
if (section->arch || section->bits) {
snprintf (str, sizeof (str), "arch=%s bits=%d ",
r_str_get2 (arch), bits);
} else {
str[0] = 0;
}
if (r->bin->prefix) {
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s%s%s.%s\n",
i, section->paddr, section->size, addr, section->vsize,
perms, str, hashstr ?hashstr : "", r->bin->prefix, section->name);
} else {
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s%s%s\n",
i, section->paddr, (ut64)section->size, addr, (ut64)section->vsize,
perms, str, hashstr ?hashstr : "", section->name);
}
free (hashstr);
}
i++;
last_processed = iter;
if (printHere) {
break;
}
}
if (IS_MODE_SET (mode) && !r_io_desc_is_dbg (r->io->desc)) {
RListIter *it;
struct io_bin_section_info_t *ibs;
r_list_foreach_prev (io_section_info, it, ibs) {
add_section (r, ibs->sec, ibs->addr, ibs->fd);
}
r_io_update (r->io);
r_list_free (io_section_info);
io_section_info = NULL;
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_println ("]");
} else if (IS_MODE_NORMAL (mode) && !at && !printHere) {
// r_cons_printf ("\n%i sections\n", i);
}
ret = true;
out:
ht_pp_free (dup_chk_ht);
return ret;
}
static int bin_fields(RCore *r, int mode, int va) {
RList *fields;
RListIter *iter;
RBinField *field;
int i = 0;
RBin *bin = r->bin;
if (!(fields = r_bin_get_fields (bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs header");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Header fields]");
}
r_list_foreach (fields, iter, field) {
ut64 addr = rva (bin, field->paddr, field->vaddr, va);
if (IS_MODE_RAD (mode)) {
char *n = __filterQuotedShell (field->name);
r_name_filter (n, -1);
r_cons_printf ("\"f header.%s 1 0x%08"PFMT64x"\"\n", n, addr);
if (field->comment && *field->comment) {
char *e = sdb_encode ((const ut8*)field->comment, -1);
r_cons_printf ("CCu %s @ 0x%"PFMT64x"\n", e, addr);
free (e);
char *f = __filterShell (field->format);
r_cons_printf ("Cf %d .%s @ 0x%"PFMT64x"\n", field->size, f, addr);
free (f);
}
if (field->format && *field->format) {
r_cons_printf ("pf.%s %s\n", n, field->format);
}
free (n);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"name\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d,
iter->p? ",": "",
field->name,
field->vaddr,
field->paddr
);
if (field->comment && *field->comment) {
// TODO: filter comment before json
r_cons_printf (",\"comment\":\"%s\"", field->comment);
}
if (field->format && *field->format) {
// TODO: filter comment before json
r_cons_printf (",\"format\":\"%s\"", field->format);
}
char *o = r_core_cmd_strf (r, "pfj.%s@0x%"PFMT64x, field->format, field->vaddr);
if (o && *o) {
r_cons_printf (",\"pf\":%s", o);
}
free (o);
r_cons_printf ("}");
} else if (IS_MODE_NORMAL (mode)) {
const bool haveComment = (field->comment && *field->comment);
r_cons_printf ("0x%08"PFMT64x" 0x%08"PFMT64x" %s%s%s\n",
field->vaddr, field->paddr, field->name,
haveComment? "; ": "",
haveComment? field->comment: "");
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i fields\n", i);
}
return true;
}
static char *get_rp(const char *rtype) {
char *rp = NULL;
switch (rtype[0]) {
case 'v':
rp = strdup ("void");
break;
case 'c':
rp = strdup ("char");
break;
case 'i':
rp = strdup ("int");
break;
case 's':
rp = strdup ("short");
break;
case 'l':
rp = strdup ("long");
break;
case 'q':
rp = strdup ("long long");
break;
case 'C':
rp = strdup ("unsigned char");
break;
case 'I':
rp = strdup ("unsigned int");
break;
case 'S':
rp = strdup ("unsigned short");
break;
case 'L':
rp = strdup ("unsigned long");
break;
case 'Q':
rp = strdup ("unsigned long long");
break;
case 'f':
rp = strdup ("float");
break;
case 'd':
rp = strdup ("double");
break;
case 'D':
rp = strdup ("long double");
break;
case 'B':
rp = strdup ("bool");
break;
case '#':
rp = strdup ("CLASS");
break;
default:
rp = strdup ("unknown");
break;
}
return rp;
}
static int bin_trycatch(RCore *core, int mode) {
RBinFile *bf = r_bin_cur (core->bin);
RListIter *iter;
RBinTrycatch *tc;
RList *trycatch = r_bin_file_get_trycatch (bf);
int idx = 0;
r_list_foreach (trycatch, iter, tc) {
r_cons_printf ("f try.%d.%"PFMT64x".from=0x%08"PFMT64x"\n", idx, tc->source, tc->from);
r_cons_printf ("f try.%d.%"PFMT64x".to=0x%08"PFMT64x"\n", idx, tc->source, tc->to);
r_cons_printf ("f try.%d.%"PFMT64x".catch=0x%08"PFMT64x"\n", idx, tc->source, tc->handler);
idx++;
}
return true;
}
static void classdump_objc(RCore *r, RBinClass *c) {
if (c->super) {
r_cons_printf ("@interface %s : %s\n{\n", c->name, c->super);
} else {
r_cons_printf ("@interface %s\n{\n", c->name);
}
RListIter *iter2, *iter3;
RBinField *f;
RBinSymbol *sym;
r_list_foreach (c->fields, iter2, f) {
if (f->name && r_regex_match ("ivar","e", f->name)) {
r_cons_printf (" %s %s\n", f->type, f->name);
}
}
r_cons_printf ("}\n");
r_list_foreach (c->methods, iter3, sym) {
if (sym->rtype && sym->rtype[0] != '@') {
char *rp = get_rp (sym->rtype);
r_cons_printf ("%s (%s) %s\n",
strncmp (sym->type, R_BIN_TYPE_METH_STR, 4)? "+": "-",
rp, sym->dname? sym->dname: sym->name);
free (rp);
} else if (sym->type) {
r_cons_printf ("%s (id) %s\n",
strncmp (sym->type, R_BIN_TYPE_METH_STR, 4)? "+": "-",
sym->dname? sym->dname: sym->name);
}
}
r_cons_printf ("@end\n");
}
static void classdump_java(RCore *r, RBinClass *c) {
RBinField *f;
RListIter *iter2, *iter3;
RBinSymbol *sym;
char *pn = strdup (c->name);
char *cn = (char *)r_str_rchr (pn, NULL, '/');
if (cn) {
*cn = 0;
cn++;
r_str_replace_char (pn, '/', '.');
}
r_cons_printf ("package %s;\n\n", pn);
r_cons_printf ("public class %s {\n", cn);
free (pn);
r_list_foreach (c->fields, iter2, f) {
if (f->name && r_regex_match ("ivar","e", f->name)) {
r_cons_printf (" public %s %s\n", f->type, f->name);
}
}
r_list_foreach (c->methods, iter3, sym) {
const char *mn = sym->dname? sym->dname: sym->name;
const char *ms = strstr (mn, "method.");
if (ms) {
mn = ms + strlen ("method.");
}
r_cons_printf (" public %s ();\n", mn);
}
r_cons_printf ("}\n\n");
}
static int bin_classes(RCore *r, int mode) {
RListIter *iter, *iter2, *iter3;
RBinSymbol *sym;
RBinClass *c;
RBinField *f;
char *name;
RList *cs = r_bin_get_classes (r->bin);
if (!cs) {
if (IS_MODE_JSON (mode)) {
r_cons_print ("[]");
}
return false;
}
// XXX: support for classes is broken and needs more love
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
if (!r_config_get_i (r->config, "bin.classes")) {
return false;
}
r_flag_space_set (r->flags, R_FLAGS_FS_CLASSES);
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs classes");
}
r_list_foreach (cs, iter, c) {
if (!c || !c->name || !c->name[0]) {
continue;
}
name = strdup (c->name);
r_name_filter (name, 0);
ut64 at_min = UT64_MAX;
ut64 at_max = 0LL;
r_list_foreach (c->methods, iter2, sym) {
if (sym->vaddr) {
if (sym->vaddr < at_min) {
at_min = sym->vaddr;
}
if (sym->vaddr + sym->size > at_max) {
at_max = sym->vaddr + sym->size;
}
}
}
if (at_min == UT64_MAX) {
at_min = c->addr;
at_max = c->addr; // XXX + size?
}
if (IS_MODE_SET (mode)) {
const char *classname = sdb_fmt ("class.%s", name);
r_flag_set (r->flags, classname, c->addr, 1);
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *method = sdb_fmt ("method%s.%s.%s",
mflags, c->name, sym->name);
R_FREE (mflags);
r_name_filter (method, -1);
r_flag_set (r->flags, method, sym->vaddr, 1);
}
} else if (IS_MODE_SIMPLEST (mode)) {
r_cons_printf ("%s\n", c->name);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] %s%s%s\n",
c->addr, at_min, at_max, c->name, c->super ? " " : "",
c->super ? c->super : "");
} else if (IS_MODE_RAD (mode)) {
char *n = __filterShell (name);
r_cons_printf ("\"f class.%s = 0x%"PFMT64x"\"\n", n, at_min);
free (n);
if (c->super) {
char *cn = c->name; // __filterShell (c->name);
char *su = c->super; // __filterShell (c->super);
r_cons_printf ("\"f super.%s.%s = %d\"\n",
cn, su, c->index);
// free (cn);
// free (su);
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *n = c->name; // __filterShell (c->name);
char *sn = sym->name; //__filterShell (sym->name);
char *cmd = r_str_newf ("\"f method%s.%s.%s = 0x%"PFMT64x"\"\n", mflags, n, sn, sym->vaddr);
// free (n);
// free (sn);
if (cmd) {
r_str_replace_char (cmd, ' ', '_');
if (strlen (cmd) > 2) {
cmd[2] = ' ';
}
char *eq = (char *)r_str_rchr (cmd, NULL, '=');
if (eq && eq != cmd) {
eq[-1] = eq[1] = ' ';
}
r_str_replace_char (cmd, '\n', 0);
r_cons_printf ("%s\n", cmd);
free (cmd);
}
R_FREE (mflags);
}
} else if (IS_MODE_JSON (mode)) {
if (c->super) {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"visibility\":\"%s\",\"super\":\"%s\",\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index, c->visibility_str? c->visibility_str: "", c->super);
} else {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index);
}
r_list_foreach (c->methods, iter2, sym) {
if (sym->method_flags) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, mflags, sym->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, sym->vaddr);
}
}
r_cons_printf ("], \"fields\":[");
r_list_foreach (c->fields, iter3, f) {
if (f->flags) {
char *mflags = r_core_bin_method_flags_str (f->flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, mflags, f->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, f->vaddr);
}
}
r_cons_printf ("]}");
} else if (IS_MODE_CLASSDUMP (mode)) {
if (c) {
RBinFile *bf = r_bin_cur (r->bin);
if (bf && bf->o) {
if (bf->o->lang == R_BIN_NM_JAVA || (bf->o->info && bf->o->info->lang && strstr (bf->o->info->lang, "dalvik"))) {
classdump_java (r, c);
} else {
classdump_objc (r, c);
}
} else {
classdump_objc (r, c);
}
}
} else {
int m = 0;
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] %6"PFMT64d" class %d %s",
c->addr, at_min, at_max, (at_max - at_min), c->index, c->name);
if (c->super) {
r_cons_printf (" :: %s\n", c->super);
} else {
r_cons_newline ();
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("0x%08"PFMT64x" method %d %s %s\n",
sym->vaddr, m, mflags, sym->dname? sym->dname: sym->name);
R_FREE (mflags);
m++;
}
}
free (name);
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
return true;
}
static int bin_size(RCore *r, int mode) {
ut64 size = r_bin_get_size (r->bin);
if (IS_MODE_SIMPLE (mode) || IS_MODE_JSON (mode)) {
r_cons_printf ("%"PFMT64u"\n", size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f bin_size @ %"PFMT64u"\n", size);
} else if (IS_MODE_SET (mode)) {
r_core_cmdf (r, "f bin_size @ %"PFMT64u"\n", size);
} else {
r_cons_printf ("%"PFMT64u"\n", size);
}
return true;
}
static int bin_libs(RCore *r, int mode) {
RList *libs;
RListIter *iter;
char* lib;
int i = 0;
if (!(libs = r_bin_get_libs (r->bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Linked libraries]");
}
r_list_foreach (libs, iter, lib) {
if (IS_MODE_SET (mode)) {
// Nothing to set.
// TODO: load libraries with iomaps?
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("\"CCa entry0 %s\"\n", lib);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s\"%s\"", iter->p ? "," : "", lib);
} else {
// simple and normal print mode
r_cons_println (lib);
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
if (i == 1) {
r_cons_printf ("\n%i library\n", i);
} else {
r_cons_printf ("\n%i libraries\n", i);
}
}
return true;
}
static void bin_mem_print(RList *mems, int perms, int depth, int mode) {
RBinMem *mem;
RListIter *iter;
if (!mems) {
return;
}
r_list_foreach (mems, iter, mem) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"name\":\"%s\",\"size\":%d,\"address\":%d,"
"\"flags\":\"%s\"}", mem->name, mem->size,
mem->addr, r_str_rwx_i (mem->perms & perms));
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", mem->addr);
} else {
r_cons_printf ("0x%08"PFMT64x" +0x%04x %s %*s%-*s\n",
mem->addr, mem->size, r_str_rwx_i (mem->perms & perms),
depth, "", 20-depth, mem->name);
}
if (mem->mirrors) {
if (IS_MODE_JSON (mode)) {
r_cons_printf (",");
}
bin_mem_print (mem->mirrors, mem->perms & perms, depth + 1, mode);
}
if (IS_MODE_JSON (mode)) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
static int bin_mem(RCore *r, int mode) {
RList *mem = NULL;
if (!r) {
return false;
}
if (!IS_MODE_JSON (mode)) {
if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
r_cons_println ("[Memory]\n");
}
}
if (!(mem = r_bin_get_mem (r->bin))) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
bin_mem_print (mem, 7, 0, R_MODE_JSON);
r_cons_println ("]");
return true;
} else if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
bin_mem_print (mem, 7, 0, mode);
}
return true;
}
static void bin_pe_versioninfo(RCore *r, int mode) {
Sdb *sdb = NULL;
int num_version = 0;
int num_stringtable = 0;
int num_string = 0;
const char *format_version = "bin/cur/info/vs_version_info/VS_VERSIONINFO%d";
const char *format_stringtable = "%s/string_file_info/stringtable%d";
const char *format_string = "%s/string%d";
if (!IS_MODE_JSON (mode)) {
r_cons_printf ("=== VS_VERSIONINFO ===\n\n");
}
bool firstit_dowhile = true;
do {
char *path_version = sdb_fmt (format_version, num_version);
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (!firstit_dowhile && IS_MODE_JSON (mode)) {
r_cons_printf (",");
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"VS_FIXEDFILEINFO\":{");
} else {
r_cons_printf ("# VS_FIXEDFILEINFO\n\n");
}
const char *path_fixedfileinfo = sdb_fmt ("%s/fixed_file_info", path_version);
if (!(sdb = sdb_ns_path (r->sdb, path_fixedfileinfo, 0))) {
r_cons_printf ("}");
break;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"Signature\":%"PFMT64u",", sdb_num_get (sdb, "Signature", 0));
r_cons_printf ("\"StrucVersion\":%"PFMT64u",", sdb_num_get (sdb, "StrucVersion", 0));
r_cons_printf ("\"FileVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
r_cons_printf ("\"ProductVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
r_cons_printf ("\"FileFlagsMask\":%"PFMT64u",", sdb_num_get (sdb, "FileFlagsMask", 0));
r_cons_printf ("\"FileFlags\":%"PFMT64u",", sdb_num_get (sdb, "FileFlags", 0));
r_cons_printf ("\"FileOS\":%"PFMT64u",", sdb_num_get (sdb, "FileOS", 0));
r_cons_printf ("\"FileType\":%"PFMT64u",", sdb_num_get (sdb, "FileType", 0));
r_cons_printf ("\"FileSubType\":%"PFMT64u, sdb_num_get (sdb, "FileSubType", 0));
r_cons_printf ("},");
} else {
r_cons_printf (" Signature: 0x%"PFMT64x"\n", sdb_num_get (sdb, "Signature", 0));
r_cons_printf (" StrucVersion: 0x%"PFMT64x"\n", sdb_num_get (sdb, "StrucVersion", 0));
r_cons_printf (" FileVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
r_cons_printf (" ProductVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
r_cons_printf (" FileFlagsMask: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlagsMask", 0));
r_cons_printf (" FileFlags: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlags", 0));
r_cons_printf (" FileOS: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileOS", 0));
r_cons_printf (" FileType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileType", 0));
r_cons_printf (" FileSubType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileSubType", 0));
r_cons_newline ();
}
#if 0
r_cons_printf (" FileDate: %d.%d.%d.%d\n",
sdb_num_get (sdb, "FileDateMS", 0) >> 16,
sdb_num_get (sdb, "FileDateMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileDateLS", 0) >> 16,
sdb_num_get (sdb, "FileDateLS", 0) & 0xFFFF);
#endif
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"StringTable\":{");
} else {
r_cons_printf ("# StringTable\n\n");
}
for (num_stringtable = 0; sdb; num_stringtable++) {
char *path_stringtable = r_str_newf (format_stringtable, path_version, num_stringtable);
sdb = sdb_ns_path (r->sdb, path_stringtable, 0);
bool firstit_for = true;
for (num_string = 0; sdb; num_string++) {
char *path_string = r_str_newf (format_string, path_stringtable, num_string);
sdb = sdb_ns_path (r->sdb, path_string, 0);
if (sdb) {
if (!firstit_for && IS_MODE_JSON (mode)) { r_cons_printf (","); }
int lenkey = 0;
int lenval = 0;
ut8 *key_utf16 = sdb_decode (sdb_const_get (sdb, "key", 0), &lenkey);
ut8 *val_utf16 = sdb_decode (sdb_const_get (sdb, "value", 0), &lenval);
ut8 *key_utf8 = calloc (lenkey * 2, 1);
ut8 *val_utf8 = calloc (lenval * 2, 1);
if (r_str_utf16_to_utf8 (key_utf8, lenkey * 2, key_utf16, lenkey, true) < 0
|| r_str_utf16_to_utf8 (val_utf8, lenval * 2, val_utf16, lenval, true) < 0) {
eprintf ("Warning: Cannot decode utf16 to utf8\n");
} else if (IS_MODE_JSON (mode)) {
char *escaped_key_utf8 = r_str_escape ((char*)key_utf8);
char *escaped_val_utf8 = r_str_escape ((char*)val_utf8);
r_cons_printf ("\"%s\":\"%s\"", escaped_key_utf8, escaped_val_utf8);
free (escaped_key_utf8);
free (escaped_val_utf8);
} else {
r_cons_printf (" %s: %s\n", (char*)key_utf8, (char*)val_utf8);
}
free (key_utf8);
free (val_utf8);
free (key_utf16);
free (val_utf16);
}
firstit_for = false;
free (path_string);
}
free (path_stringtable);
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("}}");
}
num_version++;
firstit_dowhile = false;
} while (sdb);
}
static void bin_elf_versioninfo(RCore *r, int mode) {
const char *format = "bin/cur/info/versioninfo/%s%d";
int num_versym;
int num_verneed = 0;
int num_version = 0;
Sdb *sdb = NULL;
const char *oValue = NULL;
bool firstit_for_versym = true;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"versym\":[");
}
for (num_versym = 0;; num_versym++) {
const char *versym_path = sdb_fmt (format, "versym", num_versym);
if (!(sdb = sdb_ns_path (r->sdb, versym_path, 0))) {
break;
}
ut64 addr = sdb_num_get (sdb, "addr", 0);
ut64 offset = sdb_num_get (sdb, "offset", 0);
ut64 link = sdb_num_get (sdb, "link", 0);
ut64 num_entries = sdb_num_get (sdb, "num_entries", 0);
const char *section_name = sdb_const_get (sdb, "section_name", 0);
const char *link_section_name = sdb_const_get (sdb, "link_section_name", 0);
if (IS_MODE_JSON (mode)) {
if (!firstit_for_versym) { r_cons_printf (","); }
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
section_name, (ut64)addr, (ut64)offset);
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
(ut32)link, link_section_name);
} else {
r_cons_printf ("Version symbols section '%s' contains %"PFMT64u" entries:\n", section_name, num_entries);
r_cons_printf (" Addr: 0x%08"PFMT64x" Offset: 0x%08"PFMT64x" Link: %x (%s)\n",
(ut64)addr, (ut64)offset, (ut32)link, link_section_name);
}
int i;
for (i = 0; i < num_entries; i++) {
const char *key = sdb_fmt ("entry%d", i);
const char *value = sdb_const_get (sdb, key, 0);
if (value) {
if (oValue && !strcmp (value, oValue)) {
continue;
}
if (IS_MODE_JSON (mode)) {
if (i > 0) { r_cons_printf (","); }
char *escaped_value = r_str_escape (value);
r_cons_printf ("{\"idx\":%"PFMT64u",\"value\":\"%s\"}",
(ut64) i, escaped_value);
free (escaped_value);
} else {
r_cons_printf (" 0x%08"PFMT64x": ", (ut64) i);
r_cons_printf ("%s\n", value);
}
oValue = value;
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
} else {
r_cons_printf ("\n\n");
}
firstit_for_versym = false;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("],\"verneed\":[");
}
bool firstit_dowhile_verneed = true;
do {
char *verneed_path = r_str_newf (format, "verneed", num_verneed++);
if (!(sdb = sdb_ns_path (r->sdb, verneed_path, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_verneed) {
r_cons_printf (",");
}
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
sdb_const_get (sdb, "section_name", 0), sdb_num_get (sdb, "addr", 0), sdb_num_get (sdb, "offset", 0));
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
sdb_num_get (sdb, "link", 0), sdb_const_get (sdb, "link_section_name", 0));
} else {
r_cons_printf ("Version need section '%s' contains %d entries:\n",
sdb_const_get (sdb, "section_name", 0), (int)sdb_num_get (sdb, "num_entries", 0));
r_cons_printf (" Addr: 0x%08"PFMT64x, sdb_num_get (sdb, "addr", 0));
r_cons_printf (" Offset: 0x%08"PFMT64x" Link to section: %"PFMT64d" (%s)\n",
sdb_num_get (sdb, "offset", 0), sdb_num_get (sdb, "link", 0),
sdb_const_get (sdb, "link_section_name", 0));
}
bool firstit_for_verneed = true;
for (num_version = 0;; num_version++) {
const char *filename = NULL;
int num_vernaux = 0;
char *path_version = sdb_fmt ("%s/version%d", verneed_path, num_version);
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_for_verneed) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64u",\"vn_version\":%d,",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Version: %d",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
}
if ((filename = sdb_const_get (sdb, "file_name", 0))) {
if (IS_MODE_JSON (mode)) {
char *escaped_filename = r_str_escape (filename);
r_cons_printf ("\"file_name\":\"%s\",", escaped_filename);
free (escaped_filename);
} else {
r_cons_printf (" File: %s", filename);
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"cnt\":%d,", (int)sdb_num_get (sdb, "cnt", 0));
} else {
r_cons_printf (" Cnt: %d\n", (int)sdb_num_get (sdb, "cnt", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"vernaux\":[");
}
bool firstit_dowhile_vernaux = true;
do {
const char *path_vernaux = sdb_fmt ("%s/vernaux%d", path_version, num_vernaux++);
if (!(sdb = sdb_ns_path (r->sdb, path_vernaux, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_vernaux) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64u",\"name\":\"%s\",",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf ("\"flags\":\"%s\",\"version\":%d}",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Name: %s",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf (" Flags: %s Version: %d\n",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
}
firstit_dowhile_vernaux = false;
} while (sdb);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
}
firstit_for_verneed = false;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
}
firstit_dowhile_verneed = false;
free (verneed_path);
} while (sdb);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
}
}
static void bin_mach0_versioninfo(RCore *r) {
/* TODO */
}
static void bin_pe_resources(RCore *r, int mode) {
Sdb *sdb = NULL;
int index = 0;
PJ *pj = NULL;
const char *pe_path = "bin/cur/info/pe_resource";
if (!(sdb = sdb_ns_path (r->sdb, pe_path, 0))) {
return;
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_RESOURCES);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs resources\n");
} else if (IS_MODE_JSON (mode)) {
pj = pj_new ();
pj_a (pj);
}
while (true) {
const char *timestrKey = sdb_fmt ("resource.%d.timestr", index);
const char *vaddrKey = sdb_fmt ("resource.%d.vaddr", index);
const char *sizeKey = sdb_fmt ("resource.%d.size", index);
const char *typeKey = sdb_fmt ("resource.%d.type", index);
const char *languageKey = sdb_fmt ("resource.%d.language", index);
const char *nameKey = sdb_fmt ("resource.%d.name", index);
char *timestr = sdb_get (sdb, timestrKey, 0);
if (!timestr) {
break;
}
ut64 vaddr = sdb_num_get (sdb, vaddrKey, 0);
int size = (int)sdb_num_get (sdb, sizeKey, 0);
char *name = sdb_get (sdb, nameKey, 0);
char *type = sdb_get (sdb, typeKey, 0);
char *lang = sdb_get (sdb, languageKey, 0);
if (IS_MODE_SET (mode)) {
const char *name = sdb_fmt ("resource.%d", index);
r_flag_set (r->flags, name, vaddr, size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f resource.%d %d 0x%08"PFMT32x"\n", index, size, vaddr);
} else if (IS_MODE_JSON (mode)) {
pj_o (pj);
pj_ks (pj, "name", name);
pj_ki (pj, "index", index);
pj_ks (pj, "type", type);
pj_kn (pj, "vaddr", vaddr);
pj_ki (pj, "size", size);
pj_ks (pj, "lang", lang);
pj_ks (pj, "timestamp", timestr);
pj_end (pj);
} else {
char humansz[8];
r_num_units (humansz, sizeof (humansz), size);
r_cons_printf ("Resource %d\n", index);
r_cons_printf (" name: %s\n", name);
r_cons_printf (" timestamp: %s\n", timestr);
r_cons_printf (" vaddr: 0x%08"PFMT64x"\n", vaddr);
r_cons_printf (" size: %s\n", humansz);
r_cons_printf (" type: %s\n", type);
r_cons_printf (" language: %s\n", lang);
}
R_FREE (timestr);
R_FREE (name);
R_FREE (type);
R_FREE (lang)
index++;
}
if (IS_MODE_JSON (mode)) {
pj_end (pj);
r_cons_printf ("%s\n", pj_string (pj));
pj_free (pj);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs *");
}
}
static void bin_no_resources(RCore *r, int mode) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[]");
}
}
static int bin_resources(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_resources (r, mode);
} else {
bin_no_resources (r, mode);
}
return true;
}
static int bin_versioninfo(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_versioninfo (r, mode);
} else if (!strncmp ("elf", info->rclass, 3)) {
bin_elf_versioninfo (r, mode);
} else if (!strncmp ("mach0", info->rclass, 5)) {
bin_mach0_versioninfo (r);
} else {
r_cons_println ("Unknown format");
return false;
}
return true;
}
static int bin_signature(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->signature) {
const char *signature = plg->signature (cur, IS_MODE_JSON (mode));
r_cons_println (signature);
free ((char*) signature);
return true;
}
return false;
}
R_API void r_core_bin_export_info_rad(RCore *core) {
Sdb *db = NULL;
char *flagname = NULL, *offset = NULL;
RBinFile *bf = r_bin_cur (core->bin);
if (!bf) {
return;
}
db = sdb_ns (bf->sdb, "info", 0);;
if (db) {
SdbListIter *iter;
SdbKv *kv;
r_cons_printf ("fs format\n");
// iterate over all keys
SdbList *ls = sdb_foreach_list (db, false);
ls_foreach (ls, iter, kv) {
char *k = sdbkv_key (kv);
char *v = sdbkv_value (kv);
char *dup = strdup (k);
//printf ("?e (%s) (%s)\n", k, v);
if ((flagname = strstr (dup, ".offset"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("f %s @ %s\n", flagname, v);
free (offset);
offset = strdup (v);
}
if ((flagname = strstr (dup, ".cparse"))) {
r_cons_printf ("\"td %s\"\n", v);
}
free (dup);
}
R_FREE (offset);
ls_foreach (ls, iter, kv) {
char *k = sdbkv_key (kv);
char *v = sdbkv_value (kv);
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
r_cons_printf ("pf.%s %s\n", flagname, v);
}
free (dup);
}
ls_foreach (ls, iter, kv) {
char *k = sdbkv_key (kv);
char *v = sdbkv_value (kv);
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
int fmtsize = r_print_format_struct_size (core->print, v, 0, 0);
char *offset_key = r_str_newf ("%s.offset", flagname);
const char *off = sdb_const_get (db, offset_key, 0);
free (offset_key);
if (off) {
r_cons_printf ("Cf %d %s @ %s\n", fmtsize, v, off);
}
}
if ((flagname = strstr (dup, ".size"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("fl %s %s\n", flagname, v);
}
free (dup);
}
free (offset);
}
}
static int bin_header(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->header) {
plg->header (cur);
return true;
}
return false;
}
R_API int r_core_bin_info(RCore *core, int action, int mode, int va, RCoreBinFilter *filter, const char *chksum) {
int ret = true;
const char *name = NULL;
ut64 at = 0, loadaddr = r_bin_get_laddr (core->bin);
if (filter && filter->offset) {
at = filter->offset;
}
if (filter && filter->name) {
name = filter->name;
}
// use our internal values for va
va = va ? VA_TRUE : VA_FALSE;
#if 0
if (r_config_get_i (core->config, "anal.strings")) {
r_core_cmd0 (core, "aar");
}
#endif
if ((action & R_CORE_BIN_ACC_STRINGS)) {
ret &= bin_strings (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_RAW_STRINGS)) {
ret &= bin_raw_strings (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_INFO)) {
ret &= bin_info (core, mode, loadaddr);
}
if ((action & R_CORE_BIN_ACC_MAIN)) {
ret &= bin_main (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_DWARF)) {
ret &= bin_dwarf (core, mode);
}
if ((action & R_CORE_BIN_ACC_PDB)) {
ret &= bin_pdb (core, mode);
}
if ((action & R_CORE_BIN_ACC_SOURCE)) {
ret &= bin_source (core, mode);
}
if ((action & R_CORE_BIN_ACC_ENTRIES)) {
ret &= bin_entry (core, mode, loadaddr, va, false);
}
if ((action & R_CORE_BIN_ACC_INITFINI)) {
ret &= bin_entry (core, mode, loadaddr, va, true);
}
if ((action & R_CORE_BIN_ACC_SECTIONS)) {
ret &= bin_sections (core, mode, loadaddr, va, at, name, chksum, false);
}
if ((action & R_CORE_BIN_ACC_SEGMENTS)) {
ret &= bin_sections (core, mode, loadaddr, va, at, name, chksum, true);
}
if (r_config_get_i (core->config, "bin.relocs")) {
if ((action & R_CORE_BIN_ACC_RELOCS)) {
ret &= bin_relocs (core, mode, va);
}
}
if ((action & R_CORE_BIN_ACC_LIBS)) {
ret &= bin_libs (core, mode);
}
if ((action & R_CORE_BIN_ACC_IMPORTS)) { // 5s
ret &= bin_imports (core, mode, va, name);
}
if ((action & R_CORE_BIN_ACC_EXPORTS)) {
ret &= bin_symbols (core, mode, loadaddr, va, at, name, true, chksum);
}
if ((action & R_CORE_BIN_ACC_SYMBOLS)) { // 6s
ret &= bin_symbols (core, mode, loadaddr, va, at, name, false, chksum);
}
if ((action & R_CORE_BIN_ACC_CLASSES)) { // 6s
ret &= bin_classes (core, mode);
}
if ((action & R_CORE_BIN_ACC_TRYCATCH)) {
ret &= bin_trycatch (core, mode);
}
if ((action & R_CORE_BIN_ACC_SIZE)) {
ret &= bin_size (core, mode);
}
if ((action & R_CORE_BIN_ACC_MEM)) {
ret &= bin_mem (core, mode);
}
if ((action & R_CORE_BIN_ACC_VERSIONINFO)) {
ret &= bin_versioninfo (core, mode);
}
if ((action & R_CORE_BIN_ACC_RESOURCES)) {
ret &= bin_resources (core, mode);
}
if ((action & R_CORE_BIN_ACC_SIGNATURE)) {
ret &= bin_signature (core, mode);
}
if ((action & R_CORE_BIN_ACC_FIELDS)) {
if (IS_MODE_SIMPLE (mode)) {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
/* ignore mode, just for quiet/simple here */
ret &= bin_fields (core, 0, va);
}
} else {
if (IS_MODE_NORMAL (mode)) {
ret &= bin_header (core, mode);
} else {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
ret &= bin_fields (core, mode, va);
}
}
}
}
return ret;
}
R_API int r_core_bin_set_arch_bits(RCore *r, const char *name, const char * arch, ut16 bits) {
int fd = r_io_fd_get_current (r->io);
RIODesc *desc = r_io_desc_get (r->io, fd);
RBinFile *curfile, *binfile = NULL;
if (!name) {
if (!desc || !desc->name) {
return false;
}
name = desc->name;
}
/* Check if the arch name is a valid name */
if (!r_asm_is_valid (r->assembler, arch)) {
return false;
}
/* Find a file with the requested name/arch/bits */
binfile = r_bin_file_find_by_arch_bits (r->bin, arch, bits);
if (!binfile) {
return false;
}
if (!r_bin_use_arch (r->bin, arch, bits, name)) {
return false;
}
curfile = r_bin_cur (r->bin);
//set env if the binfile changed or we are dealing with xtr
if (curfile != binfile || binfile->curxtr) {
r_core_bin_set_cur (r, binfile);
return r_core_bin_set_env (r, binfile);
}
return true;
}
R_API int r_core_bin_update_arch_bits(RCore *r) {
RBinFile *binfile = NULL;
const char *name = NULL, *arch = NULL;
ut16 bits = 0;
if (!r) {
return 0;
}
if (r->assembler) {
bits = r->assembler->bits;
if (r->assembler->cur) {
arch = r->assembler->cur->arch;
}
}
binfile = r_bin_cur (r->bin);
name = binfile ? binfile->file : NULL;
if (binfile && binfile->curxtr) {
r_anal_hint_clear (r->anal);
}
return r_core_bin_set_arch_bits (r, name, arch, bits);
}
R_API bool r_core_bin_raise(RCore *core, ut32 bfid) {
if (!r_bin_select_bfid (core->bin, bfid)) {
return false;
}
RBinFile *bf = r_bin_cur (core->bin);
if (bf) {
r_io_use_fd (core->io, bf->fd);
}
// it should be 0 to use r_io_use_fd in r_core_block_read
core->switch_file_view = 0;
return bf && r_core_bin_set_env (core, bf) && r_core_block_read (core);
}
R_API bool r_core_bin_delete(RCore *core, ut32 bf_id) {
if (bf_id == UT32_MAX) {
return false;
}
#if 0
if (!r_bin_object_delete (core->bin, bf_id)) {
return false;
}
// TODO: use rbinat()
RBinFile *bf = r_bin_cur (core->bin);
if (bf) {
r_io_use_fd (core->io, bf->fd);
}
#endif
r_bin_file_delete (core->bin, bf_id);
RBinFile *bf = r_bin_file_at (core->bin, core->offset);
if (bf) {
r_io_use_fd (core->io, bf->fd);
}
core->switch_file_view = 0;
return bf && r_core_bin_set_env (core, bf) && r_core_block_read (core);
}
static bool r_core_bin_file_print(RCore *core, RBinFile *bf, int mode) {
r_return_val_if_fail (core && bf && bf->o, NULL);
const char *name = bf ? bf->file : NULL;
(void)r_bin_get_info (core->bin); // XXX is this necssary for proper iniitialization
ut32 bin_sz = bf ? bf->size : 0;
// TODO: handle mode to print in json and r2 commands
switch (mode) {
case '*':
{
char *n = __filterShell (name);
r_cons_printf ("oba 0x%08"PFMT64x" %s # %d\n", bf->o->boffset, n, bf->id);
free (n);
}
break;
case 'q':
r_cons_printf ("%d\n", bf->id);
break;
case 'j':
// XXX there's only one binobj for each bf...so we should change that json
// TODO: use pj API
r_cons_printf ("{\"name\":\"%s\",\"iofd\":%d,\"bfid\":%d,\"size\":%d,\"objs\":[",
name? name: "", bf->fd, bf->id, bin_sz);
{
RBinObject *obj = bf->o;
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *asmarch = r_config_get (core->config, "asm.arch");
const char *arch = info ? info->arch ? info->arch: asmarch : "unknown";
r_cons_printf ("{\"arch\":\"%s\",\"bits\":%d,\"binoffset\":%"
PFMT64d",\"objsize\":%"PFMT64d"}",
arch, bits, obj->boffset, obj->obj_size);
}
r_cons_print ("]}");
break;
default:
{
RBinInfo *info = bf->o->info;
ut8 bits = info ? info->bits : 0;
const char *asmarch = r_config_get (core->config, "asm.arch");
const char *arch = info ? info->arch ? info->arch: asmarch: "unknown";
r_cons_printf ("%d %d %s-%d ba:0x%08"PFMT64x" sz:%"PFMT64d" %s\n",
bf->id, bf->fd, arch, bits, bf->o->baddr, bf->o->size, name);
}
break;
}
return true;
}
R_API int r_core_bin_list(RCore *core, int mode) {
// list all binfiles and there objects and there archs
int count = 0;
RListIter *iter;
RBinFile *binfile = NULL; //, *cur_bf = r_bin_cur (core->bin) ;
RBin *bin = core->bin;
const RList *binfiles = bin ? bin->binfiles: NULL;
if (!binfiles) {
return false;
}
if (mode == 'j') {
r_cons_print ("[");
}
r_list_foreach (binfiles, iter, binfile) {
r_core_bin_file_print (core, binfile, mode);
if (iter->n && mode == 'j') {
r_cons_print (",");
}
}
if (mode == 'j') {
r_cons_println ("]");
}
return count;
}
R_API char *r_core_bin_method_flags_str(ut64 flags, int mode) {
int i, len = 0;
RStrBuf *buf = r_strbuf_new ("");
if (IS_MODE_SET (mode) || IS_MODE_RAD (mode)) {
if (!flags) {
goto out;
}
for (i = 0; i < 64; i++) {
ut64 flag = flags & (1ULL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (flag_string) {
r_strbuf_appendf (buf, ".%s", flag_string);
}
}
}
} else if (IS_MODE_JSON (mode)) {
if (!flags) {
r_strbuf_append (buf, "[]");
goto out;
}
r_strbuf_append (buf, "[");
for (i = 0; i < 64; i++) {
ut64 flag = flags & (1ULL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (len != 0) {
r_strbuf_append (buf, ",");
}
if (flag_string) {
r_strbuf_appendf (buf, "\"%s\"", flag_string);
} else {
r_strbuf_appendf (buf, "\"0x%08"PFMT64x"\"", flag);
}
len++;
}
}
r_strbuf_append (buf, "]");
} else {
int pad_len = 4; //TODO: move to a config variable
if (!flags) {
goto padding;
}
for (i = 0; i < 64; i++) {
ut64 flag = flags & (1ULL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, true);
if (flag_string) {
r_strbuf_append (buf, flag_string);
} else {
r_strbuf_append (buf, "?");
}
len++;
}
}
padding:
for ( ; len < pad_len; len++) {
r_strbuf_append (buf, " ");
}
}
out:
return r_strbuf_drain (buf);
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/bad_1103_0 |
crossvul-cpp_data_good_1103_0 | /* radare - LGPL - Copyright 2011-2019 - earada, pancake */
#include <r_core.h>
#include <r_config.h>
#include "r_util.h"
#include "r_util/r_time.h"
#define is_in_range(at, from, sz) ((at) >= (from) && (at) < ((from) + (sz)))
#define VA_FALSE 0
#define VA_TRUE 1
#define VA_NOREBASE 2
#define LOAD_BSS_MALLOC 0
#define IS_MODE_SET(mode) ((mode) & R_MODE_SET)
#define IS_MODE_SIMPLE(mode) ((mode) & R_MODE_SIMPLE)
#define IS_MODE_SIMPLEST(mode) ((mode) & R_MODE_SIMPLEST)
#define IS_MODE_JSON(mode) ((mode) & R_MODE_JSON)
#define IS_MODE_RAD(mode) ((mode) & R_MODE_RADARE)
#define IS_MODE_EQUAL(mode) ((mode) & R_MODE_EQUAL)
#define IS_MODE_NORMAL(mode) (!(mode))
#define IS_MODE_CLASSDUMP(mode) ((mode) & R_MODE_CLASSDUMP)
// dup from cmd_info
#define PAIR_WIDTH 9
#define bprintf if (binfile && binfile->rbin && binfile->rbin->verbose) eprintf
static void pair(const char *key, const char *val, int mode, bool last) {
if (!val || !*val) {
return;
}
if (IS_MODE_JSON (mode)) {
const char *lst = last ? "" : ",";
r_cons_printf ("\"%s\":%s%s", key, val, lst);
} else {
char ws[16];
const int keyl = strlen (key);
const int wl = (keyl > PAIR_WIDTH) ? 0 : PAIR_WIDTH - keyl;
memset (ws, ' ', wl);
ws[wl] = 0;
r_cons_printf ("%s%s%s\n", key, ws, val);
}
}
static void pair_bool(const char *key, bool val, int mode, bool last) {
pair (key, r_str_bool (val), mode, last);
}
static void pair_int(const char *key, int val, int mode, bool last) {
pair (key, sdb_fmt ("%d", val), mode, last);
}
static void pair_ut64(const char *key, ut64 val, int mode, bool last) {
pair (key, sdb_fmt ("%"PFMT64d, val), mode, last);
}
static char *__filterQuotedShell(const char *arg) {
r_return_val_if_fail (arg, NULL);
char *a = malloc (strlen (arg) + 1);
if (!a) {
return NULL;
}
char *b = a;
while (*arg) {
switch (*arg) {
case ' ':
case '=':
case '"':
case '\\':
case '\r':
case '\n':
break;
default:
*b++ = *arg;
break;
}
arg++;
}
*b = 0;
return a;
}
// TODO: move into libr/util/name.c
static char *__filterShell(const char *arg) {
r_return_val_if_fail (arg, NULL);
char *a = malloc (strlen (arg) + 1);
if (!a) {
return NULL;
}
char *b = a;
while (*arg) {
char ch = *arg;
switch (ch) {
case '@':
case '`':
case '|':
case ';':
case '=':
case '\n':
break;
default:
*b++ = ch;
break;
}
arg++;
}
*b = 0;
return a;
}
static void pair_ut64x(const char *key, ut64 val, int mode, bool last) {
const char *str_val = IS_MODE_JSON (mode) ? sdb_fmt ("%"PFMT64d, val) : sdb_fmt ("0x%"PFMT64x, val);
pair (key, str_val, mode, last);
}
static void pair_str(const char *key, const char *val, int mode, int last) {
if (IS_MODE_JSON (mode)) {
if (!val) {
val = "";
}
char *encval = r_str_escape_utf8_for_json (val, -1);
if (encval) {
char *qs = r_str_newf ("\"%s\"", encval);
pair (key, qs, mode, last);
free (encval);
free (qs);
}
} else {
pair (key, val, mode, last);
}
}
#define STR(x) (x)? (x): ""
R_API int r_core_bin_set_cur(RCore *core, RBinFile *binfile);
static ut64 rva(RBin *bin, ut64 paddr, ut64 vaddr, int va) {
if (va == VA_TRUE) {
if (paddr != UT64_MAX) {
return r_bin_get_vaddr (bin, paddr, vaddr);
}
}
if (va == VA_NOREBASE) {
return vaddr;
}
return paddr;
}
R_API int r_core_bin_set_by_fd(RCore *core, ut64 bin_fd) {
if (r_bin_file_set_cur_by_fd (core->bin, bin_fd)) {
r_core_bin_set_cur (core, r_bin_cur (core->bin));
return true;
}
return false;
}
R_API int r_core_bin_set_by_name(RCore *core, const char * name) {
if (r_bin_file_set_cur_by_name (core->bin, name)) {
r_core_bin_set_cur (core, r_bin_cur (core->bin));
return true;
}
return false;
}
R_API int r_core_bin_set_env(RCore *r, RBinFile *binfile) {
r_return_val_if_fail (r, false);
RBinObject *binobj = binfile? binfile->o: NULL;
RBinInfo *info = binobj? binobj->info: NULL;
if (info) {
int va = info->has_va;
const char *arch = info->arch;
ut16 bits = info->bits;
ut64 baseaddr = r_bin_get_baddr (r->bin);
r_config_set_i (r->config, "bin.baddr", baseaddr);
sdb_num_add (r->sdb, "orig_baddr", baseaddr, 0);
r_config_set (r->config, "asm.arch", arch);
r_config_set_i (r->config, "asm.bits", bits);
r_config_set (r->config, "anal.arch", arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "anal.cpu", info->cpu);
} else {
r_config_set (r->config, "anal.cpu", arch);
}
r_asm_use (r->assembler, arch);
r_core_bin_info (r, R_CORE_BIN_ACC_ALL, R_MODE_SET, va, NULL, NULL);
r_core_bin_set_cur (r, binfile);
return true;
}
return false;
}
R_API int r_core_bin_set_cur(RCore *core, RBinFile *binfile) {
if (!core->bin) {
return false;
}
if (!binfile) {
// Find first available binfile
ut32 fd = r_core_file_cur_fd (core);
binfile = fd != (ut32)-1
? r_bin_file_find_by_fd (core->bin, fd)
: NULL;
if (!binfile) {
return false;
}
}
r_bin_file_set_cur_binfile (core->bin, binfile);
return true;
}
R_API int r_core_bin_refresh_strings(RCore *r) {
return r_bin_reset_strings (r->bin)? true: false;
}
static void _print_strings(RCore *r, RList *list, int mode, int va) {
bool b64str = r_config_get_i (r->config, "bin.b64str");
int minstr = r_config_get_i (r->config, "bin.minstr");
int maxstr = r_config_get_i (r->config, "bin.maxstr");
RBin *bin = r->bin;
RBinObject *obj = r_bin_cur_object (bin);
RListIter *iter;
RListIter *last_processed = NULL;
RBinString *string;
RBinSection *section;
char *q;
bin->minstrlen = minstr;
bin->maxstrlen = maxstr;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
if (IS_MODE_RAD (mode)) {
r_cons_println ("fs strings");
}
if (IS_MODE_SET (mode) && r_config_get_i (r->config, "bin.strings")) {
r_flag_space_set (r->flags, R_FLAGS_FS_STRINGS);
r_cons_break_push (NULL, NULL);
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("[Strings]\n");
r_cons_printf ("Num Paddr Vaddr Len Size Section Type String\n");
}
RBinString b64 = { 0 };
r_list_foreach (list, iter, string) {
const char *section_name, *type_string;
ut64 paddr, vaddr;
paddr = string->paddr;
vaddr = rva (r->bin, paddr, string->vaddr, va);
if (!r_bin_string_filter (bin, string->string, vaddr)) {
continue;
}
if (string->length < minstr) {
continue;
}
if (maxstr && string->length > maxstr) {
continue;
}
section = obj? r_bin_get_section_at (obj, paddr, 0): NULL;
section_name = section ? section->name : "";
type_string = r_bin_string_type (string->type);
if (b64str) {
ut8 *s = r_base64_decode_dyn (string->string, -1);
if (s && *s && IS_PRINTABLE (*s)) {
// TODO: add more checks
free (b64.string);
memcpy (&b64, string, sizeof (b64));
b64.string = (char *)s;
b64.size = strlen (b64.string);
string = &b64;
}
}
if (IS_MODE_SET (mode)) {
char *f_name, *f_realname, *str;
if (r_cons_is_breaked ()) {
break;
}
r_meta_add (r->anal, R_META_TYPE_STRING, vaddr, vaddr + string->size, string->string);
f_name = strdup (string->string);
r_name_filter (f_name, -1);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
f_realname = r_str_newf ("%s.\"%s\"", r->bin->prefix, string->string);
} else {
str = r_str_newf ("str.%s", f_name);
f_realname = r_str_newf ("\"%s\"", string->string);
}
RFlagItem *flag = r_flag_set (r->flags, str, vaddr, string->size);
r_flag_item_set_realname (flag, f_realname);
free (str);
free (f_name);
free (f_realname);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%"PFMT64x" %d %d %s\n", vaddr,
string->size, string->length, string->string);
} else if (IS_MODE_SIMPLEST (mode)) {
r_cons_println (string->string);
} else if (IS_MODE_JSON (mode)) {
int *block_list;
q = r_base64_encode_dyn (string->string, -1);
r_cons_printf ("%s{\"vaddr\":%"PFMT64u
",\"paddr\":%"PFMT64u",\"ordinal\":%d"
",\"size\":%d,\"length\":%d,\"section\":\"%s\","
"\"type\":\"%s\",\"string\":\"%s\"",
last_processed ? ",": "",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string, q);
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string, -1, NULL);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't include block list if
just Basic Latin (0x00 - 0x7F) */
R_FREE (block_list);
break;
}
int *block_ptr = block_list;
r_cons_printf (",\"blocks\":[");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *utfName = r_utf_block_name (*block_ptr);
r_cons_printf ("\"%s\"", utfName? utfName: "");
}
r_cons_printf ("]");
R_FREE (block_list);
}
}
r_cons_printf ("}");
free (q);
} else if (IS_MODE_RAD (mode)) {
char *f_name = strdup (string->string);
r_name_filter (f_name, R_FLAG_NAME_SIZE);
char *str = (r->bin->prefix)
? r_str_newf ("%s.str.%s", r->bin->prefix, f_name)
: r_str_newf ("str.%s", f_name);
r_cons_printf ("f %s %"PFMT64d" 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
str, string->size, vaddr,
string->size, vaddr);
free (str);
free (f_name);
} else {
int *block_list;
char *str = string->string;
char *no_dbl_bslash_str = NULL;
if (!r->print->esc_bslash) {
char *ptr;
for (ptr = str; *ptr; ptr++) {
if (*ptr != '\\') {
continue;
}
if (*(ptr + 1) == '\\') {
if (!no_dbl_bslash_str) {
no_dbl_bslash_str = strdup (str);
if (!no_dbl_bslash_str) {
break;
}
ptr = no_dbl_bslash_str + (ptr - str);
}
memmove (ptr + 1, ptr + 2, strlen (ptr + 2) + 1);
}
}
if (no_dbl_bslash_str) {
str = no_dbl_bslash_str;
}
}
r_cons_printf ("%03u 0x%08" PFMT64x " 0x%08" PFMT64x " %3u %3u (%s) %5s %s",
string->ordinal, paddr, vaddr,
string->length, string->size,
section_name, type_string, str);
if (str == no_dbl_bslash_str) {
R_FREE (str);
}
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string, -1, NULL);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't show block list if
just Basic Latin (0x00 - 0x7F) */
break;
}
int *block_ptr = block_list;
r_cons_printf (" blocks=");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *name = r_utf_block_name (*block_ptr);
r_cons_printf ("%s", name? name: "");
}
free (block_list);
}
break;
}
r_cons_printf ("\n");
}
last_processed = iter;
}
R_FREE (b64.string);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
}
if (IS_MODE_SET (mode)) {
r_cons_break_pop ();
}
}
static bool bin_raw_strings(RCore *r, int mode, int va) {
RBinFile *bf = r_bin_cur (r->bin);
bool new_bf = false;
if (bf && strstr (bf->file, "malloc://")) {
//sync bf->buf to search string on it
ut8 *tmp = R_NEWS (ut8, bf->size);
if (!tmp) {
return false;
}
r_io_read_at (r->io, 0, tmp, bf->size);
r_buf_write_at (bf->buf, 0, tmp, bf->size);
}
if (!r->file) {
eprintf ("Core file not open\n");
if (IS_MODE_JSON (mode)) {
r_cons_print ("[]");
}
return false;
}
if (!bf) {
bf = R_NEW0 (RBinFile);
if (!bf) {
return false;
}
RIODesc *desc = r_io_desc_get (r->io, r->file->fd);
if (!desc) {
free (bf);
return false;
}
bf->file = strdup (desc->name);
bf->size = r_io_desc_size (desc);
if (bf->size == UT64_MAX) {
free (bf);
return false;
}
bf->buf = r_buf_new_with_io (&r->bin->iob, r->file->fd);
bf->o = NULL;
bf->rbin = r->bin;
new_bf = true;
va = false;
}
RList *l = r_bin_raw_strings (bf, 0);
_print_strings (r, l, mode, va);
r_list_free (l);
if (new_bf) {
r_buf_free (bf->buf);
bf->buf = NULL;
bf->id = -1;
r_bin_file_free (bf);
}
return true;
}
static bool bin_strings(RCore *r, int mode, int va) {
RList *list;
RBinFile *binfile = r_bin_cur (r->bin);
RBinPlugin *plugin = r_bin_file_cur_plugin (binfile);
int rawstr = r_config_get_i (r->config, "bin.rawstr");
if (!binfile) {
return false;
}
if (!r_config_get_i (r->config, "bin.strings")) {
return false;
}
if (!plugin) {
return false;
}
if (plugin->info && plugin->name) {
if (strcmp (plugin->name, "any") == 0 && !rawstr) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
}
if (!(list = r_bin_get_strings (r->bin))) {
return false;
}
_print_strings (r, list, mode, va);
return true;
}
static const char* get_compile_time(Sdb *binFileSdb) {
Sdb *info_ns = sdb_ns (binFileSdb, "info", false);
const char *timeDateStamp_string = sdb_const_get (info_ns,
"image_file_header.TimeDateStamp_string", 0);
return timeDateStamp_string;
}
static bool is_executable(RBinObject *obj) {
RListIter *it;
RBinSection* sec;
r_return_val_if_fail (obj, false);
if (obj->info && obj->info->arch) {
return true;
}
r_list_foreach (obj->sections, it, sec) {
if (sec->perm & R_PERM_X) {
return true;
}
}
return false;
}
static void sdb_concat_by_path(Sdb *s, const char *path) {
Sdb *db = sdb_new (0, path, 0);
sdb_merge (s, db);
sdb_close (db);
sdb_free (db);
}
R_API void r_core_anal_type_init(RCore *core) {
r_return_if_fail (core && core->anal);
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
int bits = core->assembler->bits;
Sdb *types = core->anal->sdb_types;
// make sure they are empty this is initializing
sdb_reset (types);
const char *anal_arch = r_config_get (core->config, "anal.arch");
const char *os = r_config_get (core->config, "asm.os");
// spaguetti ahead
const char *dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types.sdb"), dir_prefix);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s.sdb"),
dir_prefix, anal_arch);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s.sdb"),
dir_prefix, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%d.sdb"),
dir_prefix, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%d.sdb"),
dir_prefix, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%d.sdb"),
dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%s.sdb"),
dir_prefix, anal_arch, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (R_JOIN_3_PATHS ("%s", R2_SDB_FCNSIGN, "types-%s-%s-%d.sdb"),
dir_prefix, anal_arch, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
}
static int save_ptr(void *p, const char *k, const char *v) {
Sdb *sdbs[2];
sdbs[0] = ((Sdb**) p)[0];
sdbs[1] = ((Sdb**) p)[1];
if (!strncmp (v, "cc", strlen ("cc") + 1)) {
const char *x = sdb_const_get (sdbs[1], sdb_fmt ("cc.%s.name", k), 0);
char *tmp = sdb_fmt ("%p", x);
sdb_set (sdbs[0], tmp, x, 0);
}
return 1;
}
R_API void r_core_anal_cc_init(RCore *core) {
Sdb *sdbs[2] = {
sdb_new0 (),
core->anal->sdb_cc
};
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
//save pointers and values stored inside them
//to recover from freeing heeps
const char *defaultcc = sdb_const_get (sdbs[1], "default.cc", 0);
sdb_set (sdbs[0], sdb_fmt ("0x%08"PFMT64x, r_num_get (NULL, defaultcc)), defaultcc, 0);
sdb_foreach (core->anal->sdb_cc, save_ptr, sdbs);
sdb_reset (core->anal->sdb_cc);
const char *anal_arch = r_config_get (core->config, "anal.arch");
int bits = core->anal->bits;
char *dbpath = sdb_fmt ("%s/"R2_SDB_FCNSIGN"/cc-%s-%d.sdb", dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (core->anal->sdb_cc, dbpath);
}
//restore all freed CC or replace with new default cc
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
const char *cc = NULL;
if (fcn->cc) {
char *ptr = sdb_fmt ("%p", fcn->cc);
cc = sdb_const_get (sdbs[0], ptr, 0);
}
if (!cc) {
cc = r_anal_cc_default (core->anal);
}
fcn->cc = r_str_const (cc);
}
sdb_close (sdbs[0]);
sdb_free (sdbs[0]);
}
static int bin_info(RCore *r, int mode, ut64 laddr) {
int i, j, v;
char str[R_FLAG_NAME_SIZE];
RBinInfo *info = r_bin_get_info (r->bin);
RBinFile *bf = r_bin_cur (r->bin);
if (!bf) {
return false;
}
RBinObject *obj = bf->o;
const char *compiled = NULL;
bool havecode;
if (!bf || !info || !obj) {
if (mode & R_MODE_JSON) {
r_cons_printf ("{}");
}
return false;
}
havecode = is_executable (obj) | (obj->entries != NULL);
compiled = get_compile_time (bf->sdb);
if (IS_MODE_SET (mode)) {
r_config_set (r->config, "file.type", info->rclass);
r_config_set (r->config, "cfg.bigendian",
info->big_endian ? "true" : "false");
if (info->rclass && !strcmp (info->rclass, "fs")) {
// r_config_set (r->config, "asm.arch", info->arch);
// r_core_seek (r, 0, 1);
// eprintf ("m /root %s 0", info->arch);
// r_core_cmdf (r, "m /root hfs @ 0", info->arch);
} else {
if (info->lang) {
r_config_set (r->config, "bin.lang", info->lang);
}
r_config_set (r->config, "asm.os", info->os);
if (info->rclass && !strcmp (info->rclass, "pe")) {
r_config_set (r->config, "anal.cpp.abi", "msvc");
} else {
r_config_set (r->config, "anal.cpp.abi", "itanium");
}
r_config_set (r->config, "asm.arch", info->arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "asm.cpu", info->cpu);
}
r_config_set (r->config, "anal.arch", info->arch);
snprintf (str, R_FLAG_NAME_SIZE, "%i", info->bits);
r_config_set (r->config, "asm.bits", str);
r_config_set (r->config, "asm.dwarf",
(R_BIN_DBG_STRIPPED & info->dbg_info) ? "false" : "true");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_config_set_i (r->config, "asm.pcalign", v);
}
}
r_core_anal_type_init (r);
r_core_anal_cc_init (r);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("arch %s\n", info->arch);
if (info->cpu && *info->cpu) {
r_cons_printf ("cpu %s\n", info->cpu);
}
r_cons_printf ("bits %d\n", info->bits);
r_cons_printf ("os %s\n", info->os);
r_cons_printf ("endian %s\n", info->big_endian? "big": "little");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
r_cons_printf ("minopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
r_cons_printf ("maxopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_cons_printf ("pcalign %d\n", v);
}
} else if (IS_MODE_RAD (mode)) {
if (info->type && !strcmp (info->type, "fs")) {
r_cons_printf ("e file.type=fs\n");
r_cons_printf ("m /root %s 0\n", info->arch);
} else {
r_cons_printf ("e cfg.bigendian=%s\n"
"e asm.bits=%i\n"
"e asm.dwarf=%s\n",
r_str_bool (info->big_endian),
info->bits,
r_str_bool (R_BIN_DBG_STRIPPED &info->dbg_info));
if (info->lang && *info->lang) {
r_cons_printf ("e bin.lang=%s\n", info->lang);
}
if (info->rclass && *info->rclass) {
r_cons_printf ("e file.type=%s\n",
info->rclass);
}
if (info->os) {
r_cons_printf ("e asm.os=%s\n", info->os);
}
if (info->arch) {
r_cons_printf ("e asm.arch=%s\n", info->arch);
}
if (info->cpu && *info->cpu) {
r_cons_printf ("e asm.cpu=%s\n", info->cpu);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_cons_printf ("e asm.pcalign=%d\n", v);
}
}
} else {
// XXX: if type is 'fs' show something different?
char *tmp_buf;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{");
}
pair_str ("arch", info->arch, mode, false);
if (info->cpu && *info->cpu) {
pair_str ("cpu", info->cpu, mode, false);
}
pair_ut64x ("baddr", r_bin_get_baddr (r->bin), mode, false);
pair_ut64 ("binsz", r_bin_get_size (r->bin), mode, false);
pair_str ("bintype", info->rclass, mode, false);
pair_int ("bits", info->bits, mode, false);
pair_bool ("canary", info->has_canary, mode, false);
if (info->has_retguard != -1) {
pair_bool ("retguard", info->has_retguard, mode, false);
}
pair_str ("class", info->bclass, mode, false);
if (info->actual_checksum) {
/* computed checksum */
pair_str ("cmp.csum", info->actual_checksum, mode, false);
}
pair_str ("compiled", compiled, mode, false);
pair_str ("compiler", info->compiler, mode, false);
pair_bool ("crypto", info->has_crypto, mode, false);
pair_str ("dbg_file", info->debug_file_name, mode, false);
pair_str ("endian", info->big_endian ? "big" : "little", mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
tmp_buf = sdb_get (bf->sdb, "mdmp.flags", 0);
if (tmp_buf) {
pair_str ("flags", tmp_buf, mode, false);
free (tmp_buf);
}
}
pair_bool ("havecode", havecode, mode, false);
if (info->claimed_checksum) {
/* checksum specified in header */
pair_str ("hdr.csum", info->claimed_checksum, mode, false);
}
pair_str ("guid", info->guid, mode, false);
pair_str ("intrp", info->intrp, mode, false);
pair_ut64x ("laddr", laddr, mode, false);
pair_str ("lang", info->lang, mode, false);
pair_bool ("linenum", R_BIN_DBG_LINENUMS & info->dbg_info, mode, false);
pair_bool ("lsyms", R_BIN_DBG_SYMS & info->dbg_info, mode, false);
pair_str ("machine", info->machine, mode, false);
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
pair_int ("maxopsz", v, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
pair_int ("minopsz", v, mode, false);
}
pair_bool ("nx", info->has_nx, mode, false);
pair_str ("os", info->os, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
pair_bool ("overlay", info->pe_overlay, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
pair_int ("pcalign", v, mode, false);
}
pair_bool ("pic", info->has_pi, mode, false);
pair_bool ("relocs", R_BIN_DBG_RELOCS & info->dbg_info, mode, false);
Sdb *sdb_info = sdb_ns (obj->kv, "info", false);
tmp_buf = sdb_get (sdb_info, "elf.relro", 0);
if (tmp_buf) {
pair_str ("relro", tmp_buf, mode, false);
free (tmp_buf);
}
pair_str ("rpath", info->rpath, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
//this should be moved if added to mach0 (or others)
pair_bool ("signed", info->signature, mode, false);
}
pair_bool ("sanitiz", info->has_sanitizers, mode, false);
pair_bool ("static", r_bin_is_static (r->bin), mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
v = sdb_num_get (bf->sdb, "mdmp.streams", 0);
if (v != -1) {
pair_int ("streams", v, mode, false);
}
}
pair_bool ("stripped", R_BIN_DBG_STRIPPED & info->dbg_info, mode, false);
pair_str ("subsys", info->subsystem, mode, false);
pair_bool ("va", info->has_va, mode, true);
if (IS_MODE_JSON (mode)) {
r_cons_printf (",\"checksums\":{");
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
ut8 *tmp = R_NEWS (ut8, h->to);
if (!tmp) {
return false;
}
r_buf_read_at (bf->buf, h->from, tmp, h->to);
int len = r_hash_calculate (rh, hash, tmp, h->to);
free (tmp);
if (len < 1) {
eprintf ("Invalid checksum length\n");
}
r_hash_free (rh);
r_cons_printf ("%s\"%s\":{\"hex\":\"", i?",": "", h->type);
// r_cons_printf ("%s\t%d-%dc\t", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_printf ("\"}");
}
r_cons_printf ("}");
} else {
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
ut8 *tmp = R_NEWS (ut8, h->to);
if (!tmp) {
return false;
}
r_buf_read_at (bf->buf, h->from, tmp, h->to);
int len = r_hash_calculate (rh, hash, tmp, h->to);
free (tmp);
if (len < 1) {
eprintf ("Invalid wtf\n");
}
r_hash_free (rh);
r_cons_printf ("%s %d-%dc ", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_newline ();
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("}");
}
}
const char *dir_prefix = r_config_get (r->config, "dir.prefix");
char *spath = sdb_fmt ("%s/"R2_SDB_FCNSIGN"/spec.sdb", dir_prefix);
if (r_file_exists (spath)) {
sdb_concat_by_path (r->anal->sdb_fmts, spath);
}
return true;
}
static int bin_dwarf(RCore *core, int mode) {
RBinDwarfRow *row;
RListIter *iter;
RList *list = NULL;
if (!r_config_get_i (core->config, "bin.dbginfo")) {
return false;
}
RBinFile *binfile = r_bin_cur (core->bin);
RBinPlugin * plugin = r_bin_file_cur_plugin (binfile);
if (!binfile) {
return false;
}
if (plugin && plugin->lines) {
list = plugin->lines (binfile);
} else if (core->bin) {
// TODO: complete and speed-up support for dwarf
RBinDwarfDebugAbbrev *da = NULL;
da = r_bin_dwarf_parse_abbrev (core->bin, mode);
r_bin_dwarf_parse_info (da, core->bin, mode);
r_bin_dwarf_parse_aranges (core->bin, mode);
list = r_bin_dwarf_parse_line (core->bin, mode);
r_bin_dwarf_free_debug_abbrev (da);
free (da);
}
if (!list) {
return false;
}
r_cons_break_push (NULL, NULL);
/* cache file:line contents */
const char *lastFile = NULL;
int *lastFileLines = NULL;
char *lastFileContents = NULL;
int lastFileLinesCount = 0;
/* ugly dupe for speedup */
const char *lastFile2 = NULL;
int *lastFileLines2 = NULL;
char *lastFileContents2 = NULL;
int lastFileLinesCount2 = 0;
const char *lf = NULL;
int *lfl = NULL;
char *lfc = NULL;
int lflc = 0;
//TODO we should need to store all this in sdb, or do a filecontentscache in libr/util
//XXX this whole thing has leaks
r_list_foreach (list, iter, row) {
if (r_cons_is_breaked ()) {
break;
}
if (mode) {
// TODO: use 'Cl' instead of CC
const char *path = row->file;
if (!lastFile || strcmp (path, lastFile)) {
if (lastFile && lastFile2 && !strcmp (path, lastFile2)) {
lf = lastFile;
lfl = lastFileLines;
lfc = lastFileContents;
lflc = lastFileLinesCount;
lastFile = lastFile2;
lastFileLines = lastFileLines2;
lastFileContents = lastFileContents2;
lastFileLinesCount = lastFileLinesCount2;
lastFile2 = lf;
lastFileLines2 = lfl;
lastFileContents2 = lfc;
lastFileLinesCount2 = lflc;
} else {
lastFile2 = lastFile;
lastFileLines2 = lastFileLines;
lastFileContents2 = lastFileContents;
lastFileLinesCount2 = lastFileLinesCount;
lastFile = path;
lastFileContents = r_file_slurp (path, NULL);
if (lastFileContents) {
lastFileLines = r_str_split_lines (lastFileContents, &lastFileLinesCount);
}
}
}
char *line = NULL;
//r_file_slurp_line (path, row->line - 1, 0);
if (lastFileLines && lastFileContents) {
int nl = row->line - 1;
if (nl >= 0 && nl < lastFileLinesCount) {
line = strdup (lastFileContents + lastFileLines[nl]);
}
} else {
line = NULL;
}
if (line) {
r_str_filter (line, strlen (line));
line = r_str_replace (line, "\"", "\\\"", 1);
line = r_str_replace (line, "\\\\", "\\", 1);
}
bool chopPath = !r_config_get_i (core->config, "dir.dwarf.abspath");
char *file = strdup (row->file);
if (chopPath) {
const char *slash = r_str_lchr (file, '/');
if (slash) {
memmove (file, slash + 1, strlen (slash));
}
}
// TODO: implement internal : if ((mode & R_MODE_SET))
if ((mode & R_MODE_SET)) {
// TODO: use CL here.. but its not necessary.. so better not do anything imho
// r_core_cmdf (core, "CL %s:%d 0x%08"PFMT64x, file, (int)row->line, row->address);
#if 0
char *cmt = r_str_newf ("%s:%d %s", file, (int)row->line, line? line: "");
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, row->address, cmt);
free (cmt);
#endif
} else {
r_cons_printf ("CL %s:%d 0x%08" PFMT64x "\n",
file, (int)row->line,
row->address);
r_cons_printf ("\"CC %s:%d %s\"@0x%" PFMT64x
"\n",
file, row->line,
line ? line : "", row->address);
}
free (file);
free (line);
} else {
r_cons_printf ("0x%08" PFMT64x "\t%s\t%d\n",
row->address, row->file, row->line);
}
}
r_cons_break_pop ();
R_FREE (lastFileContents);
R_FREE (lastFileContents2);
// this list is owned by rbin, not us, we shouldn't free it
// r_list_free (list);
free (lastFileLines);
return true;
}
R_API int r_core_pdb_info(RCore *core, const char *file, ut64 baddr, int mode) {
R_PDB pdb = R_EMPTY;
pdb.cb_printf = r_cons_printf;
if (!init_pdb_parser (&pdb, file)) {
return false;
}
if (!pdb.pdb_parse (&pdb)) {
eprintf ("pdb was not parsed\n");
pdb.finish_pdb_parse (&pdb);
return false;
}
if (mode == R_MODE_JSON) {
r_cons_printf ("[");
}
switch (mode) {
case R_MODE_SET:
mode = 's';
r_core_cmd0 (core, ".iP*");
return true;
case R_MODE_JSON:
mode = 'j';
break;
case '*':
case 1:
mode = 'r';
break;
default:
mode = 'd'; // default
break;
}
pdb.print_types (&pdb, mode);
if (mode == 'j') {
r_cons_printf (",");
}
pdb.print_gvars (&pdb, baddr, mode);
if (mode == 'j') {
r_cons_printf ("]");
}
pdb.finish_pdb_parse (&pdb);
return true;
}
static int bin_pdb(RCore *core, int mode) {
ut64 baddr = r_bin_get_baddr (core->bin);
return r_core_pdb_info (core, core->bin->file, baddr, mode);
}
static int srclineCmp(const void *a, const void *b) {
return r_str_cmp (a, b, -1);
}
static int bin_source(RCore *r, int mode) {
RList *final_list = r_list_new ();
RBinFile * binfile = r->bin->cur;
if (!binfile) {
bprintf ("[Error bin file]\n");
r_list_free (final_list);
return false;
}
SdbListIter *iter;
RListIter *iter2;
char* srcline;
SdbKv *kv;
SdbList *ls = sdb_foreach_list (binfile->sdb_addrinfo, false);
ls_foreach (ls, iter, kv) {
char *v = sdbkv_value (kv);
RList *list = r_str_split_list (v, "|", 0);
srcline = r_list_get_bottom (list);
if (srcline) {
if (!strstr (srcline, "0x")){
r_list_append (final_list, srcline);
}
}
r_list_free (list);
}
r_cons_printf ("[Source file]\n");
RList *uniqlist = r_list_uniq (final_list, srclineCmp);
r_list_foreach (uniqlist, iter2, srcline) {
r_cons_printf ("%s\n", srcline);
}
r_list_free (uniqlist);
r_list_free (final_list);
return true;
}
static int bin_main(RCore *r, int mode, int va) {
RBinAddr *binmain = r_bin_get_sym (r->bin, R_BIN_SYM_MAIN);
ut64 addr;
if (!binmain) {
return false;
}
addr = va ? r_bin_a2b (r->bin, binmain->vaddr) : binmain->paddr;
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
r_flag_set (r->flags, "main", addr, r->blocksize);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("%"PFMT64d, addr);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
r_cons_printf ("f main @ 0x%08"PFMT64x"\n", addr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"vaddr\":%" PFMT64d
",\"paddr\":%" PFMT64d "}", addr, binmain->paddr);
} else {
r_cons_printf ("[Main]\n");
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x"\n",
addr, binmain->paddr);
}
return true;
}
static inline bool is_initfini(RBinAddr *entry) {
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
return true;
default:
return false;
}
}
static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RListIter *last_processed = NULL;
RBinAddr *entry = NULL;
int i = 0, init_i = 0, fini_i = 0, preinit_i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 hpaddr = UT64_MAX;
ut64 hvaddr = UT64_MAX;
if (mode != R_MODE_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
if (entry->hpaddr) {
hpaddr = entry->hpaddr;
if (entry->hvaddr) {
hvaddr = rva (r->bin, hpaddr, entry->hvaddr, va);
}
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
const char *hpaddr_key = (entry->type == R_BIN_ENTRY_TYPE_PROGRAM)
? "haddr" : "hpaddr";
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry.init%i", init_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry.fini%i", fini_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry.preinit%i", preinit_i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
if (is_initfini (entry) && hvaddr != UT64_MAX) {
r_meta_add (r->anal, R_META_TYPE_DATA, hvaddr,
hvaddr + entry->bits / 8, NULL);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64u ","
"\"paddr\":%" PFMT64u ","
"\"baddr\":%" PFMT64u ","
"\"laddr\":%" PFMT64u ",",
last_processed ? "," : "", at, paddr, baddr, laddr);
if (hvaddr != UT64_MAX) {
r_cons_printf ("\"hvaddr\":%" PFMT64u ",", hvaddr);
}
r_cons_printf ("\"%s\":%" PFMT64u ","
"\"type\":\"%s\"}",
hpaddr_key, hpaddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry.init%i", init_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry.fini%i", fini_i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry.preinit%i", preinit_i);
} else {
name = r_str_newf ("entry%i", i);
}
char *n = __filterQuotedShell (name);
r_cons_printf ("\"f %s 1 0x%08"PFMT64x"\"\n", n, at);
r_cons_printf ("\"f %s_%s 1 0x%08"PFMT64x"\"\n", n, hpaddr_key, hpaddr);
r_cons_printf ("\"s %s\"\n", n);
free (n);
free (name);
} else {
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x, at, paddr);
if (is_initfini (entry) && hvaddr != UT64_MAX) {
r_cons_printf (" hvaddr=0x%08"PFMT64x, hvaddr);
}
r_cons_printf (" %s=", hpaddr_key);
if (hpaddr == UT64_MAX) {
r_cons_printf ("%"PFMT64d, hpaddr);
} else {
r_cons_printf ("0x%08"PFMT64x, hpaddr);
}
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM && hvaddr != UT64_MAX) {
r_cons_printf (" hvaddr=0x%08"PFMT64x, hvaddr);
}
r_cons_printf (" type=%s\n", type);
}
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
init_i++;
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
fini_i++;
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
preinit_i++;
} else {
i++;
}
last_processed = iter;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", init_i + fini_i + preinit_i + i);
}
return true;
}
static const char *bin_reloc_type_name(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return reloc->additive ? "ADD_" #T : "SET_" #T
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return "UNKNOWN";
#undef CASE
}
static ut8 bin_reloc_size(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return (T) / 8
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return 0;
#undef CASE
}
static char *resolveModuleOrdinal(Sdb *sdb, const char *module, int ordinal) {
Sdb *db = sdb;
char *foo = sdb_get (db, sdb_fmt ("%d", ordinal), 0);
return (foo && *foo) ? foo : NULL;
}
static char *get_reloc_name(RCore *r, RBinReloc *reloc, ut64 addr) {
char *reloc_name = NULL;
char *demangled_name = NULL;
const char *lang = r_config_get (r->config, "bin.lang");
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
if (reloc->import && reloc->import->name) {
if (bin_demangle) {
demangled_name = r_bin_demangle (r->bin->cur, lang, reloc->import->name, addr, keep_lib);
}
reloc_name = sdb_fmt ("reloc.%s_%d", demangled_name ? demangled_name : reloc->import->name,
(int)(addr & 0xff));
if (!reloc_name) {
free (demangled_name);
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->symbol && reloc->symbol->name) {
if (bin_demangle) {
demangled_name = r_bin_demangle (r->bin->cur, lang, reloc->symbol->name, addr, keep_lib);
}
reloc_name = sdb_fmt ("reloc.%s_%d", demangled_name ? demangled_name : reloc->symbol->name,
(int)(addr & 0xff));
if (!reloc_name) {
free (demangled_name);
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->is_ifunc) {
// addend is the function pointer for the resolving ifunc
reloc_name = sdb_fmt ("reloc.ifunc_%"PFMT64x, reloc->addend);
} else {
// TODO(eddyb) implement constant relocs.
}
free (demangled_name);
return reloc_name;
}
static void set_bin_relocs(RCore *r, RBinReloc *reloc, ut64 addr, Sdb **db, char **sdb_module) {
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
const char *lang = r_config_get (r->config, "bin.lang");
char *reloc_name, *demname = NULL;
bool is_pe = true;
int is_sandbox = r_sandbox_enable (0);
if (reloc->import && reloc->import->name[0]) {
char str[R_FLAG_NAME_SIZE];
RFlagItem *fi;
if (is_pe && !is_sandbox && strstr (reloc->import->name, "Ordinal")) {
const char *TOKEN = ".dll_Ordinal_";
char *module = strdup (reloc->import->name);
char *import = strstr (module, TOKEN);
r_str_case (module, false);
if (import) {
char *filename = NULL;
int ordinal;
*import = 0;
import += strlen (TOKEN);
ordinal = atoi (import);
if (!*sdb_module || strcmp (module, *sdb_module)) {
sdb_free (*db);
*db = NULL;
free (*sdb_module);
*sdb_module = strdup (module);
/* always lowercase */
filename = sdb_fmt ("%s.sdb", module);
r_str_case (filename, false);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
} else {
const char *dirPrefix = r_sys_prefix (NULL);
filename = sdb_fmt (R_JOIN_4_PATHS ("%s", R2_SDB_FORMAT, "dll", "%s.sdb"),
dirPrefix, module);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
}
}
}
if (*db) {
// ordinal-1 because we enumerate starting at 0
char *symname = resolveModuleOrdinal (*db, module, ordinal - 1); // uses sdb_get
if (symname) {
if (r->bin->prefix) {
reloc->import->name = r_str_newf
("%s.%s.%s", r->bin->prefix, module, symname);
} else {
reloc->import->name = r_str_newf
("%s.%s", module, symname);
}
R_FREE (symname);
}
}
}
free (module);
r_anal_hint_set_size (r->anal, reloc->vaddr, 4);
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr+4, NULL);
}
reloc_name = reloc->import->name;
if (r->bin->prefix) {
snprintf (str, R_FLAG_NAME_SIZE, "%s.reloc.%s", r->bin->prefix, reloc_name);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "reloc.%s", reloc_name);
}
if (bin_demangle) {
demname = r_bin_demangle (r->bin->cur, lang, str, addr, keep_lib);
if (demname) {
snprintf (str, R_FLAG_NAME_SIZE, "reloc.%s", demname);
}
}
r_name_filter (str, 0);
fi = r_flag_set (r->flags, str, addr, bin_reloc_size (reloc));
if (demname) {
char *realname;
if (r->bin->prefix) {
realname = sdb_fmt ("%s.reloc.%s", r->bin->prefix, demname);
} else {
realname = sdb_fmt ("reloc.%s", demname);
}
r_flag_item_set_realname (fi, realname);
}
} else {
char *reloc_name = get_reloc_name (r, reloc, addr);
if (reloc_name) {
r_flag_set (r->flags, reloc_name, addr, bin_reloc_size (reloc));
} else {
// eprintf ("Cannot find a name for 0x%08"PFMT64x"\n", addr);
}
}
}
/* Define new data at relocation address if it's not in an executable section */
static void add_metadata(RCore *r, RBinReloc *reloc, ut64 addr, int mode) {
RBinFile * binfile = r->bin->cur;
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
int cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (cdsz == 0) {
return;
}
RIOMap *map = r_io_map_get (r->io, addr);
if (!map || map ->perm & R_PERM_X) {
return;
}
if (IS_MODE_SET (mode)) {
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr + cdsz, NULL);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("Cd %d @ 0x%08" PFMT64x "\n", cdsz, addr);
}
}
static bool is_section_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
if (!s || *s->name) {
return false;
}
return (s->type && !strcmp (s->type, R_BIN_TYPE_SECTION_STR));
}
static bool is_special_symbol(RBinSymbol *s) {
return s->type && !strcmp (s->type, R_BIN_TYPE_SPECIAL_SYM_STR);
}
static bool is_section_reloc(RBinReloc *r) {
return is_section_symbol (r->symbol);
}
static bool is_file_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
return (s && s->type && !strcmp (s->type, R_BIN_TYPE_FILE_STR));
}
static bool is_file_reloc(RBinReloc *r) {
return is_file_symbol (r->symbol);
}
static int bin_relocs(RCore *r, int mode, int va) {
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
const char *lang = r_config_get (r->config, "bin.lang");
RBIter iter;
RBinReloc *reloc = NULL;
Sdb *db = NULL;
PJ *pj = NULL;
char *sdb_module = NULL;
int i = 0;
R_TIME_BEGIN;
va = VA_TRUE; // XXX relocs always vaddr?
//this has been created for reloc object files
RBNode *relocs = r_bin_patch_relocs (r->bin);
if (!relocs) {
relocs = r_bin_get_relocs (r->bin);
}
if (IS_MODE_RAD (mode)) {
r_cons_println ("fs relocs");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Relocations]");
} else if (IS_MODE_JSON (mode)) {
// start a new JSON object
pj = pj_new ();
if (pj) {
pj_a (pj);
}
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_RELOCS);
}
r_rbtree_foreach (relocs, iter, reloc, RBinReloc, vrb) {
ut64 addr = rva (r->bin, reloc->paddr, reloc->vaddr, va);
if (IS_MODE_SET (mode) && (is_section_reloc (reloc) || is_file_reloc (reloc))) {
/*
* Skip section reloc because they will have their own flag.
* Skip also file reloc because not useful for now.
*/
} else if (IS_MODE_SET (mode)) {
set_bin_relocs (r, reloc, addr, &db, &sdb_module);
add_metadata (r, reloc, addr, mode);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" %s\n", addr, reloc->import ? reloc->import->name : "");
} else if (IS_MODE_RAD (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: (reloc->symbol ? strdup (reloc->symbol->name) : NULL);
if (name && bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr, keep_lib);
if (mn) {
free (name);
name = mn;
}
}
if (name) {
int reloc_size = 4;
char *n = __filterQuotedShell (name);
r_cons_printf ("\"f %s%s%s %d 0x%08"PFMT64x"\"\n",
r->bin->prefix ? r->bin->prefix : "reloc.",
r->bin->prefix ? "." : "", n, reloc_size, addr);
add_metadata (r, reloc, addr, mode);
free (n);
free (name);
}
} else if (IS_MODE_JSON (mode)) {
if (pj) {
pj_o (pj);
char *mn = NULL;
char *relname = NULL;
// take care with very long symbol names! do not use sdb_fmt or similar
if (reloc->import) {
mn = r_bin_demangle (r->bin->cur, lang, reloc->import->name, addr, keep_lib);
relname = strdup (reloc->import->name);
} else if (reloc->symbol) {
mn = r_bin_demangle (r->bin->cur, lang, reloc->symbol->name, addr, keep_lib);
relname = strdup (reloc->symbol->name);
}
// check if name is available
pj_ks (pj, "name", (relname && strcmp (relname, "")) ? relname : "N/A");
pj_ks (pj, "demname", mn ? mn : "");
pj_ks (pj, "type", bin_reloc_type_name (reloc));
pj_kn (pj, "vaddr", reloc->vaddr);
pj_kn (pj, "paddr", reloc->paddr);
if (reloc->symbol) {
pj_kn (pj, "sym_va", reloc->symbol->vaddr);
}
pj_kb (pj, "is_ifunc", reloc->is_ifunc);
// end reloc item
pj_end (pj);
free (mn);
if (relname) {
free (relname);
}
}
} else if (IS_MODE_NORMAL (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: reloc->symbol
? strdup (reloc->symbol->name)
: strdup ("null");
if (bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr, keep_lib);
if (mn && *mn) {
free (name);
name = mn;
}
}
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" type=%s",
addr, reloc->paddr, bin_reloc_type_name (reloc));
if (reloc->import && reloc->import->name[0]) {
r_cons_printf (" %s", name);
} else if (reloc->symbol && name && name[0]) {
r_cons_printf (" %s", name);
}
R_FREE (name);
if (reloc->addend) {
if ((reloc->import || (reloc->symbol && !R_STR_ISEMPTY (name))) && reloc->addend > 0) {
r_cons_printf (" +");
}
if (reloc->addend < 0) {
r_cons_printf (" - 0x%08"PFMT64x, -reloc->addend);
} else {
r_cons_printf (" 0x%08"PFMT64x, reloc->addend);
}
}
if (reloc->is_ifunc) {
r_cons_print (" (ifunc)");
}
r_cons_newline ();
}
i++;
}
if (IS_MODE_JSON (mode)) {
// close Json output
pj_end (pj);
r_cons_println (pj_string (pj));
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i relocations\n", i);
}
// free PJ object if used
if (pj) {
pj_free (pj);
}
R_FREE (sdb_module);
sdb_free (db);
db = NULL;
R_TIME_END;
return relocs != NULL;
}
#define MYDB 1
/* this is a hacky workaround that needs proper refactoring in Rbin to use Sdb */
#if MYDB
static Sdb *mydb = NULL;
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol, *res = NULL;
RListIter *iter;
if (mydb && symbols && symbols != osymbols) {
sdb_free (mydb);
mydb = NULL;
osymbols = symbols;
}
if (mydb) {
if (name) {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("%x", sdb_hash (name)), NULL);
} else {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("0x"PFMT64x, addr), NULL);
}
} else {
mydb = sdb_new0 ();
r_list_foreach (symbols, iter, symbol) {
if (!symbol->name) {
continue;
}
/* ${name}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("%x", sdb_hash (symbol->name)), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
/* 0x${vaddr}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("0x"PFMT64x, symbol->vaddr), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
if (name) {
if (!res && !strcmp (symbol->name, name)) {
res = symbol;
}
} else {
if (symbol->vaddr == addr) {
res = symbol;
}
}
}
osymbols = symbols;
}
return res;
}
#else
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol;
RListIter *iter;
// XXX this is slow, we should use a hashtable here
r_list_foreach (symbols, iter, symbol) {
if (name) {
if (!strcmp (symbol->name, name))
return symbol;
} else {
if (symbol->vaddr == addr) {
return symbol;
}
}
}
return NULL;
}
#endif
/* XXX: This is a hack to get PLT references in rabin2 -i */
/* imp. is a prefix that can be rewritten by the symbol table */
R_API ut64 r_core_bin_impaddr(RBin *bin, int va, const char *name) {
RList *symbols;
if (!name || !*name) {
return false;
}
if (!(symbols = r_bin_get_symbols (bin))) {
return false;
}
char *impname = r_str_newf ("imp.%s", name);
RBinSymbol *s = get_symbol (bin, symbols, impname, 0LL);
// maybe ut64_MAX to indicate import not found?
ut64 addr = 0LL;
if (s) {
if (va) {
if (s->paddr == UT64_MAX) {
addr = s->vaddr;
} else {
addr = r_bin_get_vaddr (bin, s->paddr, s->vaddr);
}
} else {
addr = s->paddr;
}
}
free (impname);
return addr;
}
static int bin_imports(RCore *r, int mode, int va, const char *name) {
RBinInfo *info = r_bin_get_info (r->bin);
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
RBinImport *import;
RListIter *iter;
bool lit = info ? info->has_lit: false;
char *str;
int i = 0;
if (!info) {
return false;
}
RList *imports = r_bin_get_imports (r->bin);
int cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs imports");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Imports]");
r_cons_println ("Num Vaddr Bind Type Name");
}
r_list_foreach (imports, iter, import) {
if (name && strcmp (import->name, name)) {
continue;
}
char *symname = strdup (import->name);
ut64 addr = lit ? r_core_bin_impaddr (r->bin, va, symname): 0;
if (bin_demangle) {
char *dname = r_bin_demangle (r->bin->cur, NULL, symname, addr, keep_lib);
if (dname) {
free (symname);
symname = r_str_newf ("sym.imp.%s", dname);
free (dname);
}
}
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, symname);
free (symname);
symname = prname;
}
if (IS_MODE_SET (mode)) {
// TODO(eddyb) symbols that are imports.
// Add a dword/qword for PE imports
if (strstr (symname, ".dll_") && cdsz) {
r_meta_add (r->anal, R_META_TYPE_DATA, addr, addr + cdsz, NULL);
}
} else if (IS_MODE_SIMPLE (mode) || IS_MODE_SIMPLEST (mode)) {
r_cons_println (symname);
} else if (IS_MODE_JSON (mode)) {
str = r_str_escape_utf8_for_json (symname, -1);
str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"type\":\"%s\",",
iter->p ? "," : "",
import->ordinal,
import->bind,
import->type);
if (import->classname && import->classname[0]) {
r_cons_printf ("\"classname\":\"%s\","
"\"descriptor\":\"%s\",",
import->classname,
import->descriptor);
}
r_cons_printf ("\"name\":\"%s\",\"plt\":%"PFMT64d"}",
str, addr);
free (str);
} else if (IS_MODE_RAD (mode)) {
// TODO(eddyb) symbols that are imports.
} else {
const char *bind = r_str_get (import->bind);
const char *type = r_str_get (import->type);
#if 0
r_cons_printf ("ordinal=%03d plt=0x%08"PFMT64x" bind=%s type=%s",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf (" classname=%s", import->classname);
}
r_cons_printf (" name=%s", symname);
if (import->descriptor && import->descriptor[0]) {
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#else
r_cons_printf ("%4d 0x%08"PFMT64x" %7s %7s ",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf ("%s.", import->classname);
}
r_cons_printf ("%s", symname);
if (import->descriptor && import->descriptor[0]) {
// Uh?
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#endif
}
R_FREE (symname);
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
// r_cons_printf ("# %i imports\n", i);
}
#if MYDB
// NOTE: if we comment out this, it will leak.. but it will be faster
// because it will keep the cache across multiple RBin calls
osymbols = NULL;
sdb_free (mydb);
mydb = NULL;
#endif
return true;
}
static const char *getPrefixFor(const char *s) {
if (s) {
// workaround for ELF
if (!strcmp (s, R_BIN_TYPE_NOTYPE_STR)) {
return "loc";
}
if (!strcmp (s, R_BIN_TYPE_OBJECT_STR)) {
return "obj";
}
}
return "sym";
}
#define MAXFLAG_LEN_DEFAULT 128
static char *construct_symbol_flagname(const char *pfx, const char *symname, int len) {
char *r = r_str_newf ("%s.%s", pfx, symname);
if (r) {
r_name_filter (r, len); // maybe unnecessary..
char *R = __filterQuotedShell (r);
free (r);
return R;
}
return NULL;
}
typedef struct {
const char *pfx; // prefix for flags
char *name; // raw symbol name
char *nameflag; // flag name for symbol
char *demname; // demangled raw symbol name
char *demflag; // flag name for demangled symbol
char *classname; // classname
char *classflag; // flag for classname
char *methname; // methods [class]::[method]
char *methflag; // methods flag sym.[class].[method]
} SymName;
static void snInit(RCore *r, SymName *sn, RBinSymbol *sym, const char *lang) {
int bin_demangle = lang != NULL;
bool keep_lib = r_config_get_i (r->config, "bin.demangle.libs");
if (!r || !sym || !sym->name) {
return;
}
sn->name = strdup (sym->name);
const char *pfx = getPrefixFor (sym->type);
sn->nameflag = construct_symbol_flagname (pfx, r_bin_symbol_name (sym), MAXFLAG_LEN_DEFAULT);
if (sym->classname && sym->classname[0]) {
sn->classname = strdup (sym->classname);
sn->classflag = r_str_newf ("sym.%s.%s", sn->classname, sn->name);
r_name_filter (sn->classflag, MAXFLAG_LEN_DEFAULT);
const char *name = sym->dname? sym->dname: sym->name;
sn->methname = r_str_newf ("%s::%s", sn->classname, name);
sn->methflag = r_str_newf ("sym.%s.%s", sn->classname, name);
r_name_filter (sn->methflag, strlen (sn->methflag));
} else {
sn->classname = NULL;
sn->classflag = NULL;
sn->methname = NULL;
sn->methflag = NULL;
}
sn->demname = NULL;
sn->demflag = NULL;
if (bin_demangle && sym->paddr) {
sn->demname = r_bin_demangle (r->bin->cur, lang, sn->name, sym->vaddr, keep_lib);
if (sn->demname) {
sn->demflag = construct_symbol_flagname (pfx, sn->demname, -1);
}
}
}
static void snFini(SymName *sn) {
R_FREE (sn->name);
R_FREE (sn->nameflag);
R_FREE (sn->demname);
R_FREE (sn->demflag);
R_FREE (sn->classname);
R_FREE (sn->classflag);
R_FREE (sn->methname);
R_FREE (sn->methflag);
}
static bool isAnExport(RBinSymbol *s) {
/* workaround for some bin plugs */
if (!strncmp (s->name, "imp.", 4)) {
return false;
}
return (s->bind && !strcmp (s->bind, R_BIN_BIND_GLOBAL_STR));
}
static ut64 compute_addr(RBin *bin, ut64 paddr, ut64 vaddr, int va) {
return paddr == UT64_MAX? vaddr: rva (bin, paddr, vaddr, va);
}
static void handle_arm_special_symbol(RCore *core, RBinSymbol *symbol, int va) {
ut64 addr = compute_addr (core->bin, symbol->paddr, symbol->vaddr, va);
if (!strcmp (symbol->name, "$a")) {
r_anal_hint_set_bits (core->anal, addr, 32);
} else if (!strcmp (symbol->name, "$t")) {
r_anal_hint_set_bits (core->anal, addr, 16);
} else if (!strcmp (symbol->name, "$d")) {
// TODO: we could add data meta type at addr, but sometimes $d
// is in the middle of the code and it would make the code less
// readable.
} else {
R_LOG_WARN ("Special symbol %s not handled\n", symbol->name);
}
}
static void handle_arm_hint(RCore *core, RBinInfo *info, ut64 paddr, ut64 vaddr, int bits, int va) {
if (info->bits > 32) { // we look at 16 or 32 bit only
return;
}
int force_bits = 0;
ut64 addr = compute_addr (core->bin, paddr, vaddr, va);
if (paddr & 1 || bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && bits == 32) {
force_bits = 32;
} else if (!(paddr & 1) && bits == 32) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (core->anal, addr, force_bits);
}
}
static void handle_arm_symbol(RCore *core, RBinSymbol *symbol, RBinInfo *info, int va) {
return handle_arm_hint (core, info, symbol->paddr, symbol->vaddr, symbol->bits, va);
}
static void handle_arm_entry(RCore *core, RBinAddr *entry, RBinInfo *info, int va) {
return handle_arm_hint (core, info, entry->paddr, entry->vaddr, entry->bits, va);
}
static void select_flag_space(RCore *core, RBinSymbol *symbol) {
if (!strncmp (symbol->name, "imp.", 4)) {
r_flag_space_push (core->flags, R_FLAGS_FS_IMPORTS);
} else if (symbol->type && !strcmp (symbol->type, R_BIN_TYPE_SECTION_STR)) {
r_flag_space_push (core->flags, R_FLAGS_FS_SYMBOLS_SECTIONS);
} else {
r_flag_space_push (core->flags, R_FLAGS_FS_SYMBOLS);
}
}
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) {
RBinInfo *info = r_bin_get_info (r->bin);
RList *entries = r_bin_get_entries (r->bin);
RBinSymbol *symbol;
RBinAddr *entry;
RListIter *iter;
bool firstexp = true;
bool printHere = false;
int i = 0, lastfs = 's';
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
if (!info) {
return 0;
}
if (args && *args == '.') {
printHere = true;
}
bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3);
const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL;
RList *symbols = r_bin_get_symbols (r->bin);
r_spaces_push (&r->anal->meta_spaces, "bin");
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS);
} else if (!at && exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs exports\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Exports]\n");
}
} else if (!at && !exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Symbols]\n");
}
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n");
}
size_t count = 0;
r_list_foreach (symbols, iter, symbol) {
if (!symbol->name) {
continue;
}
char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true);
ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va);
int len = symbol->size ? symbol->size : 32;
SymName sn = {0};
if (exponly && !isAnExport (symbol)) {
free (r_symbol_name);
continue;
}
if (name && strcmp (r_symbol_name, name)) {
free (r_symbol_name);
continue;
}
if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {
free (r_symbol_name);
continue;
}
if ((printHere && !is_in_range (r->offset, symbol->paddr, len))
&& (printHere && !is_in_range (r->offset, addr, len))) {
free (r_symbol_name);
continue;
}
count ++;
snInit (r, &sn, symbol, lang);
if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) {
/*
* Skip section symbols because they will have their own flag.
* Skip also file symbols because not useful for now.
*/
} else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) {
if (is_arm) {
handle_arm_special_symbol (r, symbol, va);
}
} else if (IS_MODE_SET (mode)) {
// TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata
if (is_arm) {
handle_arm_symbol (r, symbol, info, va);
}
select_flag_space (r, symbol);
/* If that's a Classed symbol (method or so) */
if (sn.classname) {
RFlagItem *fi = r_flag_get (r->flags, sn.methflag);
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag);
r_name_filter (sn.methflag, -1);
free (sn.methflag);
sn.methflag = prname;
}
if (fi) {
r_flag_item_set_realname (fi, sn.methname);
if ((fi->offset - r->flags->base) == addr) {
// char *comment = fi->comment ? strdup (fi->comment) : NULL;
r_flag_unset (r->flags, fi);
}
} else {
fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);
char *comment = fi->comment ? strdup (fi->comment) : NULL;
if (comment) {
r_flag_item_set_comment (fi, comment);
R_FREE (comment);
}
}
} else {
const char *n = sn.demname ? sn.demname : sn.name;
const char *fn = sn.demflag ? sn.demflag : sn.nameflag;
char *fnp = (r->bin->prefix) ?
r_str_newf ("%s.%s", r->bin->prefix, fn):
strdup (fn);
RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size);
if (fi) {
r_flag_item_set_realname (fi, n);
fi->demangled = (bool)(size_t)sn.demname;
} else {
if (fn) {
eprintf ("[Warning] Can't find flag (%s)\n", fn);
}
}
free (fnp);
}
if (sn.demname) {
r_meta_add (r->anal, R_META_TYPE_COMMENT,
addr, symbol->size, sn.demname);
}
r_flag_space_pop (r->flags);
} else if (IS_MODE_JSON (mode)) {
char *str = r_str_escape_utf8_for_json (r_symbol_name, -1);
// str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"name\":\"%s\","
"\"demname\":\"%s\","
"\"flagname\":\"%s\","
"\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"size\":%d,"
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d"}",
((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""),
str,
sn.demname? sn.demname: "",
sn.nameflag,
symbol->ordinal,
symbol->bind,
(int)symbol->size,
symbol->type,
(ut64)addr, (ut64)symbol->paddr);
free (str);
} else if (IS_MODE_SIMPLE (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("0x%08"PFMT64x" %d %s\n",
addr, (int)symbol->size, name);
} else if (IS_MODE_SIMPLEST (mode)) {
const char *name = sn.demname? sn.demname: r_symbol_name;
r_cons_printf ("%s\n", name);
} else if (IS_MODE_RAD (mode)) {
/* Skip special symbols because we do not flag them and
* they shouldn't be printed in the rad format either */
if (is_special_symbol (symbol)) {
goto next;
}
RBinFile *binfile;
RBinPlugin *plugin;
const char *name = sn.demname? sn.demname: r_symbol_name;
if (!name) {
goto next;
}
if (!strncmp (name, "imp.", 4)) {
if (lastfs != 'i') {
r_cons_printf ("fs imports\n");
}
lastfs = 'i';
} else {
if (lastfs != 's') {
const char *fs = exponly? "exports": "symbols";
r_cons_printf ("fs %s\n", fs);
}
lastfs = 's';
}
if (r->bin->prefix || *name) { // we don't want unnamed symbol flags
char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT);
if (!flagname) {
goto next;
}
r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n",
r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "",
flagname, symbol->size, addr);
free (flagname);
}
binfile = r_bin_cur (r->bin);
plugin = r_bin_file_cur_plugin (binfile);
if (plugin && plugin->name) {
if (r_str_startswith (plugin->name, "pe")) {
char *module = strdup (r_symbol_name);
char *p = strstr (module, ".dll_");
if (p && strstr (module, "imp.")) {
char *symname = __filterShell (p + 5);
char *m = __filterShell (module);
*p = 0;
if (r->bin->prefix) {
r_cons_printf ("\"k bin/pe/%s/%d=%s.%s\"\n",
module, symbol->ordinal, r->bin->prefix, symname);
} else {
r_cons_printf ("\"k bin/pe/%s/%d=%s\"\n",
module, symbol->ordinal, symname);
}
free (symname);
free (m);
}
free (module);
}
}
} else {
const char *bind = symbol->bind? symbol->bind: "NONE";
const char *type = symbol->type? symbol->type: "NONE";
const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name);
// const char *fwd = r_str_get (symbol->forwarder);
r_cons_printf ("%03u", symbol->ordinal);
if (symbol->paddr == UT64_MAX) {
r_cons_printf (" ----------");
} else {
r_cons_printf (" 0x%08"PFMT64x, symbol->paddr);
}
r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n",
addr, bind, type, symbol->size, *name? " ": "", name);
}
next:
snFini (&sn);
i++;
free (r_symbol_name);
if (exponly && firstexp) {
firstexp = false;
}
if (printHere) {
break;
}
}
if (count == 0 && IS_MODE_JSON (mode)) {
r_cons_printf ("{}");
}
//handle thumb and arm for entry point since they are not present in symbols
if (is_arm) {
r_list_foreach (entries, iter, entry) {
if (IS_MODE_SET (mode)) {
handle_arm_entry (r, entry, info, va);
}
}
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("]");
}
r_spaces_pop (&r->anal->meta_spaces);
return true;
}
static char *build_hash_string(int mode, const char *chksum, ut8 *data, ut32 datalen) {
char *chkstr = NULL, *aux, *ret = NULL;
const char *ptr = chksum;
char tmp[128];
int i;
do {
for (i = 0; *ptr && *ptr != ',' && i < sizeof (tmp) -1; i++) {
tmp[i] = *ptr++;
}
tmp[i] = '\0';
r_str_trim_head_tail (tmp);
chkstr = r_hash_to_string (NULL, tmp, data, datalen);
if (!chkstr) {
if (*ptr && *ptr == ',') {
ptr++;
}
continue;
}
if (IS_MODE_SIMPLE (mode)) {
aux = r_str_newf ("%s ", chkstr);
} else if (IS_MODE_JSON (mode)) {
aux = r_str_newf ("\"%s\":\"%s\",", tmp, chkstr);
} else {
aux = r_str_newf ("%s=%s ", tmp, chkstr);
}
ret = r_str_append (ret, aux);
free (chkstr);
free (aux);
if (*ptr && *ptr == ',') {
ptr++;
}
} while (*ptr);
return ret;
}
typedef struct {
const char *uri;
int perm;
RIODesc *desc;
} FindFile;
static bool findFile(void *user, void *data, ut32 id) {
FindFile *res = (FindFile*)user;
RIODesc *desc = (RIODesc*)data;
if (desc->perm && res->perm && !strcmp (desc->uri, res->uri)) {
res->desc = desc;
return false;
}
return true;
}
static RIODesc *findReusableFile(RIO *io, const char *uri, int perm) {
FindFile arg = {
.uri = uri,
.perm = perm,
.desc = NULL,
};
r_id_storage_foreach (io->files, findFile, &arg);
return arg.desc;
}
static bool io_create_mem_map(RIO *io, RBinSection *sec, ut64 at) {
r_return_val_if_fail (io && sec, false);
bool reused = false;
ut64 gap = sec->vsize - sec->size;
char *uri = r_str_newf ("null://%"PFMT64u, gap);
RIODesc *desc = findReusableFile (io, uri, sec->perm);
if (desc) {
RIOMap *map = r_io_map_get (io, at);
if (!map) {
r_io_map_add_batch (io, desc->fd, desc->perm, 0LL, at, gap);
}
reused = true;
}
if (!desc) {
desc = r_io_open_at (io, uri, sec->perm, 0664, at);
}
free (uri);
if (!desc) {
return false;
}
// this works, because new maps are always born on the top
RIOMap *map = r_io_map_get (io, at);
// check if the mapping failed
if (!map) {
if (!reused) {
r_io_desc_close (desc);
}
return false;
}
// let the section refere to the map as a memory-map
map->name = r_str_newf ("mmap.%s", sec->name);
return true;
}
static void add_section(RCore *core, RBinSection *sec, ut64 addr, int fd) {
if (!r_io_desc_get (core->io, fd) || UT64_ADD_OVFCHK (sec->size, sec->paddr) ||
UT64_ADD_OVFCHK (sec->size, addr) || !sec->vsize) {
return;
}
ut64 size = sec->vsize;
// if there is some part of the section that needs to be zeroed by the loader
// we add a null map that takes care of it
if (sec->vsize > sec->size) {
if (!io_create_mem_map (core->io, sec, addr + sec->size)) {
return;
}
size = sec->size;
}
// then we map the part of the section that comes from the physical file
char *map_name = r_str_newf ("fmap.%s", sec->name);
if (!map_name) {
return;
}
int perm = sec->perm;
// workaround to force exec bit in text section
if (sec->name && strstr (sec->name, "text")) {
perm |= R_PERM_X;
}
RIOMap *map = r_io_map_add_batch (core->io, fd, perm, sec->paddr, addr, size);
if (!map) {
free (map_name);
return;
}
map->name = map_name;
return;
}
struct io_bin_section_info_t {
RBinSection *sec;
ut64 addr;
int fd;
};
static int bin_sections(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *chksum, bool print_segments) {
char *str = NULL;
RBinSection *section;
RBinInfo *info = NULL;
RList *sections;
RListIter *iter;
RListIter *last_processed = NULL;
int i = 0;
int fd = -1;
bool printHere = false;
sections = r_bin_get_sections (r->bin);
#if LOAD_BSS_MALLOC
bool inDebugger = r_config_get_i (r->config, "cfg.debug");
#endif
HtPP *dup_chk_ht = ht_pp_new0 ();
bool ret = false;
const char *type = print_segments ? "segment" : "section";
bool segments_only = true;
RList *io_section_info = NULL;
if (!dup_chk_ht) {
return false;
}
if (chksum && *chksum == '.') {
printHere = true;
}
if (IS_MODE_EQUAL (mode)) {
int cols = r_cons_get_size (NULL);
RList *list = r_list_newf ((RListFree) r_listinfo_free);
if (!list) {
return false;
}
RBinSection *s;
r_list_foreach (sections, iter, s) {
char humansz[8];
if (print_segments != s->is_segment) {
continue;
}
RInterval pitv = (RInterval){s->paddr, s->size};
RInterval vitv = (RInterval){s->vaddr, s->vsize};
r_num_units (humansz, sizeof (humansz), s->size);
RListInfo *info = r_listinfo_new (s->name, pitv, vitv, s->perm, strdup (humansz));
r_list_append (list, info);
}
r_core_visual_list (r, list, r->offset, -1, cols, r->print->flags & R_PRINT_FLAGS_COLOR);
r_list_free (list);
goto out;
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_RAD (mode) && !at) {
r_cons_printf ("fs %ss\n", type);
} else if (IS_MODE_NORMAL (mode) && !at && !printHere) {
r_cons_printf ("[%s]\n", print_segments ? "Segments" : "Sections");
} else if (IS_MODE_NORMAL (mode) && printHere) {
r_cons_printf ("Current section\n");
} else if (IS_MODE_SET (mode)) {
fd = r_core_file_cur_fd (r);
r_flag_space_set (r->flags, print_segments? R_FLAGS_FS_SEGMENTS: R_FLAGS_FS_SECTIONS);
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("Nm Paddr Size Vaddr Memsz Perms %sName\n",
chksum ? "Checksum " : "");
}
if (IS_MODE_SET (mode)) {
r_list_foreach (sections, iter, section) {
if (!section->is_segment) {
segments_only = false;
break;
}
}
io_section_info = r_list_newf ((RListFree)free);
}
r_list_foreach (sections, iter, section) {
char perms[] = "----";
int va_sect = va;
ut64 addr;
if (va && !(section->perm & R_PERM_R)) {
va_sect = VA_NOREBASE;
}
addr = rva (r->bin, section->paddr, section->vaddr, va_sect);
if (name && strcmp (section->name, name)) {
continue;
}
if ((printHere && !(section->paddr <= r->offset && r->offset < (section->paddr + section->size)))
&& (printHere && !(addr <= r->offset && r->offset < (addr + section->size)))) {
continue;
}
r_name_filter (section->name, strlen (section->name) + 1);
if (at && (!section->size || !is_in_range (at, addr, section->size))) {
continue;
}
if (section->is_segment != print_segments) {
continue;
}
if (section->perm & R_PERM_SHAR) {
perms[0] = 's';
}
if (section->perm & R_PERM_R) {
perms[1] = 'r';
}
if (section->perm & R_PERM_W) {
perms[2] = 'w';
}
if (section->perm & R_PERM_X) {
perms[3] = 'x';
}
const char *arch = NULL;
int bits = 0;
if (section->arch || section->bits) {
arch = section->arch;
bits = section->bits;
}
if (info) {
if (!arch) {
arch = info->arch;
}
if (!bits) {
bits = info->bits;
}
}
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
if (!bits) {
bits = R_SYS_BITS;
}
if (IS_MODE_RAD (mode)) {
char *n = __filterQuotedShell (section->name);
r_cons_printf ("\"f %s.%s 1 0x%08"PFMT64x"\"\n", type, n, section->vaddr);
free (n);
} else if (IS_MODE_SET (mode)) {
#if LOAD_BSS_MALLOC
if (!strcmp (section->name, ".bss")) {
// check if there's already a file opened there
int loaded = 0;
RListIter *iter;
RIOMap *m;
r_list_foreach (r->io->maps, iter, m) {
if (m->from == addr) {
loaded = 1;
}
}
if (!loaded && !inDebugger) {
r_core_cmdf (r, "on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
}
}
#endif
if (section->format) {
// This is damn slow if section vsize is HUGE
if (section->vsize < 1024 * 1024 * 2) {
r_core_cmdf (r, "%s @ 0x%"PFMT64x, section->format, section->vaddr);
}
}
if (r->bin->prefix) {
str = r_str_newf ("%s.%s.%s", r->bin->prefix, type, section->name);
} else {
str = r_str_newf ("%s.%s", type, section->name);
}
ut64 size = r->io->va? section->vsize: section->size;
r_flag_set (r->flags, str, addr, size);
R_FREE (str);
if (!section->is_segment || segments_only) {
char *pfx = r->bin->prefix;
str = r_str_newf ("[%02d] %s %s size %" PFMT64d" named %s%s%s",
i, perms, type, size,
pfx? pfx: "", pfx? ".": "", section->name);
r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, addr, str);
R_FREE (str);
}
if (section->add) {
bool found;
str = r_str_newf ("%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT32u".%s.%"PFMT32u".%d",
section->paddr, addr, section->size, section->vsize, section->perm, section->name, r->bin->cur->id, fd);
ht_pp_find (dup_chk_ht, str, &found);
if (!found) {
// can't directly add maps because they
// need to be reversed, otherwise for
// the way IO works maps would be shown
// in reverse order
struct io_bin_section_info_t *ibs = R_NEW (struct io_bin_section_info_t);
if (!ibs) {
eprintf ("Could not allocate memory\n");
goto out;
}
ibs->sec = section;
ibs->addr = addr;
ibs->fd = fd;
r_list_append (io_section_info, ibs);
ht_pp_insert (dup_chk_ht, str, NULL);
}
R_FREE (str);
}
} else if (IS_MODE_SIMPLE (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("0x%"PFMT64x" 0x%"PFMT64x" %s %s%s%s\n",
addr, addr + section->size,
perms,
hashstr ? hashstr : "", hashstr ? " " : "",
section->name
);
free (hashstr);
} else if (IS_MODE_JSON (mode)) {
char *hashstr = NULL;
if (chksum && section->size > 0) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("%s{\"name\":\"%s\","
"\"size\":%"PFMT64d","
"\"vsize\":%"PFMT64d","
"\"perm\":\"%s\","
"%s"
"\"paddr\":%"PFMT64d","
"\"vaddr\":%"PFMT64d"}",
(last_processed && !printHere) ? "," : "",
section->name,
section->size,
section->vsize,
perms,
hashstr ? hashstr : "",
section->paddr,
addr);
free (hashstr);
} else {
char *hashstr = NULL, str[128];
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
// VA READ IS BROKEN?
if (datalen > 0) {
r_io_pread_at (r->io, section->paddr, data, datalen);
}
hashstr = build_hash_string (mode, chksum, data, datalen);
free (data);
}
if (section->arch || section->bits) {
snprintf (str, sizeof (str), "arch=%s bits=%d ",
r_str_get2 (arch), bits);
} else {
str[0] = 0;
}
if (r->bin->prefix) {
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s%s%s.%s\n",
i, section->paddr, section->size, addr, section->vsize,
perms, str, hashstr ?hashstr : "", r->bin->prefix, section->name);
} else {
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s%s%s\n",
i, section->paddr, (ut64)section->size, addr, (ut64)section->vsize,
perms, str, hashstr ?hashstr : "", section->name);
}
free (hashstr);
}
i++;
last_processed = iter;
if (printHere) {
break;
}
}
if (IS_MODE_SET (mode) && !r_io_desc_is_dbg (r->io->desc)) {
RListIter *it;
struct io_bin_section_info_t *ibs;
r_list_foreach_prev (io_section_info, it, ibs) {
add_section (r, ibs->sec, ibs->addr, ibs->fd);
}
r_io_update (r->io);
r_list_free (io_section_info);
io_section_info = NULL;
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_println ("]");
} else if (IS_MODE_NORMAL (mode) && !at && !printHere) {
// r_cons_printf ("\n%i sections\n", i);
}
ret = true;
out:
ht_pp_free (dup_chk_ht);
return ret;
}
static int bin_fields(RCore *r, int mode, int va) {
RList *fields;
RListIter *iter;
RBinField *field;
int i = 0;
RBin *bin = r->bin;
if (!(fields = r_bin_get_fields (bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs header");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Header fields]");
}
r_list_foreach (fields, iter, field) {
ut64 addr = rva (bin, field->paddr, field->vaddr, va);
if (IS_MODE_RAD (mode)) {
char *n = __filterQuotedShell (field->name);
r_name_filter (n, -1);
r_cons_printf ("\"f header.%s 1 0x%08"PFMT64x"\"\n", n, addr);
if (field->comment && *field->comment) {
char *e = sdb_encode ((const ut8*)field->comment, -1);
r_cons_printf ("CCu %s @ 0x%"PFMT64x"\n", e, addr);
free (e);
char *f = __filterShell (field->format);
r_cons_printf ("Cf %d .%s @ 0x%"PFMT64x"\n", field->size, f, addr);
free (f);
}
if (field->format && *field->format) {
r_cons_printf ("pf.%s %s\n", n, field->format);
}
free (n);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"name\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d,
iter->p? ",": "",
field->name,
field->vaddr,
field->paddr
);
if (field->comment && *field->comment) {
// TODO: filter comment before json
r_cons_printf (",\"comment\":\"%s\"", field->comment);
}
if (field->format && *field->format) {
// TODO: filter comment before json
r_cons_printf (",\"format\":\"%s\"", field->format);
}
char *o = r_core_cmd_strf (r, "pfj.%s@0x%"PFMT64x, field->format, field->vaddr);
if (o && *o) {
r_cons_printf (",\"pf\":%s", o);
}
free (o);
r_cons_printf ("}");
} else if (IS_MODE_NORMAL (mode)) {
const bool haveComment = (field->comment && *field->comment);
r_cons_printf ("0x%08"PFMT64x" 0x%08"PFMT64x" %s%s%s\n",
field->vaddr, field->paddr, field->name,
haveComment? "; ": "",
haveComment? field->comment: "");
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i fields\n", i);
}
return true;
}
static char *get_rp(const char *rtype) {
char *rp = NULL;
switch (rtype[0]) {
case 'v':
rp = strdup ("void");
break;
case 'c':
rp = strdup ("char");
break;
case 'i':
rp = strdup ("int");
break;
case 's':
rp = strdup ("short");
break;
case 'l':
rp = strdup ("long");
break;
case 'q':
rp = strdup ("long long");
break;
case 'C':
rp = strdup ("unsigned char");
break;
case 'I':
rp = strdup ("unsigned int");
break;
case 'S':
rp = strdup ("unsigned short");
break;
case 'L':
rp = strdup ("unsigned long");
break;
case 'Q':
rp = strdup ("unsigned long long");
break;
case 'f':
rp = strdup ("float");
break;
case 'd':
rp = strdup ("double");
break;
case 'D':
rp = strdup ("long double");
break;
case 'B':
rp = strdup ("bool");
break;
case '#':
rp = strdup ("CLASS");
break;
default:
rp = strdup ("unknown");
break;
}
return rp;
}
static int bin_trycatch(RCore *core, int mode) {
RBinFile *bf = r_bin_cur (core->bin);
RListIter *iter;
RBinTrycatch *tc;
RList *trycatch = r_bin_file_get_trycatch (bf);
int idx = 0;
r_list_foreach (trycatch, iter, tc) {
r_cons_printf ("f try.%d.%"PFMT64x".from=0x%08"PFMT64x"\n", idx, tc->source, tc->from);
r_cons_printf ("f try.%d.%"PFMT64x".to=0x%08"PFMT64x"\n", idx, tc->source, tc->to);
r_cons_printf ("f try.%d.%"PFMT64x".catch=0x%08"PFMT64x"\n", idx, tc->source, tc->handler);
idx++;
}
return true;
}
static void classdump_objc(RCore *r, RBinClass *c) {
if (c->super) {
r_cons_printf ("@interface %s : %s\n{\n", c->name, c->super);
} else {
r_cons_printf ("@interface %s\n{\n", c->name);
}
RListIter *iter2, *iter3;
RBinField *f;
RBinSymbol *sym;
r_list_foreach (c->fields, iter2, f) {
if (f->name && r_regex_match ("ivar","e", f->name)) {
r_cons_printf (" %s %s\n", f->type, f->name);
}
}
r_cons_printf ("}\n");
r_list_foreach (c->methods, iter3, sym) {
if (sym->rtype && sym->rtype[0] != '@') {
char *rp = get_rp (sym->rtype);
r_cons_printf ("%s (%s) %s\n",
strncmp (sym->type, R_BIN_TYPE_METH_STR, 4)? "+": "-",
rp, sym->dname? sym->dname: sym->name);
free (rp);
} else if (sym->type) {
r_cons_printf ("%s (id) %s\n",
strncmp (sym->type, R_BIN_TYPE_METH_STR, 4)? "+": "-",
sym->dname? sym->dname: sym->name);
}
}
r_cons_printf ("@end\n");
}
static void classdump_java(RCore *r, RBinClass *c) {
RBinField *f;
RListIter *iter2, *iter3;
RBinSymbol *sym;
char *pn = strdup (c->name);
char *cn = (char *)r_str_rchr (pn, NULL, '/');
if (cn) {
*cn = 0;
cn++;
r_str_replace_char (pn, '/', '.');
}
r_cons_printf ("package %s;\n\n", pn);
r_cons_printf ("public class %s {\n", cn);
free (pn);
r_list_foreach (c->fields, iter2, f) {
if (f->name && r_regex_match ("ivar","e", f->name)) {
r_cons_printf (" public %s %s\n", f->type, f->name);
}
}
r_list_foreach (c->methods, iter3, sym) {
const char *mn = sym->dname? sym->dname: sym->name;
const char *ms = strstr (mn, "method.");
if (ms) {
mn = ms + strlen ("method.");
}
r_cons_printf (" public %s ();\n", mn);
}
r_cons_printf ("}\n\n");
}
static int bin_classes(RCore *r, int mode) {
RListIter *iter, *iter2, *iter3;
RBinSymbol *sym;
RBinClass *c;
RBinField *f;
char *name;
RList *cs = r_bin_get_classes (r->bin);
if (!cs) {
if (IS_MODE_JSON (mode)) {
r_cons_print ("[]");
}
return false;
}
// XXX: support for classes is broken and needs more love
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
if (!r_config_get_i (r->config, "bin.classes")) {
return false;
}
r_flag_space_set (r->flags, R_FLAGS_FS_CLASSES);
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs classes");
}
r_list_foreach (cs, iter, c) {
if (!c || !c->name || !c->name[0]) {
continue;
}
name = strdup (c->name);
r_name_filter (name, 0);
ut64 at_min = UT64_MAX;
ut64 at_max = 0LL;
r_list_foreach (c->methods, iter2, sym) {
if (sym->vaddr) {
if (sym->vaddr < at_min) {
at_min = sym->vaddr;
}
if (sym->vaddr + sym->size > at_max) {
at_max = sym->vaddr + sym->size;
}
}
}
if (at_min == UT64_MAX) {
at_min = c->addr;
at_max = c->addr; // XXX + size?
}
if (IS_MODE_SET (mode)) {
const char *classname = sdb_fmt ("class.%s", name);
r_flag_set (r->flags, classname, c->addr, 1);
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *method = sdb_fmt ("method%s.%s.%s",
mflags, c->name, sym->name);
R_FREE (mflags);
r_name_filter (method, -1);
r_flag_set (r->flags, method, sym->vaddr, 1);
}
} else if (IS_MODE_SIMPLEST (mode)) {
r_cons_printf ("%s\n", c->name);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] %s%s%s\n",
c->addr, at_min, at_max, c->name, c->super ? " " : "",
c->super ? c->super : "");
} else if (IS_MODE_RAD (mode)) {
char *n = __filterShell (name);
r_cons_printf ("\"f class.%s = 0x%"PFMT64x"\"\n", n, at_min);
free (n);
if (c->super) {
char *cn = c->name; // __filterShell (c->name);
char *su = c->super; // __filterShell (c->super);
r_cons_printf ("\"f super.%s.%s = %d\"\n",
cn, su, c->index);
// free (cn);
// free (su);
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *n = c->name; // __filterShell (c->name);
char *sn = sym->name; //__filterShell (sym->name);
char *cmd = r_str_newf ("\"f method%s.%s.%s = 0x%"PFMT64x"\"\n", mflags, n, sn, sym->vaddr);
// free (n);
// free (sn);
if (cmd) {
r_str_replace_char (cmd, ' ', '_');
if (strlen (cmd) > 2) {
cmd[2] = ' ';
}
char *eq = (char *)r_str_rchr (cmd, NULL, '=');
if (eq && eq != cmd) {
eq[-1] = eq[1] = ' ';
}
r_str_replace_char (cmd, '\n', 0);
r_cons_printf ("%s\n", cmd);
free (cmd);
}
R_FREE (mflags);
}
} else if (IS_MODE_JSON (mode)) {
if (c->super) {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"visibility\":\"%s\",\"super\":\"%s\",\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index, c->visibility_str? c->visibility_str: "", c->super);
} else {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index);
}
r_list_foreach (c->methods, iter2, sym) {
if (sym->method_flags) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, mflags, sym->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, sym->vaddr);
}
}
r_cons_printf ("], \"fields\":[");
r_list_foreach (c->fields, iter3, f) {
if (f->flags) {
char *mflags = r_core_bin_method_flags_str (f->flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, mflags, f->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, f->vaddr);
}
}
r_cons_printf ("]}");
} else if (IS_MODE_CLASSDUMP (mode)) {
if (c) {
RBinFile *bf = r_bin_cur (r->bin);
if (bf && bf->o) {
if (bf->o->lang == R_BIN_NM_JAVA || (bf->o->info && bf->o->info->lang && strstr (bf->o->info->lang, "dalvik"))) {
classdump_java (r, c);
} else {
classdump_objc (r, c);
}
} else {
classdump_objc (r, c);
}
}
} else {
int m = 0;
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] %6"PFMT64d" class %d %s",
c->addr, at_min, at_max, (at_max - at_min), c->index, c->name);
if (c->super) {
r_cons_printf (" :: %s\n", c->super);
} else {
r_cons_newline ();
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("0x%08"PFMT64x" method %d %s %s\n",
sym->vaddr, m, mflags, sym->dname? sym->dname: sym->name);
R_FREE (mflags);
m++;
}
}
free (name);
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
return true;
}
static int bin_size(RCore *r, int mode) {
ut64 size = r_bin_get_size (r->bin);
if (IS_MODE_SIMPLE (mode) || IS_MODE_JSON (mode)) {
r_cons_printf ("%"PFMT64u"\n", size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f bin_size @ %"PFMT64u"\n", size);
} else if (IS_MODE_SET (mode)) {
r_core_cmdf (r, "f bin_size @ %"PFMT64u"\n", size);
} else {
r_cons_printf ("%"PFMT64u"\n", size);
}
return true;
}
static int bin_libs(RCore *r, int mode) {
RList *libs;
RListIter *iter;
char* lib;
int i = 0;
if (!(libs = r_bin_get_libs (r->bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Linked libraries]");
}
r_list_foreach (libs, iter, lib) {
if (IS_MODE_SET (mode)) {
// Nothing to set.
// TODO: load libraries with iomaps?
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("\"CCa entry0 %s\"\n", lib);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s\"%s\"", iter->p ? "," : "", lib);
} else {
// simple and normal print mode
r_cons_println (lib);
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
if (i == 1) {
r_cons_printf ("\n%i library\n", i);
} else {
r_cons_printf ("\n%i libraries\n", i);
}
}
return true;
}
static void bin_mem_print(RList *mems, int perms, int depth, int mode) {
RBinMem *mem;
RListIter *iter;
if (!mems) {
return;
}
r_list_foreach (mems, iter, mem) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"name\":\"%s\",\"size\":%d,\"address\":%d,"
"\"flags\":\"%s\"}", mem->name, mem->size,
mem->addr, r_str_rwx_i (mem->perms & perms));
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", mem->addr);
} else {
r_cons_printf ("0x%08"PFMT64x" +0x%04x %s %*s%-*s\n",
mem->addr, mem->size, r_str_rwx_i (mem->perms & perms),
depth, "", 20-depth, mem->name);
}
if (mem->mirrors) {
if (IS_MODE_JSON (mode)) {
r_cons_printf (",");
}
bin_mem_print (mem->mirrors, mem->perms & perms, depth + 1, mode);
}
if (IS_MODE_JSON (mode)) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
static int bin_mem(RCore *r, int mode) {
RList *mem = NULL;
if (!r) {
return false;
}
if (!IS_MODE_JSON (mode)) {
if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
r_cons_println ("[Memory]\n");
}
}
if (!(mem = r_bin_get_mem (r->bin))) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
bin_mem_print (mem, 7, 0, R_MODE_JSON);
r_cons_println ("]");
return true;
} else if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
bin_mem_print (mem, 7, 0, mode);
}
return true;
}
static void bin_pe_versioninfo(RCore *r, int mode) {
Sdb *sdb = NULL;
int num_version = 0;
int num_stringtable = 0;
int num_string = 0;
const char *format_version = "bin/cur/info/vs_version_info/VS_VERSIONINFO%d";
const char *format_stringtable = "%s/string_file_info/stringtable%d";
const char *format_string = "%s/string%d";
if (!IS_MODE_JSON (mode)) {
r_cons_printf ("=== VS_VERSIONINFO ===\n\n");
}
bool firstit_dowhile = true;
do {
char *path_version = sdb_fmt (format_version, num_version);
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (!firstit_dowhile && IS_MODE_JSON (mode)) {
r_cons_printf (",");
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"VS_FIXEDFILEINFO\":{");
} else {
r_cons_printf ("# VS_FIXEDFILEINFO\n\n");
}
const char *path_fixedfileinfo = sdb_fmt ("%s/fixed_file_info", path_version);
if (!(sdb = sdb_ns_path (r->sdb, path_fixedfileinfo, 0))) {
r_cons_printf ("}");
break;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"Signature\":%"PFMT64u",", sdb_num_get (sdb, "Signature", 0));
r_cons_printf ("\"StrucVersion\":%"PFMT64u",", sdb_num_get (sdb, "StrucVersion", 0));
r_cons_printf ("\"FileVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
r_cons_printf ("\"ProductVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
r_cons_printf ("\"FileFlagsMask\":%"PFMT64u",", sdb_num_get (sdb, "FileFlagsMask", 0));
r_cons_printf ("\"FileFlags\":%"PFMT64u",", sdb_num_get (sdb, "FileFlags", 0));
r_cons_printf ("\"FileOS\":%"PFMT64u",", sdb_num_get (sdb, "FileOS", 0));
r_cons_printf ("\"FileType\":%"PFMT64u",", sdb_num_get (sdb, "FileType", 0));
r_cons_printf ("\"FileSubType\":%"PFMT64u, sdb_num_get (sdb, "FileSubType", 0));
r_cons_printf ("},");
} else {
r_cons_printf (" Signature: 0x%"PFMT64x"\n", sdb_num_get (sdb, "Signature", 0));
r_cons_printf (" StrucVersion: 0x%"PFMT64x"\n", sdb_num_get (sdb, "StrucVersion", 0));
r_cons_printf (" FileVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
r_cons_printf (" ProductVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
r_cons_printf (" FileFlagsMask: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlagsMask", 0));
r_cons_printf (" FileFlags: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlags", 0));
r_cons_printf (" FileOS: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileOS", 0));
r_cons_printf (" FileType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileType", 0));
r_cons_printf (" FileSubType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileSubType", 0));
r_cons_newline ();
}
#if 0
r_cons_printf (" FileDate: %d.%d.%d.%d\n",
sdb_num_get (sdb, "FileDateMS", 0) >> 16,
sdb_num_get (sdb, "FileDateMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileDateLS", 0) >> 16,
sdb_num_get (sdb, "FileDateLS", 0) & 0xFFFF);
#endif
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"StringTable\":{");
} else {
r_cons_printf ("# StringTable\n\n");
}
for (num_stringtable = 0; sdb; num_stringtable++) {
char *path_stringtable = r_str_newf (format_stringtable, path_version, num_stringtable);
sdb = sdb_ns_path (r->sdb, path_stringtable, 0);
bool firstit_for = true;
for (num_string = 0; sdb; num_string++) {
char *path_string = r_str_newf (format_string, path_stringtable, num_string);
sdb = sdb_ns_path (r->sdb, path_string, 0);
if (sdb) {
if (!firstit_for && IS_MODE_JSON (mode)) { r_cons_printf (","); }
int lenkey = 0;
int lenval = 0;
ut8 *key_utf16 = sdb_decode (sdb_const_get (sdb, "key", 0), &lenkey);
ut8 *val_utf16 = sdb_decode (sdb_const_get (sdb, "value", 0), &lenval);
ut8 *key_utf8 = calloc (lenkey * 2, 1);
ut8 *val_utf8 = calloc (lenval * 2, 1);
if (r_str_utf16_to_utf8 (key_utf8, lenkey * 2, key_utf16, lenkey, true) < 0
|| r_str_utf16_to_utf8 (val_utf8, lenval * 2, val_utf16, lenval, true) < 0) {
eprintf ("Warning: Cannot decode utf16 to utf8\n");
} else if (IS_MODE_JSON (mode)) {
char *escaped_key_utf8 = r_str_escape ((char*)key_utf8);
char *escaped_val_utf8 = r_str_escape ((char*)val_utf8);
r_cons_printf ("\"%s\":\"%s\"", escaped_key_utf8, escaped_val_utf8);
free (escaped_key_utf8);
free (escaped_val_utf8);
} else {
r_cons_printf (" %s: %s\n", (char*)key_utf8, (char*)val_utf8);
}
free (key_utf8);
free (val_utf8);
free (key_utf16);
free (val_utf16);
}
firstit_for = false;
free (path_string);
}
free (path_stringtable);
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("}}");
}
num_version++;
firstit_dowhile = false;
} while (sdb);
}
static void bin_elf_versioninfo(RCore *r, int mode) {
const char *format = "bin/cur/info/versioninfo/%s%d";
int num_versym;
int num_verneed = 0;
int num_version = 0;
Sdb *sdb = NULL;
const char *oValue = NULL;
bool firstit_for_versym = true;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"versym\":[");
}
for (num_versym = 0;; num_versym++) {
const char *versym_path = sdb_fmt (format, "versym", num_versym);
if (!(sdb = sdb_ns_path (r->sdb, versym_path, 0))) {
break;
}
ut64 addr = sdb_num_get (sdb, "addr", 0);
ut64 offset = sdb_num_get (sdb, "offset", 0);
ut64 link = sdb_num_get (sdb, "link", 0);
ut64 num_entries = sdb_num_get (sdb, "num_entries", 0);
const char *section_name = sdb_const_get (sdb, "section_name", 0);
const char *link_section_name = sdb_const_get (sdb, "link_section_name", 0);
if (IS_MODE_JSON (mode)) {
if (!firstit_for_versym) { r_cons_printf (","); }
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
section_name, (ut64)addr, (ut64)offset);
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
(ut32)link, link_section_name);
} else {
r_cons_printf ("Version symbols section '%s' contains %"PFMT64u" entries:\n", section_name, num_entries);
r_cons_printf (" Addr: 0x%08"PFMT64x" Offset: 0x%08"PFMT64x" Link: %x (%s)\n",
(ut64)addr, (ut64)offset, (ut32)link, link_section_name);
}
int i;
for (i = 0; i < num_entries; i++) {
const char *key = sdb_fmt ("entry%d", i);
const char *value = sdb_const_get (sdb, key, 0);
if (value) {
if (oValue && !strcmp (value, oValue)) {
continue;
}
if (IS_MODE_JSON (mode)) {
if (i > 0) { r_cons_printf (","); }
char *escaped_value = r_str_escape (value);
r_cons_printf ("{\"idx\":%"PFMT64u",\"value\":\"%s\"}",
(ut64) i, escaped_value);
free (escaped_value);
} else {
r_cons_printf (" 0x%08"PFMT64x": ", (ut64) i);
r_cons_printf ("%s\n", value);
}
oValue = value;
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
} else {
r_cons_printf ("\n\n");
}
firstit_for_versym = false;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("],\"verneed\":[");
}
bool firstit_dowhile_verneed = true;
do {
char *verneed_path = r_str_newf (format, "verneed", num_verneed++);
if (!(sdb = sdb_ns_path (r->sdb, verneed_path, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_verneed) {
r_cons_printf (",");
}
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
sdb_const_get (sdb, "section_name", 0), sdb_num_get (sdb, "addr", 0), sdb_num_get (sdb, "offset", 0));
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
sdb_num_get (sdb, "link", 0), sdb_const_get (sdb, "link_section_name", 0));
} else {
r_cons_printf ("Version need section '%s' contains %d entries:\n",
sdb_const_get (sdb, "section_name", 0), (int)sdb_num_get (sdb, "num_entries", 0));
r_cons_printf (" Addr: 0x%08"PFMT64x, sdb_num_get (sdb, "addr", 0));
r_cons_printf (" Offset: 0x%08"PFMT64x" Link to section: %"PFMT64d" (%s)\n",
sdb_num_get (sdb, "offset", 0), sdb_num_get (sdb, "link", 0),
sdb_const_get (sdb, "link_section_name", 0));
}
bool firstit_for_verneed = true;
for (num_version = 0;; num_version++) {
const char *filename = NULL;
int num_vernaux = 0;
char *path_version = sdb_fmt ("%s/version%d", verneed_path, num_version);
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_for_verneed) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64u",\"vn_version\":%d,",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Version: %d",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
}
if ((filename = sdb_const_get (sdb, "file_name", 0))) {
if (IS_MODE_JSON (mode)) {
char *escaped_filename = r_str_escape (filename);
r_cons_printf ("\"file_name\":\"%s\",", escaped_filename);
free (escaped_filename);
} else {
r_cons_printf (" File: %s", filename);
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"cnt\":%d,", (int)sdb_num_get (sdb, "cnt", 0));
} else {
r_cons_printf (" Cnt: %d\n", (int)sdb_num_get (sdb, "cnt", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"vernaux\":[");
}
bool firstit_dowhile_vernaux = true;
do {
const char *path_vernaux = sdb_fmt ("%s/vernaux%d", path_version, num_vernaux++);
if (!(sdb = sdb_ns_path (r->sdb, path_vernaux, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_vernaux) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64u",\"name\":\"%s\",",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf ("\"flags\":\"%s\",\"version\":%d}",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Name: %s",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf (" Flags: %s Version: %d\n",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
}
firstit_dowhile_vernaux = false;
} while (sdb);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
}
firstit_for_verneed = false;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
}
firstit_dowhile_verneed = false;
free (verneed_path);
} while (sdb);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
}
}
static void bin_mach0_versioninfo(RCore *r) {
/* TODO */
}
static void bin_pe_resources(RCore *r, int mode) {
Sdb *sdb = NULL;
int index = 0;
PJ *pj = NULL;
const char *pe_path = "bin/cur/info/pe_resource";
if (!(sdb = sdb_ns_path (r->sdb, pe_path, 0))) {
return;
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, R_FLAGS_FS_RESOURCES);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs resources\n");
} else if (IS_MODE_JSON (mode)) {
pj = pj_new ();
pj_a (pj);
}
while (true) {
const char *timestrKey = sdb_fmt ("resource.%d.timestr", index);
const char *vaddrKey = sdb_fmt ("resource.%d.vaddr", index);
const char *sizeKey = sdb_fmt ("resource.%d.size", index);
const char *typeKey = sdb_fmt ("resource.%d.type", index);
const char *languageKey = sdb_fmt ("resource.%d.language", index);
const char *nameKey = sdb_fmt ("resource.%d.name", index);
char *timestr = sdb_get (sdb, timestrKey, 0);
if (!timestr) {
break;
}
ut64 vaddr = sdb_num_get (sdb, vaddrKey, 0);
int size = (int)sdb_num_get (sdb, sizeKey, 0);
char *name = sdb_get (sdb, nameKey, 0);
char *type = sdb_get (sdb, typeKey, 0);
char *lang = sdb_get (sdb, languageKey, 0);
if (IS_MODE_SET (mode)) {
const char *name = sdb_fmt ("resource.%d", index);
r_flag_set (r->flags, name, vaddr, size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f resource.%d %d 0x%08"PFMT32x"\n", index, size, vaddr);
} else if (IS_MODE_JSON (mode)) {
pj_o (pj);
pj_ks (pj, "name", name);
pj_ki (pj, "index", index);
pj_ks (pj, "type", type);
pj_kn (pj, "vaddr", vaddr);
pj_ki (pj, "size", size);
pj_ks (pj, "lang", lang);
pj_ks (pj, "timestamp", timestr);
pj_end (pj);
} else {
char humansz[8];
r_num_units (humansz, sizeof (humansz), size);
r_cons_printf ("Resource %d\n", index);
r_cons_printf (" name: %s\n", name);
r_cons_printf (" timestamp: %s\n", timestr);
r_cons_printf (" vaddr: 0x%08"PFMT64x"\n", vaddr);
r_cons_printf (" size: %s\n", humansz);
r_cons_printf (" type: %s\n", type);
r_cons_printf (" language: %s\n", lang);
}
R_FREE (timestr);
R_FREE (name);
R_FREE (type);
R_FREE (lang)
index++;
}
if (IS_MODE_JSON (mode)) {
pj_end (pj);
r_cons_printf ("%s\n", pj_string (pj));
pj_free (pj);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs *");
}
}
static void bin_no_resources(RCore *r, int mode) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[]");
}
}
static int bin_resources(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_resources (r, mode);
} else {
bin_no_resources (r, mode);
}
return true;
}
static int bin_versioninfo(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_versioninfo (r, mode);
} else if (!strncmp ("elf", info->rclass, 3)) {
bin_elf_versioninfo (r, mode);
} else if (!strncmp ("mach0", info->rclass, 5)) {
bin_mach0_versioninfo (r);
} else {
r_cons_println ("Unknown format");
return false;
}
return true;
}
static int bin_signature(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->signature) {
const char *signature = plg->signature (cur, IS_MODE_JSON (mode));
r_cons_println (signature);
free ((char*) signature);
return true;
}
return false;
}
R_API void r_core_bin_export_info_rad(RCore *core) {
Sdb *db = NULL;
char *flagname = NULL, *offset = NULL;
RBinFile *bf = r_bin_cur (core->bin);
if (!bf) {
return;
}
db = sdb_ns (bf->sdb, "info", 0);;
if (db) {
SdbListIter *iter;
SdbKv *kv;
r_cons_printf ("fs format\n");
// iterate over all keys
SdbList *ls = sdb_foreach_list (db, false);
ls_foreach (ls, iter, kv) {
char *k = sdbkv_key (kv);
char *v = sdbkv_value (kv);
char *dup = strdup (k);
//printf ("?e (%s) (%s)\n", k, v);
if ((flagname = strstr (dup, ".offset"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("f %s @ %s\n", flagname, v);
free (offset);
offset = strdup (v);
}
if ((flagname = strstr (dup, ".cparse"))) {
r_cons_printf ("\"td %s\"\n", v);
}
free (dup);
}
R_FREE (offset);
ls_foreach (ls, iter, kv) {
char *k = sdbkv_key (kv);
char *v = sdbkv_value (kv);
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
r_cons_printf ("pf.%s %s\n", flagname, v);
}
free (dup);
}
ls_foreach (ls, iter, kv) {
char *k = sdbkv_key (kv);
char *v = sdbkv_value (kv);
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
int fmtsize = r_print_format_struct_size (core->print, v, 0, 0);
char *offset_key = r_str_newf ("%s.offset", flagname);
const char *off = sdb_const_get (db, offset_key, 0);
free (offset_key);
if (off) {
r_cons_printf ("Cf %d %s @ %s\n", fmtsize, v, off);
}
}
if ((flagname = strstr (dup, ".size"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("fl %s %s\n", flagname, v);
}
free (dup);
}
free (offset);
}
}
static int bin_header(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->header) {
plg->header (cur);
return true;
}
return false;
}
R_API int r_core_bin_info(RCore *core, int action, int mode, int va, RCoreBinFilter *filter, const char *chksum) {
int ret = true;
const char *name = NULL;
ut64 at = 0, loadaddr = r_bin_get_laddr (core->bin);
if (filter && filter->offset) {
at = filter->offset;
}
if (filter && filter->name) {
name = filter->name;
}
// use our internal values for va
va = va ? VA_TRUE : VA_FALSE;
#if 0
if (r_config_get_i (core->config, "anal.strings")) {
r_core_cmd0 (core, "aar");
}
#endif
if ((action & R_CORE_BIN_ACC_STRINGS)) {
ret &= bin_strings (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_RAW_STRINGS)) {
ret &= bin_raw_strings (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_INFO)) {
ret &= bin_info (core, mode, loadaddr);
}
if ((action & R_CORE_BIN_ACC_MAIN)) {
ret &= bin_main (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_DWARF)) {
ret &= bin_dwarf (core, mode);
}
if ((action & R_CORE_BIN_ACC_PDB)) {
ret &= bin_pdb (core, mode);
}
if ((action & R_CORE_BIN_ACC_SOURCE)) {
ret &= bin_source (core, mode);
}
if ((action & R_CORE_BIN_ACC_ENTRIES)) {
ret &= bin_entry (core, mode, loadaddr, va, false);
}
if ((action & R_CORE_BIN_ACC_INITFINI)) {
ret &= bin_entry (core, mode, loadaddr, va, true);
}
if ((action & R_CORE_BIN_ACC_SECTIONS)) {
ret &= bin_sections (core, mode, loadaddr, va, at, name, chksum, false);
}
if ((action & R_CORE_BIN_ACC_SEGMENTS)) {
ret &= bin_sections (core, mode, loadaddr, va, at, name, chksum, true);
}
if (r_config_get_i (core->config, "bin.relocs")) {
if ((action & R_CORE_BIN_ACC_RELOCS)) {
ret &= bin_relocs (core, mode, va);
}
}
if ((action & R_CORE_BIN_ACC_LIBS)) {
ret &= bin_libs (core, mode);
}
if ((action & R_CORE_BIN_ACC_IMPORTS)) { // 5s
ret &= bin_imports (core, mode, va, name);
}
if ((action & R_CORE_BIN_ACC_EXPORTS)) {
ret &= bin_symbols (core, mode, loadaddr, va, at, name, true, chksum);
}
if ((action & R_CORE_BIN_ACC_SYMBOLS)) { // 6s
ret &= bin_symbols (core, mode, loadaddr, va, at, name, false, chksum);
}
if ((action & R_CORE_BIN_ACC_CLASSES)) { // 6s
ret &= bin_classes (core, mode);
}
if ((action & R_CORE_BIN_ACC_TRYCATCH)) {
ret &= bin_trycatch (core, mode);
}
if ((action & R_CORE_BIN_ACC_SIZE)) {
ret &= bin_size (core, mode);
}
if ((action & R_CORE_BIN_ACC_MEM)) {
ret &= bin_mem (core, mode);
}
if ((action & R_CORE_BIN_ACC_VERSIONINFO)) {
ret &= bin_versioninfo (core, mode);
}
if ((action & R_CORE_BIN_ACC_RESOURCES)) {
ret &= bin_resources (core, mode);
}
if ((action & R_CORE_BIN_ACC_SIGNATURE)) {
ret &= bin_signature (core, mode);
}
if ((action & R_CORE_BIN_ACC_FIELDS)) {
if (IS_MODE_SIMPLE (mode)) {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
/* ignore mode, just for quiet/simple here */
ret &= bin_fields (core, 0, va);
}
} else {
if (IS_MODE_NORMAL (mode)) {
ret &= bin_header (core, mode);
} else {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
ret &= bin_fields (core, mode, va);
}
}
}
}
return ret;
}
R_API int r_core_bin_set_arch_bits(RCore *r, const char *name, const char * arch, ut16 bits) {
int fd = r_io_fd_get_current (r->io);
RIODesc *desc = r_io_desc_get (r->io, fd);
RBinFile *curfile, *binfile = NULL;
if (!name) {
if (!desc || !desc->name) {
return false;
}
name = desc->name;
}
/* Check if the arch name is a valid name */
if (!r_asm_is_valid (r->assembler, arch)) {
return false;
}
/* Find a file with the requested name/arch/bits */
binfile = r_bin_file_find_by_arch_bits (r->bin, arch, bits);
if (!binfile) {
return false;
}
if (!r_bin_use_arch (r->bin, arch, bits, name)) {
return false;
}
curfile = r_bin_cur (r->bin);
//set env if the binfile changed or we are dealing with xtr
if (curfile != binfile || binfile->curxtr) {
r_core_bin_set_cur (r, binfile);
return r_core_bin_set_env (r, binfile);
}
return true;
}
R_API int r_core_bin_update_arch_bits(RCore *r) {
RBinFile *binfile = NULL;
const char *name = NULL, *arch = NULL;
ut16 bits = 0;
if (!r) {
return 0;
}
if (r->assembler) {
bits = r->assembler->bits;
if (r->assembler->cur) {
arch = r->assembler->cur->arch;
}
}
binfile = r_bin_cur (r->bin);
name = binfile ? binfile->file : NULL;
if (binfile && binfile->curxtr) {
r_anal_hint_clear (r->anal);
}
return r_core_bin_set_arch_bits (r, name, arch, bits);
}
R_API bool r_core_bin_raise(RCore *core, ut32 bfid) {
if (!r_bin_select_bfid (core->bin, bfid)) {
return false;
}
RBinFile *bf = r_bin_cur (core->bin);
if (bf) {
r_io_use_fd (core->io, bf->fd);
}
// it should be 0 to use r_io_use_fd in r_core_block_read
core->switch_file_view = 0;
return bf && r_core_bin_set_env (core, bf) && r_core_block_read (core);
}
R_API bool r_core_bin_delete(RCore *core, ut32 bf_id) {
if (bf_id == UT32_MAX) {
return false;
}
#if 0
if (!r_bin_object_delete (core->bin, bf_id)) {
return false;
}
// TODO: use rbinat()
RBinFile *bf = r_bin_cur (core->bin);
if (bf) {
r_io_use_fd (core->io, bf->fd);
}
#endif
r_bin_file_delete (core->bin, bf_id);
RBinFile *bf = r_bin_file_at (core->bin, core->offset);
if (bf) {
r_io_use_fd (core->io, bf->fd);
}
core->switch_file_view = 0;
return bf && r_core_bin_set_env (core, bf) && r_core_block_read (core);
}
static bool r_core_bin_file_print(RCore *core, RBinFile *bf, int mode) {
r_return_val_if_fail (core && bf && bf->o, NULL);
const char *name = bf ? bf->file : NULL;
(void)r_bin_get_info (core->bin); // XXX is this necssary for proper iniitialization
ut32 bin_sz = bf ? bf->size : 0;
// TODO: handle mode to print in json and r2 commands
switch (mode) {
case '*':
{
char *n = __filterShell (name);
r_cons_printf ("oba 0x%08"PFMT64x" %s # %d\n", bf->o->boffset, n, bf->id);
free (n);
}
break;
case 'q':
r_cons_printf ("%d\n", bf->id);
break;
case 'j':
// XXX there's only one binobj for each bf...so we should change that json
// TODO: use pj API
r_cons_printf ("{\"name\":\"%s\",\"iofd\":%d,\"bfid\":%d,\"size\":%d,\"objs\":[",
name? name: "", bf->fd, bf->id, bin_sz);
{
RBinObject *obj = bf->o;
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *asmarch = r_config_get (core->config, "asm.arch");
const char *arch = info ? info->arch ? info->arch: asmarch : "unknown";
r_cons_printf ("{\"arch\":\"%s\",\"bits\":%d,\"binoffset\":%"
PFMT64d",\"objsize\":%"PFMT64d"}",
arch, bits, obj->boffset, obj->obj_size);
}
r_cons_print ("]}");
break;
default:
{
RBinInfo *info = bf->o->info;
ut8 bits = info ? info->bits : 0;
const char *asmarch = r_config_get (core->config, "asm.arch");
const char *arch = info ? info->arch ? info->arch: asmarch: "unknown";
r_cons_printf ("%d %d %s-%d ba:0x%08"PFMT64x" sz:%"PFMT64d" %s\n",
bf->id, bf->fd, arch, bits, bf->o->baddr, bf->o->size, name);
}
break;
}
return true;
}
R_API int r_core_bin_list(RCore *core, int mode) {
// list all binfiles and there objects and there archs
int count = 0;
RListIter *iter;
RBinFile *binfile = NULL; //, *cur_bf = r_bin_cur (core->bin) ;
RBin *bin = core->bin;
const RList *binfiles = bin ? bin->binfiles: NULL;
if (!binfiles) {
return false;
}
if (mode == 'j') {
r_cons_print ("[");
}
r_list_foreach (binfiles, iter, binfile) {
r_core_bin_file_print (core, binfile, mode);
if (iter->n && mode == 'j') {
r_cons_print (",");
}
}
if (mode == 'j') {
r_cons_println ("]");
}
return count;
}
R_API char *r_core_bin_method_flags_str(ut64 flags, int mode) {
int i, len = 0;
RStrBuf *buf = r_strbuf_new ("");
if (IS_MODE_SET (mode) || IS_MODE_RAD (mode)) {
if (!flags) {
goto out;
}
for (i = 0; i < 64; i++) {
ut64 flag = flags & (1ULL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (flag_string) {
r_strbuf_appendf (buf, ".%s", flag_string);
}
}
}
} else if (IS_MODE_JSON (mode)) {
if (!flags) {
r_strbuf_append (buf, "[]");
goto out;
}
r_strbuf_append (buf, "[");
for (i = 0; i < 64; i++) {
ut64 flag = flags & (1ULL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (len != 0) {
r_strbuf_append (buf, ",");
}
if (flag_string) {
r_strbuf_appendf (buf, "\"%s\"", flag_string);
} else {
r_strbuf_appendf (buf, "\"0x%08"PFMT64x"\"", flag);
}
len++;
}
}
r_strbuf_append (buf, "]");
} else {
int pad_len = 4; //TODO: move to a config variable
if (!flags) {
goto padding;
}
for (i = 0; i < 64; i++) {
ut64 flag = flags & (1ULL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, true);
if (flag_string) {
r_strbuf_append (buf, flag_string);
} else {
r_strbuf_append (buf, "?");
}
len++;
}
}
padding:
for ( ; len < pad_len; len++) {
r_strbuf_append (buf, " ");
}
}
out:
return r_strbuf_drain (buf);
}
| ./CrossVul/dataset_final_sorted/CWE-78/c/good_1103_0 |
crossvul-cpp_data_bad_3010_0 | /*
* Client routines for the CUPS scheduler.
*
* Copyright 2007-2015 by Apple Inc.
* Copyright 1997-2007 by Easy Software Products, all rights reserved.
*
* This file contains Kerberos support code, copyright 2006 by
* Jelmer Vernooij.
*
* These coded instructions, statements, and computer programs are the
* property of Apple Inc. and are protected by Federal copyright
* law. Distribution and use rights are outlined in the file "LICENSE.txt"
* which should have been included with this file. If this file is
* file is missing or damaged, see the license at "http://www.cups.org/".
*/
/*
* Include necessary headers...
*/
#define _CUPS_NO_DEPRECATED
#define _HTTP_NO_PRIVATE
#include "cupsd.h"
#ifdef __APPLE__
# include <libproc.h>
#endif /* __APPLE__ */
#ifdef HAVE_TCPD_H
# include <tcpd.h>
#endif /* HAVE_TCPD_H */
/*
* Local functions...
*/
static int check_if_modified(cupsd_client_t *con,
struct stat *filestats);
static int compare_clients(cupsd_client_t *a, cupsd_client_t *b,
void *data);
#ifdef HAVE_SSL
static int cupsd_start_tls(cupsd_client_t *con, http_encryption_t e);
#endif /* HAVE_SSL */
static char *get_file(cupsd_client_t *con, struct stat *filestats,
char *filename, size_t len);
static http_status_t install_cupsd_conf(cupsd_client_t *con);
static int is_cgi(cupsd_client_t *con, const char *filename,
struct stat *filestats, mime_type_t *type);
static int is_path_absolute(const char *path);
static int pipe_command(cupsd_client_t *con, int infile, int *outfile,
char *command, char *options, int root);
static int valid_host(cupsd_client_t *con);
static int write_file(cupsd_client_t *con, http_status_t code,
char *filename, char *type,
struct stat *filestats);
static void write_pipe(cupsd_client_t *con);
/*
* 'cupsdAcceptClient()' - Accept a new client.
*/
void
cupsdAcceptClient(cupsd_listener_t *lis)/* I - Listener socket */
{
const char *hostname; /* Hostname of client */
char name[256]; /* Hostname of client */
int count; /* Count of connections on a host */
cupsd_client_t *con, /* New client pointer */
*tempcon; /* Temporary client pointer */
socklen_t addrlen; /* Length of address */
http_addr_t temp; /* Temporary address variable */
static time_t last_dos = 0; /* Time of last DoS attack */
#ifdef HAVE_TCPD_H
struct request_info wrap_req; /* TCP wrappers request information */
#endif /* HAVE_TCPD_H */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis, lis->fd, cupsArrayCount(Clients));
/*
* Make sure we don't have a full set of clients already...
*/
if (cupsArrayCount(Clients) == MaxClients)
return;
/*
* Get a pointer to the next available client...
*/
if (!Clients)
Clients = cupsArrayNew(NULL, NULL);
if (!Clients)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to allocate memory for clients array!");
cupsdPauseListening();
return;
}
if (!ActiveClients)
ActiveClients = cupsArrayNew((cups_array_func_t)compare_clients, NULL);
if (!ActiveClients)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to allocate memory for active clients array!");
cupsdPauseListening();
return;
}
if ((con = calloc(1, sizeof(cupsd_client_t))) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to allocate memory for client!");
cupsdPauseListening();
return;
}
/*
* Accept the client and get the remote address...
*/
con->number = ++ LastClientNumber;
con->file = -1;
if ((con->http = httpAcceptConnection(lis->fd, 0)) == NULL)
{
if (errno == ENFILE || errno == EMFILE)
cupsdPauseListening();
cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to accept client connection - %s.",
strerror(errno));
free(con);
return;
}
/*
* Save the connected address and port number...
*/
addrlen = sizeof(con->clientaddr);
if (getsockname(httpGetFd(con->http), (struct sockaddr *)&con->clientaddr, &addrlen) || addrlen == 0)
con->clientaddr = lis->address;
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Server address is \"%s\".", httpAddrString(&con->clientaddr, name, sizeof(name)));
/*
* Check the number of clients on the same address...
*/
for (count = 0, tempcon = (cupsd_client_t *)cupsArrayFirst(Clients);
tempcon;
tempcon = (cupsd_client_t *)cupsArrayNext(Clients))
if (httpAddrEqual(httpGetAddress(tempcon->http), httpGetAddress(con->http)))
{
count ++;
if (count >= MaxClientsPerHost)
break;
}
if (count >= MaxClientsPerHost)
{
if ((time(NULL) - last_dos) >= 60)
{
last_dos = time(NULL);
cupsdLogMessage(CUPSD_LOG_WARN,
"Possible DoS attack - more than %d clients connecting "
"from %s.",
MaxClientsPerHost,
httpGetHostname(con->http, name, sizeof(name)));
}
httpClose(con->http);
free(con);
return;
}
/*
* Get the hostname or format the IP address as needed...
*/
if (HostNameLookups)
hostname = httpResolveHostname(con->http, NULL, 0);
else
hostname = httpGetHostname(con->http, NULL, 0);
if (hostname == NULL && HostNameLookups == 2)
{
/*
* Can't have an unresolved IP address with double-lookups enabled...
*/
httpClose(con->http);
cupsdLogClient(con, CUPSD_LOG_WARN,
"Name lookup failed - connection from %s closed!",
httpGetHostname(con->http, NULL, 0));
free(con);
return;
}
if (HostNameLookups == 2)
{
/*
* Do double lookups as needed...
*/
http_addrlist_t *addrlist, /* List of addresses */
*addr; /* Current address */
if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, NULL)) != NULL)
{
/*
* See if the hostname maps to the same IP address...
*/
for (addr = addrlist; addr; addr = addr->next)
if (httpAddrEqual(httpGetAddress(con->http), &(addr->addr)))
break;
}
else
addr = NULL;
httpAddrFreeList(addrlist);
if (!addr)
{
/*
* Can't have a hostname that doesn't resolve to the same IP address
* with double-lookups enabled...
*/
httpClose(con->http);
cupsdLogClient(con, CUPSD_LOG_WARN,
"IP lookup failed - connection from %s closed!",
httpGetHostname(con->http, NULL, 0));
free(con);
return;
}
}
#ifdef HAVE_TCPD_H
/*
* See if the connection is denied by TCP wrappers...
*/
request_init(&wrap_req, RQ_DAEMON, "cupsd", RQ_FILE, httpGetFd(con->http),
NULL);
fromhost(&wrap_req);
if (!hosts_access(&wrap_req))
{
httpClose(con->http);
cupsdLogClient(con, CUPSD_LOG_WARN,
"Connection from %s refused by /etc/hosts.allow and "
"/etc/hosts.deny rules.", httpGetHostname(con->http, NULL, 0));
free(con);
return;
}
#endif /* HAVE_TCPD_H */
#ifdef AF_LOCAL
if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
{
# ifdef __APPLE__
socklen_t peersize; /* Size of peer credentials */
pid_t peerpid; /* Peer process ID */
char peername[256]; /* Name of process */
peersize = sizeof(peerpid);
if (!getsockopt(httpGetFd(con->http), SOL_LOCAL, LOCAL_PEERPID, &peerpid,
&peersize))
{
if (!proc_name((int)peerpid, peername, sizeof(peername)))
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Accepted from %s (Domain ???[%d])",
httpGetHostname(con->http, NULL, 0), (int)peerpid);
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Accepted from %s (Domain %s[%d])",
httpGetHostname(con->http, NULL, 0), peername, (int)peerpid);
}
else
# endif /* __APPLE__ */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s (Domain)",
httpGetHostname(con->http, NULL, 0));
}
else
#endif /* AF_LOCAL */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s:%d (IPv%d)",
httpGetHostname(con->http, NULL, 0),
httpAddrPort(httpGetAddress(con->http)),
httpAddrFamily(httpGetAddress(con->http)) == AF_INET ? 4 : 6);
/*
* Get the local address the client connected to...
*/
addrlen = sizeof(temp);
if (getsockname(httpGetFd(con->http), (struct sockaddr *)&temp, &addrlen))
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to get local address - %s",
strerror(errno));
strlcpy(con->servername, "localhost", sizeof(con->servername));
con->serverport = LocalPort;
}
#ifdef AF_LOCAL
else if (httpAddrFamily(&temp) == AF_LOCAL)
{
strlcpy(con->servername, "localhost", sizeof(con->servername));
con->serverport = LocalPort;
}
#endif /* AF_LOCAL */
else
{
if (httpAddrLocalhost(&temp))
strlcpy(con->servername, "localhost", sizeof(con->servername));
else if (HostNameLookups)
httpAddrLookup(&temp, con->servername, sizeof(con->servername));
else
httpAddrString(&temp, con->servername, sizeof(con->servername));
con->serverport = httpAddrPort(&(lis->address));
}
/*
* Add the connection to the array of active clients...
*/
cupsArrayAdd(Clients, con);
/*
* Add the socket to the server select.
*/
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL,
con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
/*
* Temporarily suspend accept()'s until we lose a client...
*/
if (cupsArrayCount(Clients) == MaxClients)
cupsdPauseListening();
#ifdef HAVE_SSL
/*
* See if we are connecting on a secure port...
*/
if (lis->encryption == HTTP_ENCRYPTION_ALWAYS)
{
/*
* https connection; go secure...
*/
if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))
cupsdCloseClient(con);
}
else
con->auto_ssl = 1;
#endif /* HAVE_SSL */
}
/*
* 'cupsdCloseAllClients()' - Close all remote clients immediately.
*/
void
cupsdCloseAllClients(void)
{
cupsd_client_t *con; /* Current client */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients));
for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
con;
con = (cupsd_client_t *)cupsArrayNext(Clients))
if (cupsdCloseClient(con))
cupsdCloseClient(con);
}
/*
* 'cupsdCloseClient()' - Close a remote client.
*/
int /* O - 1 if partial close, 0 if fully closed */
cupsdCloseClient(cupsd_client_t *con) /* I - Client to close */
{
int partial; /* Do partial close for SSL? */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing connection.");
/*
* Flush pending writes before closing...
*/
httpFlushWrite(con->http);
partial = 0;
if (con->pipe_pid != 0)
{
/*
* Stop any CGI process...
*/
cupsdEndProcess(con->pipe_pid, 1);
con->pipe_pid = 0;
}
if (con->file >= 0)
{
cupsdRemoveSelect(con->file);
close(con->file);
con->file = -1;
}
/*
* Close the socket and clear the file from the input set for select()...
*/
if (httpGetFd(con->http) >= 0)
{
cupsArrayRemove(ActiveClients, con);
cupsdSetBusyState();
#ifdef HAVE_SSL
/*
* Shutdown encryption as needed...
*/
if (httpIsEncrypted(con->http))
partial = 1;
#endif /* HAVE_SSL */
if (partial)
{
/*
* Only do a partial close so that the encrypted client gets everything.
*/
httpShutdown(con->http);
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for socket close.");
}
else
{
/*
* Shut the socket down fully...
*/
cupsdRemoveSelect(httpGetFd(con->http));
httpClose(con->http);
con->http = NULL;
}
}
if (!partial)
{
/*
* Free memory...
*/
cupsdRemoveSelect(httpGetFd(con->http));
httpClose(con->http);
if (con->filename)
{
unlink(con->filename);
cupsdClearString(&con->filename);
}
cupsdClearString(&con->command);
cupsdClearString(&con->options);
cupsdClearString(&con->query_string);
if (con->request)
{
ippDelete(con->request);
con->request = NULL;
}
if (con->response)
{
ippDelete(con->response);
con->response = NULL;
}
if (con->language)
{
cupsLangFree(con->language);
con->language = NULL;
}
#ifdef HAVE_AUTHORIZATION_H
if (con->authref)
{
AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
con->authref = NULL;
}
#endif /* HAVE_AUTHORIZATION_H */
/*
* Re-enable new client connections if we are going back under the
* limit...
*/
if (cupsArrayCount(Clients) == MaxClients)
cupsdResumeListening();
/*
* Compact the list of clients as necessary...
*/
cupsArrayRemove(Clients, con);
free(con);
}
return (partial);
}
/*
* 'cupsdReadClient()' - Read data from a client.
*/
void
cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
{
char line[32768], /* Line from client... */
locale[64], /* Locale */
*ptr; /* Pointer into strings */
http_status_t status; /* Transfer status */
ipp_state_t ipp_state; /* State of IPP transfer */
int bytes; /* Number of bytes to POST */
char *filename; /* Name of file for GET/HEAD */
char buf[1024]; /* Buffer for real filename */
struct stat filestats; /* File information */
mime_type_t *type; /* MIME type of file */
cupsd_printer_t *p; /* Printer */
static unsigned request_id = 0; /* Request ID for temp files */
status = HTTP_STATUS_CONTINUE;
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdReadClient: error=%d, used=%d, state=%s, data_encoding=HTTP_ENCODING_%s, data_remaining=" CUPS_LLFMT ", request=%p(%s), file=%d", httpError(con->http), (int)httpGetReady(con->http), httpStateString(httpGetState(con->http)), httpIsChunked(con->http) ? "CHUNKED" : "LENGTH", CUPS_LLCAST httpGetRemaining(con->http), con->request, con->request ? ippStateString(ippGetState(con->request)) : "", con->file);
if (httpGetState(con->http) == HTTP_STATE_GET_SEND ||
httpGetState(con->http) == HTTP_STATE_POST_SEND ||
httpGetState(con->http) == HTTP_STATE_STATUS)
{
/*
* If we get called in the wrong state, then something went wrong with the
* connection and we need to shut it down...
*/
if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
{
/*
* Connection closed...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
cupsdCloseClient(con);
return;
}
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con->http)));
cupsdCloseClient(con);
return;
}
#ifdef HAVE_SSL
if (con->auto_ssl)
{
/*
* Automatically check for a SSL/TLS handshake...
*/
con->auto_ssl = 0;
if (recv(httpGetFd(con->http), buf, 1, MSG_PEEK) == 1 &&
(!buf[0] || !strchr("DGHOPT", buf[0])))
{
/*
* Encrypt this connection...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf[0] & 255);
if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))
cupsdCloseClient(con);
return;
}
}
#endif /* HAVE_SSL */
switch (httpGetState(con->http))
{
case HTTP_STATE_WAITING :
/*
* See if we've received a request line...
*/
con->operation = httpReadRequest(con->http, con->uri, sizeof(con->uri));
if (con->operation == HTTP_STATE_ERROR ||
con->operation == HTTP_STATE_UNKNOWN_METHOD ||
con->operation == HTTP_STATE_UNKNOWN_VERSION)
{
if (httpError(con->http))
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_WAITING Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_WAITING Closing on error: %s",
cupsLastErrorString());
cupsdCloseClient(con);
return;
}
/*
* Ignore blank request lines...
*/
if (con->operation == HTTP_STATE_WAITING)
break;
/*
* Clear other state variables...
*/
con->bytes = 0;
con->file = -1;
con->file_ready = 0;
con->pipe_pid = 0;
con->username[0] = '\0';
con->password[0] = '\0';
cupsdClearString(&con->command);
cupsdClearString(&con->options);
cupsdClearString(&con->query_string);
if (con->request)
{
ippDelete(con->request);
con->request = NULL;
}
if (con->response)
{
ippDelete(con->response);
con->response = NULL;
}
if (con->language)
{
cupsLangFree(con->language);
con->language = NULL;
}
#ifdef HAVE_GSSAPI
con->have_gss = 0;
con->gss_uid = 0;
#endif /* HAVE_GSSAPI */
/*
* Handle full URLs in the request line...
*/
if (strcmp(con->uri, "*"))
{
char scheme[HTTP_MAX_URI], /* Method/scheme */
userpass[HTTP_MAX_URI], /* Username:password */
hostname[HTTP_MAX_URI], /* Hostname */
resource[HTTP_MAX_URI]; /* Resource path */
int port; /* Port number */
/*
* Separate the URI into its components...
*/
if (httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,
scheme, sizeof(scheme),
userpass, sizeof(userpass),
hostname, sizeof(hostname), &port,
resource, sizeof(resource)) < HTTP_URI_STATUS_OK)
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
con->uri);
cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
/*
* Only allow URIs with the servername, localhost, or an IP
* address...
*/
if (strcmp(scheme, "file") &&
_cups_strcasecmp(hostname, ServerName) &&
_cups_strcasecmp(hostname, "localhost") &&
!cupsArrayFind(ServerAlias, hostname) &&
!isdigit(hostname[0]) && hostname[0] != '[')
{
/*
* Nope, we don't do proxies...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
con->uri);
cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
/*
* Copy the resource portion back into the URI; both resource and
* con->uri are HTTP_MAX_URI bytes in size...
*/
strlcpy(con->uri, resource, sizeof(con->uri));
}
/*
* Process the request...
*/
gettimeofday(&(con->start), NULL);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "%s %s HTTP/%d.%d",
httpStateString(con->operation) + 11, con->uri,
httpGetVersion(con->http) / 100,
httpGetVersion(con->http) % 100);
if (!cupsArrayFind(ActiveClients, con))
{
cupsArrayAdd(ActiveClients, con);
cupsdSetBusyState();
}
case HTTP_STATE_OPTIONS :
case HTTP_STATE_DELETE :
case HTTP_STATE_GET :
case HTTP_STATE_HEAD :
case HTTP_STATE_POST :
case HTTP_STATE_PUT :
case HTTP_STATE_TRACE :
/*
* Parse incoming parameters until the status changes...
*/
while ((status = httpUpdate(con->http)) == HTTP_STATUS_CONTINUE)
if (!httpGetReady(con->http))
break;
if (status != HTTP_STATUS_OK && status != HTTP_STATUS_CONTINUE)
{
if (httpError(con->http) && httpError(con->http) != EPIPE)
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing for error %d (%s) while reading headers.",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing on EOF while reading headers.");
cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
break;
default :
if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
{
/*
* Connection closed...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
cupsdCloseClient(con);
return;
}
break; /* Anti-compiler-warning-code */
}
/*
* Handle new transfers...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Read: status=%d", status);
if (status == HTTP_STATUS_OK)
{
if (httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE)[0])
{
/*
* Figure out the locale from the Accept-Language and Content-Type
* fields...
*/
if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
',')) != NULL)
*ptr = '\0';
if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
';')) != NULL)
*ptr = '\0';
if ((ptr = strstr(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
"charset=")) != NULL)
{
/*
* Combine language and charset, and trim any extra params in the
* content-type.
*/
snprintf(locale, sizeof(locale), "%s.%s",
httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE), ptr + 8);
if ((ptr = strchr(locale, ',')) != NULL)
*ptr = '\0';
}
else
snprintf(locale, sizeof(locale), "%s.UTF-8",
httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE));
con->language = cupsLangGet(locale);
}
else
con->language = cupsLangGet(DefaultLocale);
cupsdAuthorize(con);
if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
"Keep-Alive", 10) && KeepAlive)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_ON);
else if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
"close", 5))
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
if (!httpGetField(con->http, HTTP_FIELD_HOST)[0] &&
httpGetVersion(con->http) >= HTTP_VERSION_1_1)
{
/*
* HTTP/1.1 and higher require the "Host:" field...
*/
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Missing Host: field in request.");
cupsdCloseClient(con);
return;
}
}
else if (!valid_host(con))
{
/*
* Access to localhost must use "localhost" or the corresponding IPv4
* or IPv6 values in the Host: field.
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Request from \"%s\" using invalid Host: field \"%s\".",
httpGetHostname(con->http, NULL, 0), httpGetField(con->http, HTTP_FIELD_HOST));
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else if (con->operation == HTTP_STATE_OPTIONS)
{
/*
* Do OPTIONS command...
*/
if (con->best && con->best->type != CUPSD_AUTH_NONE)
{
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION), "Upgrade") && strstr(httpGetField(con->http, HTTP_FIELD_UPGRADE), "TLS/") != NULL && !httpIsEncrypted(con->http))
{
#ifdef HAVE_SSL
/*
* Do encryption stuff...
*/
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
{
cupsdCloseClient(con);
return;
}
#else
if (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
#endif /* HAVE_SSL */
}
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_ALLOW,
"GET, HEAD, OPTIONS, POST, PUT");
httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else if (!is_path_absolute(con->uri))
{
/*
* Protect against malicious users!
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Request for non-absolute resource \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
{
if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
"Upgrade") && !httpIsEncrypted(con->http))
{
#ifdef HAVE_SSL
/*
* Do encryption stuff...
*/
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL,
CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
{
cupsdCloseClient(con);
return;
}
#else
if (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
#endif /* HAVE_SSL */
}
if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_STATUS_OK)
{
cupsdSendError(con, status, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
if (httpGetExpect(con->http) &&
(con->operation == HTTP_STATE_POST || con->operation == HTTP_STATE_PUT))
{
if (httpGetExpect(con->http) == HTTP_STATUS_CONTINUE)
{
/*
* Send 100-continue header...
*/
if (httpWriteResponse(con->http, HTTP_STATUS_CONTINUE))
{
cupsdCloseClient(con);
return;
}
}
else
{
/*
* Send 417-expectation-failed header...
*/
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
cupsdSendError(con, HTTP_STATUS_EXPECTATION_FAILED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
}
switch (httpGetState(con->http))
{
case HTTP_STATE_GET_SEND :
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Processing GET %s", con->uri);
if ((!strncmp(con->uri, "/ppd/", 5) ||
!strncmp(con->uri, "/printers/", 10) ||
!strncmp(con->uri, "/classes/", 9)) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
{
/*
* Send PPD file - get the real printer name since printer
* names are not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
if (!strncmp(con->uri, "/ppd/", 5))
p = cupsdFindPrinter(con->uri + 5);
else if (!strncmp(con->uri, "/printers/", 10))
p = cupsdFindPrinter(con->uri + 10);
else
{
p = cupsdFindClass(con->uri + 9);
if (p)
{
int i; /* Looping var */
for (i = 0; i < p->num_printers; i ++)
{
if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
{
char ppdname[1024];/* PPD filename */
snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
ServerRoot, p->printers[i]->name);
if (!access(ppdname, 0))
{
p = p->printers[i];
break;
}
}
}
if (i >= p->num_printers)
p = NULL;
}
}
if (p)
{
snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
}
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
}
else if ((!strncmp(con->uri, "/icons/", 7) ||
!strncmp(con->uri, "/printers/", 10) ||
!strncmp(con->uri, "/classes/", 9)) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".png"))
{
/*
* Send icon file - get the real queue name since queue names are
* not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".png" */
if (!strncmp(con->uri, "/icons/", 7))
p = cupsdFindPrinter(con->uri + 7);
else if (!strncmp(con->uri, "/printers/", 10))
p = cupsdFindPrinter(con->uri + 10);
else
{
p = cupsdFindClass(con->uri + 9);
if (p)
{
int i; /* Looping var */
for (i = 0; i < p->num_printers; i ++)
{
if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
{
char ppdname[1024];/* PPD filename */
snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
ServerRoot, p->printers[i]->name);
if (!access(ppdname, 0))
{
p = p->printers[i];
break;
}
}
}
if (i >= p->num_printers)
p = NULL;
}
}
if (p)
snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
}
if ((!strncmp(con->uri, "/admin", 6) && strcmp(con->uri, "/admin/conf/cupsd.conf") && strncmp(con->uri, "/admin/log/", 11)) ||
!strncmp(con->uri, "/printers", 9) ||
!strncmp(con->uri, "/classes", 8) ||
!strncmp(con->uri, "/help", 5) ||
!strncmp(con->uri, "/jobs", 5))
{
if (!WebInterface)
{
/*
* Web interface is disabled. Show an appropriate message...
*/
if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* Send CGI output...
*/
if (!strncmp(con->uri, "/admin", 6))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
ServerBin);
cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
}
else if (!strncmp(con->uri, "/printers", 9))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
ServerBin);
if (con->uri[9] && con->uri[10])
cupsdSetString(&con->options, con->uri + 9);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/classes", 8))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
ServerBin);
if (con->uri[8] && con->uri[9])
cupsdSetString(&con->options, con->uri + 8);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/jobs", 5))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
else
{
cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
if (!cupsdSendCommand(con, con->command, con->options, 0))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
cupsdLogRequest(con, HTTP_STATUS_OK);
if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
}
else if (!strncmp(con->uri, "/admin/log/", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))
{
/*
* GET can only be done to configuration files directly under
* /admin/conf...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR, "Request for subdirectory \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else
{
/*
* Serve a file...
*/
if ((filename = get_file(con, &filestats, buf,
sizeof(buf))) == NULL)
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
type = mimeFileType(MimeDatabase, filename, NULL, NULL);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "filename=\"%s\", type=%s/%s", filename, type ? type->super : "", type ? type->type : "");
if (is_cgi(con, filename, &filestats, type))
{
/*
* Note: con->command and con->options were set by
* is_cgi()...
*/
if (!cupsdSendCommand(con, con->command, con->options, 0))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
cupsdLogRequest(con, HTTP_STATUS_OK);
if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
break;
}
if (!check_if_modified(con, &filestats))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
{
if (type == NULL)
strlcpy(line, "text/plain", sizeof(line));
else
snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
if (!write_file(con, HTTP_STATUS_OK, filename, line, &filestats))
{
cupsdCloseClient(con);
return;
}
}
}
break;
case HTTP_STATE_POST_RECV :
/*
* See if the POST request includes a Content-Length field, and if
* so check the length against any limits that are set...
*/
if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
MaxRequestSize > 0 &&
httpGetLength2(con->http) > MaxRequestSize)
{
/*
* Request too large...
*/
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else if (httpGetLength2(con->http) < 0)
{
/*
* Negative content lengths are invalid!
*/
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* See what kind of POST request this is; for IPP requests the
* content-type field will be "application/ipp"...
*/
if (!strcmp(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
"application/ipp"))
con->request = ippNew();
else if (!WebInterface)
{
/*
* Web interface is disabled. Show an appropriate message...
*/
if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else if ((!strncmp(con->uri, "/admin", 6) && strncmp(con->uri, "/admin/log/", 11)) ||
!strncmp(con->uri, "/printers", 9) ||
!strncmp(con->uri, "/classes", 8) ||
!strncmp(con->uri, "/help", 5) ||
!strncmp(con->uri, "/jobs", 5))
{
/*
* CGI request...
*/
if (!strncmp(con->uri, "/admin", 6))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
ServerBin);
cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
}
else if (!strncmp(con->uri, "/printers", 9))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
ServerBin);
if (con->uri[9] && con->uri[10])
cupsdSetString(&con->options, con->uri + 9);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/classes", 8))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
ServerBin);
if (con->uri[8] && con->uri[9])
cupsdSetString(&con->options, con->uri + 8);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/jobs", 5))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
else
{
cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
}
else
{
/*
* POST to a file...
*/
if ((filename = get_file(con, &filestats, buf,
sizeof(buf))) == NULL)
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
type = mimeFileType(MimeDatabase, filename, NULL, NULL);
if (!is_cgi(con, filename, &filestats, type))
{
/*
* Only POST to CGI's...
*/
if (!cupsdSendError(con, HTTP_STATUS_UNAUTHORIZED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
break;
case HTTP_STATE_PUT_RECV :
/*
* Validate the resource name...
*/
if (strcmp(con->uri, "/admin/conf/cupsd.conf"))
{
/*
* PUT can only be done to the cupsd.conf file...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Disallowed PUT request for \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* See if the PUT request includes a Content-Length field, and if
* so check the length against any limits that are set...
*/
if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
MaxRequestSize > 0 &&
httpGetLength2(con->http) > MaxRequestSize)
{
/*
* Request too large...
*/
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else if (httpGetLength2(con->http) < 0)
{
/*
* Negative content lengths are invalid!
*/
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* Open a temporary file to hold the request...
*/
cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
request_id ++);
con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
if (con->file < 0)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to create request file \"%s\": %s",
con->filename, strerror(errno));
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
fchmod(con->file, 0640);
fchown(con->file, RunUser, Group);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
break;
case HTTP_STATE_DELETE :
case HTTP_STATE_TRACE :
cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
case HTTP_STATE_HEAD :
if (!strncmp(con->uri, "/printers/", 10) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
{
/*
* Send PPD file - get the real printer name since printer
* names are not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
break;
}
}
else if (!strncmp(con->uri, "/printers/", 10) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".png"))
{
/*
* Send PNG file - get the real printer name since printer
* names are not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
break;
}
}
else if (!WebInterface)
{
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_OK);
break;
}
if ((!strncmp(con->uri, "/admin", 6) && strcmp(con->uri, "/admin/conf/cupsd.conf") && strncmp(con->uri, "/admin/log/", 11)) ||
!strncmp(con->uri, "/printers", 9) ||
!strncmp(con->uri, "/classes", 8) ||
!strncmp(con->uri, "/help", 5) ||
!strncmp(con->uri, "/jobs", 5))
{
/*
* CGI output...
*/
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_OK, "text/html", CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_OK);
}
else if (!strncmp(con->uri, "/admin/log/", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))
{
/*
* HEAD can only be done to configuration files under
* /admin/conf...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Request for subdirectory \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_FORBIDDEN);
break;
}
else if ((filename = get_file(con, &filestats, buf,
sizeof(buf))) == NULL)
{
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_NOT_FOUND, "text/html",
CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
}
else if (!check_if_modified(con, &filestats))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_MODIFIED);
}
else
{
/*
* Serve a file...
*/
type = mimeFileType(MimeDatabase, filename, NULL, NULL);
if (type == NULL)
strlcpy(line, "text/plain", sizeof(line));
else
snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
httpGetDateString(filestats.st_mtime));
httpSetLength(con->http, (size_t)filestats.st_size);
if (!cupsdSendHeader(con, HTTP_STATUS_OK, line, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_OK);
}
break;
default :
break; /* Anti-compiler-warning-code */
}
}
}
/*
* Handle any incoming data...
*/
switch (httpGetState(con->http))
{
case HTTP_STATE_PUT_RECV :
do
{
if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
{
if (httpError(con->http) && httpError(con->http) != EPIPE)
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_PUT_RECV Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_PUT_RECV Closing on EOF.");
cupsdCloseClient(con);
return;
}
else if (bytes > 0)
{
con->bytes += bytes;
if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)
{
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
if (write(con->file, line, (size_t)bytes) < bytes)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to write %d bytes to \"%s\": %s", bytes,
con->filename, strerror(errno));
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
else if (httpGetState(con->http) == HTTP_STATE_PUT_RECV)
{
cupsdCloseClient(con);
return;
}
}
while (httpGetState(con->http) == HTTP_STATE_PUT_RECV && httpGetReady(con->http));
if (httpGetState(con->http) == HTTP_STATE_STATUS)
{
/*
* End of file, see how big it is...
*/
fstat(con->file, &filestats);
close(con->file);
con->file = -1;
if (filestats.st_size > MaxRequestSize &&
MaxRequestSize > 0)
{
/*
* Request is too big; remove it and send an error...
*/
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
/*
* Install the configuration file...
*/
status = install_cupsd_conf(con);
/*
* Return the status to the client...
*/
if (!cupsdSendError(con, status, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
break;
case HTTP_STATE_POST_RECV :
do
{
if (con->request && con->file < 0)
{
/*
* Grab any request data from the connection...
*/
if (!httpWait(con->http, 0))
return;
if ((ipp_state = ippRead(con->http, con->request)) == IPP_STATE_ERROR)
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "IPP read error: %s",
cupsLastErrorString());
cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
else if (ipp_state != IPP_STATE_DATA)
{
if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
{
cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
if (httpGetReady(con->http))
continue;
break;
}
else
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "%d.%d %s %d",
con->request->request.op.version[0],
con->request->request.op.version[1],
ippOpString(con->request->request.op.operation_id),
con->request->request.op.request_id);
con->bytes += (off_t)ippLength(con->request);
}
}
if (con->file < 0 && httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
/*
* Create a file as needed for the request data...
*/
cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
request_id ++);
con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
if (con->file < 0)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to create request file \"%s\": %s",
con->filename, strerror(errno));
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
fchmod(con->file, 0640);
fchown(con->file, RunUser, Group);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
}
if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
if (!httpWait(con->http, 0))
return;
else if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
{
if (httpError(con->http) && httpError(con->http) != EPIPE)
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_POST_SEND Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_POST_SEND Closing on EOF.");
cupsdCloseClient(con);
return;
}
else if (bytes > 0)
{
con->bytes += bytes;
if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)
{
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
if (write(con->file, line, (size_t)bytes) < bytes)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to write %d bytes to \"%s\": %s",
bytes, con->filename, strerror(errno));
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE,
CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
else if (httpGetState(con->http) == HTTP_STATE_POST_RECV)
return;
else if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing on unexpected state %s.",
httpStateString(httpGetState(con->http)));
cupsdCloseClient(con);
return;
}
}
}
while (httpGetState(con->http) == HTTP_STATE_POST_RECV && httpGetReady(con->http));
if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
{
if (con->file >= 0)
{
fstat(con->file, &filestats);
close(con->file);
con->file = -1;
if (filestats.st_size > MaxRequestSize &&
MaxRequestSize > 0)
{
/*
* Request is too big; remove it and send an error...
*/
unlink(con->filename);
cupsdClearString(&con->filename);
if (con->request)
{
/*
* Delete any IPP request data...
*/
ippDelete(con->request);
con->request = NULL;
}
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else if (filestats.st_size == 0)
{
/*
* Don't allow empty file...
*/
unlink(con->filename);
cupsdClearString(&con->filename);
}
if (con->command)
{
if (!cupsdSendCommand(con, con->command, con->options, 0))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
cupsdLogRequest(con, HTTP_STATUS_OK);
}
}
if (con->request)
{
cupsdProcessIPPRequest(con);
if (con->filename)
{
unlink(con->filename);
cupsdClearString(&con->filename);
}
return;
}
}
break;
default :
break; /* Anti-compiler-warning-code */
}
if (httpGetState(con->http) == HTTP_STATE_WAITING)
{
if (!httpGetKeepAlive(con->http))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing because Keep-Alive is disabled.");
cupsdCloseClient(con);
}
else
{
cupsArrayRemove(ActiveClients, con);
cupsdSetBusyState();
}
}
}
/*
* 'cupsdSendCommand()' - Send output from a command via HTTP.
*/
int /* O - 1 on success, 0 on failure */
cupsdSendCommand(
cupsd_client_t *con, /* I - Client connection */
char *command, /* I - Command to run */
char *options, /* I - Command-line options */
int root) /* I - Run as root? */
{
int fd; /* Standard input file descriptor */
if (con->filename)
{
fd = open(con->filename, O_RDONLY);
if (fd < 0)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to open \"%s\" for reading: %s",
con->filename ? con->filename : "/dev/null",
strerror(errno));
return (0);
}
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
}
else
fd = -1;
con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
con->pipe_status = HTTP_STATUS_OK;
httpClearFields(con->http);
if (fd >= 0)
close(fd);
cupsdLogClient(con, CUPSD_LOG_INFO, "Started \"%s\" (pid=%d, file=%d)",
command, con->pipe_pid, con->file);
if (con->pipe_pid == 0)
return (0);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
con->sent_header = 0;
con->file_ready = 0;
con->got_fields = 0;
con->header_used = 0;
return (1);
}
/*
* 'cupsdSendError()' - Send an error message via HTTP.
*/
int /* O - 1 if successful, 0 otherwise */
cupsdSendError(cupsd_client_t *con, /* I - Connection */
http_status_t code, /* I - Error code */
int auth_type)/* I - Authentication type */
{
char location[HTTP_MAX_VALUE]; /* Location field */
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdSendError code=%d, auth_type=%d", code, auth_type);
#ifdef HAVE_SSL
/*
* Force client to upgrade for authentication if that is how the
* server is configured...
*/
if (code == HTTP_STATUS_UNAUTHORIZED &&
DefaultEncryption == HTTP_ENCRYPTION_REQUIRED &&
_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost") &&
!httpIsEncrypted(con->http))
{
code = HTTP_STATUS_UPGRADE_REQUIRED;
}
#endif /* HAVE_SSL */
/*
* Put the request in the access_log file...
*/
cupsdLogRequest(con, code);
/*
* To work around bugs in some proxies, don't use Keep-Alive for some
* error messages...
*
* Kerberos authentication doesn't work without Keep-Alive, so
* never disable it in that case.
*/
strlcpy(location, httpGetField(con->http, HTTP_FIELD_LOCATION), sizeof(location));
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_LOCATION, location);
if (code >= HTTP_STATUS_BAD_REQUEST && con->type != CUPSD_AUTH_NEGOTIATE)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
if (httpGetVersion(con->http) >= HTTP_VERSION_1_1 &&
httpGetKeepAlive(con->http) == HTTP_KEEPALIVE_OFF)
httpSetField(con->http, HTTP_FIELD_CONNECTION, "close");
if (code >= HTTP_STATUS_BAD_REQUEST)
{
/*
* Send a human-readable error message.
*/
char message[4096], /* Message for user */
urltext[1024], /* URL redirection text */
redirect[1024]; /* Redirection link */
const char *text; /* Status-specific text */
redirect[0] = '\0';
if (code == HTTP_STATUS_UNAUTHORIZED)
text = _cupsLangString(con->language,
_("Enter your username and password or the "
"root username and password to access this "
"page. If you are using Kerberos authentication, "
"make sure you have a valid Kerberos ticket."));
else if (code == HTTP_STATUS_UPGRADE_REQUIRED)
{
text = urltext;
snprintf(urltext, sizeof(urltext),
_cupsLangString(con->language,
_("You must access this page using the URL "
"<A HREF=\"https://%s:%d%s\">"
"https://%s:%d%s</A>.")),
con->servername, con->serverport, con->uri,
con->servername, con->serverport, con->uri);
snprintf(redirect, sizeof(redirect),
"<META HTTP-EQUIV=\"Refresh\" "
"CONTENT=\"3;URL=https://%s:%d%s\">\n",
con->servername, con->serverport, con->uri);
}
else if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
text = _cupsLangString(con->language,
_("The web interface is currently disabled. Run "
"\"cupsctl WebInterface=yes\" to enable it."));
else
text = "";
snprintf(message, sizeof(message),
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
"\"http://www.w3.org/TR/html4/loose.dtd\">\n"
"<HTML>\n"
"<HEAD>\n"
"\t<META HTTP-EQUIV=\"Content-Type\" "
"CONTENT=\"text/html; charset=utf-8\">\n"
"\t<TITLE>%s - " CUPS_SVERSION "</TITLE>\n"
"\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
"HREF=\"/cups.css\">\n"
"%s"
"</HEAD>\n"
"<BODY>\n"
"<H1>%s</H1>\n"
"<P>%s</P>\n"
"</BODY>\n"
"</HTML>\n",
_httpStatus(con->language, code), redirect,
_httpStatus(con->language, code), text);
/*
* Send an error message back to the client. If the error code is a
* 400 or 500 series, make sure the message contains some text, too!
*/
size_t length = strlen(message); /* Length of message */
httpSetLength(con->http, length);
if (!cupsdSendHeader(con, code, "text/html", auth_type))
return (0);
if (httpWrite2(con->http, message, length) < 0)
return (0);
if (httpFlushWrite(con->http) < 0)
return (0);
}
else
{
httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
if (!cupsdSendHeader(con, code, NULL, auth_type))
return (0);
}
return (1);
}
/*
* 'cupsdSendHeader()' - Send an HTTP request.
*/
int /* O - 1 on success, 0 on failure */
cupsdSendHeader(
cupsd_client_t *con, /* I - Client to send to */
http_status_t code, /* I - HTTP status code */
char *type, /* I - MIME type of document */
int auth_type) /* I - Type of authentication */
{
char auth_str[1024]; /* Authorization string */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code, type, auth_type);
/*
* Send the HTTP status header...
*/
if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
{
/*
* Treat our special "web interface is disabled" status as "200 OK" for web
* browsers.
*/
code = HTTP_STATUS_OK;
}
if (ServerHeader)
httpSetField(con->http, HTTP_FIELD_SERVER, ServerHeader);
if (code == HTTP_STATUS_METHOD_NOT_ALLOWED)
httpSetField(con->http, HTTP_FIELD_ALLOW, "GET, HEAD, OPTIONS, POST, PUT");
if (code == HTTP_STATUS_UNAUTHORIZED)
{
if (auth_type == CUPSD_AUTH_NONE)
{
if (!con->best || con->best->type <= CUPSD_AUTH_NONE)
auth_type = cupsdDefaultAuthType();
else
auth_type = con->best->type;
}
auth_str[0] = '\0';
if (auth_type == CUPSD_AUTH_BASIC)
strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
#ifdef HAVE_GSSAPI
else if (auth_type == CUPSD_AUTH_NEGOTIATE)
{
# ifdef AF_LOCAL
if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
else
# endif /* AF_LOCAL */
strlcpy(auth_str, "Negotiate", sizeof(auth_str));
}
#endif /* HAVE_GSSAPI */
if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE &&
!_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost"))
{
/*
* Add a "trc" (try root certification) parameter for local non-Kerberos
* requests when the request requires system group membership - then the
* client knows the root certificate can/should be used.
*
* Also, for macOS we also look for @AUTHKEY and add an "authkey"
* parameter as needed...
*/
char *name, /* Current user name */
*auth_key; /* Auth key buffer */
size_t auth_size; /* Size of remaining buffer */
auth_key = auth_str + strlen(auth_str);
auth_size = sizeof(auth_str) - (size_t)(auth_key - auth_str);
for (name = (char *)cupsArrayFirst(con->best->names);
name;
name = (char *)cupsArrayNext(con->best->names))
{
#ifdef HAVE_AUTHORIZATION_H
if (!_cups_strncasecmp(name, "@AUTHKEY(", 9))
{
snprintf(auth_key, auth_size, ", authkey=\"%s\"", name + 9);
/* end parenthesis is stripped in conf.c */
break;
}
else
#endif /* HAVE_AUTHORIZATION_H */
if (!_cups_strcasecmp(name, "@SYSTEM"))
{
#ifdef HAVE_AUTHORIZATION_H
if (SystemGroupAuthKey)
snprintf(auth_key, auth_size,
", authkey=\"%s\"",
SystemGroupAuthKey);
else
#else
strlcpy(auth_key, ", trc=\"y\"", auth_size);
#endif /* HAVE_AUTHORIZATION_H */
break;
}
}
}
if (auth_str[0])
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "WWW-Authenticate: %s", auth_str);
httpSetField(con->http, HTTP_FIELD_WWW_AUTHENTICATE, auth_str);
}
}
if (con->language && strcmp(con->language->language, "C"))
httpSetField(con->http, HTTP_FIELD_CONTENT_LANGUAGE, con->language->language);
if (type)
{
if (!strcmp(type, "text/html"))
httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, "text/html; charset=utf-8");
else
httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, type);
}
return (!httpWriteResponse(con->http, code));
}
/*
* 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
*/
void
cupsdUpdateCGI(void)
{
char *ptr, /* Pointer to end of line in buffer */
message[1024]; /* Pointer to message text */
int loglevel; /* Log level for message */
while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
message, sizeof(message))) != NULL)
{
if (loglevel == CUPSD_LOG_INFO)
cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
if (!strchr(CGIStatusBuffer->buffer, '\n'))
break;
}
if (ptr == NULL && !CGIStatusBuffer->bufused)
{
/*
* Fatal error on pipe - should never happen!
*/
cupsdLogMessage(CUPSD_LOG_CRIT,
"cupsdUpdateCGI: error reading from CGI error pipe - %s",
strerror(errno));
}
}
/*
* 'cupsdWriteClient()' - Write data to a client as needed.
*/
void
cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
{
int bytes, /* Number of bytes written */
field_col; /* Current column */
char *bufptr, /* Pointer into buffer */
*bufend; /* Pointer to end of buffer */
ipp_state_t ipp_state; /* IPP state value */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "con->http=%p", con->http);
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"cupsdWriteClient "
"error=%d, "
"used=%d, "
"state=%s, "
"data_encoding=HTTP_ENCODING_%s, "
"data_remaining=" CUPS_LLFMT ", "
"response=%p(%s), "
"pipe_pid=%d, "
"file=%d",
httpError(con->http), (int)httpGetReady(con->http),
httpStateString(httpGetState(con->http)),
httpIsChunked(con->http) ? "CHUNKED" : "LENGTH",
CUPS_LLCAST httpGetLength2(con->http),
con->response,
con->response ? ippStateString(ippGetState(con->request)) : "",
con->pipe_pid, con->file);
if (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
/*
* If we get called in the wrong state, then something went wrong with the
* connection and we need to shut it down...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP write state %s.",
httpStateString(httpGetState(con->http)));
cupsdCloseClient(con);
return;
}
if (con->pipe_pid)
{
/*
* Make sure we select on the CGI output...
*/
cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
if (!con->file_ready)
{
/*
* Try again later when there is CGI output available...
*/
cupsdRemoveSelect(httpGetFd(con->http));
return;
}
con->file_ready = 0;
}
bytes = (ssize_t)(sizeof(con->header) - (size_t)con->header_used);
if (!con->pipe_pid && bytes > (ssize_t)httpGetRemaining(con->http))
{
/*
* Limit GET bytes to original size of file (STR #3265)...
*/
bytes = (ssize_t)httpGetRemaining(con->http);
}
if (con->response && con->response->state != IPP_STATE_DATA)
{
size_t wused = httpGetPending(con->http); /* Previous write buffer use */
do
{
/*
* Write a single attribute or the IPP message header...
*/
ipp_state = ippWrite(con->http, con->response);
/*
* If the write buffer has been flushed, stop buffering up attributes...
*/
if (httpGetPending(con->http) <= wused)
break;
}
while (ipp_state != IPP_STATE_DATA && ipp_state != IPP_STATE_ERROR);
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Writing IPP response, ipp_state=%s, old "
"wused=" CUPS_LLFMT ", new wused=" CUPS_LLFMT,
ippStateString(ipp_state),
CUPS_LLCAST wused, CUPS_LLCAST httpGetPending(con->http));
if (httpGetPending(con->http) > 0)
httpFlushWrite(con->http);
bytes = ipp_state != IPP_STATE_ERROR &&
(con->file >= 0 || ipp_state != IPP_STATE_DATA);
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT,
(int)bytes, httpGetState(con->http),
CUPS_LLCAST httpGetLength2(con->http));
}
else if ((bytes = read(con->file, con->header + con->header_used, (size_t)bytes)) > 0)
{
con->header_used += bytes;
if (con->pipe_pid && !con->got_fields)
{
/*
* Inspect the data for Content-Type and other fields.
*/
for (bufptr = con->header, bufend = con->header + con->header_used,
field_col = 0;
!con->got_fields && bufptr < bufend;
bufptr ++)
{
if (*bufptr == '\n')
{
/*
* Send line to client...
*/
if (bufptr > con->header && bufptr[-1] == '\r')
bufptr[-1] = '\0';
*bufptr++ = '\0';
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Script header: %s", con->header);
if (!con->sent_header)
{
/*
* Handle redirection and CGI status codes...
*/
http_field_t field; /* HTTP field */
char *value = strchr(con->header, ':');
/* Value of field */
if (value)
{
*value++ = '\0';
while (isspace(*value & 255))
value ++;
}
field = httpFieldValue(con->header);
if (field != HTTP_FIELD_UNKNOWN && value)
{
httpSetField(con->http, field, value);
if (field == HTTP_FIELD_LOCATION)
{
con->pipe_status = HTTP_STATUS_SEE_OTHER;
con->sent_header = 2;
}
else
con->sent_header = 1;
}
else if (!_cups_strcasecmp(con->header, "Status") && value)
{
con->pipe_status = (http_status_t)atoi(value);
con->sent_header = 2;
}
else if (!_cups_strcasecmp(con->header, "Set-Cookie") && value)
{
httpSetCookie(con->http, value);
con->sent_header = 1;
}
}
/*
* Update buffer...
*/
con->header_used -= bufptr - con->header;
if (con->header_used > 0)
memmove(con->header, bufptr, (size_t)con->header_used);
bufptr = con->header - 1;
/*
* See if the line was empty...
*/
if (field_col == 0)
{
con->got_fields = 1;
if (httpGetVersion(con->http) == HTTP_VERSION_1_1 &&
!httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0])
httpSetLength(con->http, 0);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending status %d for CGI.", con->pipe_status);
if (con->pipe_status == HTTP_STATUS_OK)
{
if (!cupsdSendHeader(con, con->pipe_status, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
{
if (!cupsdSendError(con, con->pipe_status, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
else
field_col = 0;
}
else if (*bufptr != '\r')
field_col ++;
}
if (!con->got_fields)
return;
}
if (con->header_used > 0)
{
if (httpWrite2(con->http, con->header, (size_t)con->header_used) < 0)
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
cupsdCloseClient(con);
return;
}
if (httpIsChunked(con->http))
httpFlushWrite(con->http);
con->bytes += con->header_used;
if (httpGetState(con->http) == HTTP_STATE_WAITING)
bytes = 0;
else
bytes = con->header_used;
con->header_used = 0;
}
}
if (bytes <= 0 ||
(httpGetState(con->http) != HTTP_STATE_GET_SEND &&
httpGetState(con->http) != HTTP_STATE_POST_SEND))
{
if (!con->sent_header && con->pipe_pid)
cupsdSendError(con, HTTP_STATUS_SERVER_ERROR, CUPSD_AUTH_NONE);
else
{
cupsdLogRequest(con, HTTP_STATUS_OK);
if (httpIsChunked(con->http) && (!con->pipe_pid || con->sent_header > 0))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending 0-length chunk.");
if (httpWrite2(con->http, "", 0) < 0)
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
cupsdCloseClient(con);
return;
}
}
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Flushing write buffer.");
httpFlushWrite(con->http);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "New state is %s", httpStateString(httpGetState(con->http)));
}
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
if (con->file >= 0)
{
cupsdRemoveSelect(con->file);
if (con->pipe_pid)
cupsdEndProcess(con->pipe_pid, 0);
close(con->file);
con->file = -1;
con->pipe_pid = 0;
}
if (con->filename)
{
unlink(con->filename);
cupsdClearString(&con->filename);
}
if (con->request)
{
ippDelete(con->request);
con->request = NULL;
}
if (con->response)
{
ippDelete(con->response);
con->response = NULL;
}
cupsdClearString(&con->command);
cupsdClearString(&con->options);
cupsdClearString(&con->query_string);
if (!httpGetKeepAlive(con->http))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing because Keep-Alive is disabled.");
cupsdCloseClient(con);
return;
}
else
{
cupsArrayRemove(ActiveClients, con);
cupsdSetBusyState();
}
}
}
/*
* 'check_if_modified()' - Decode an "If-Modified-Since" line.
*/
static int /* O - 1 if modified since */
check_if_modified(
cupsd_client_t *con, /* I - Client connection */
struct stat *filestats) /* I - File information */
{
const char *ptr; /* Pointer into field */
time_t date; /* Time/date value */
off_t size; /* Size/length value */
size = 0;
date = 0;
ptr = httpGetField(con->http, HTTP_FIELD_IF_MODIFIED_SINCE);
if (*ptr == '\0')
return (1);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "check_if_modified: filestats=%p(" CUPS_LLFMT ", %d)) If-Modified-Since=\"%s\"", filestats, CUPS_LLCAST filestats->st_size, (int)filestats->st_mtime, ptr);
while (*ptr != '\0')
{
while (isspace(*ptr) || *ptr == ';')
ptr ++;
if (_cups_strncasecmp(ptr, "length=", 7) == 0)
{
ptr += 7;
size = strtoll(ptr, NULL, 10);
while (isdigit(*ptr))
ptr ++;
}
else if (isalpha(*ptr))
{
date = httpGetDateTime(ptr);
while (*ptr != '\0' && *ptr != ';')
ptr ++;
}
else
ptr ++;
}
return ((size != filestats->st_size && size != 0) ||
(date < filestats->st_mtime && date != 0) ||
(size == 0 && date == 0));
}
/*
* 'compare_clients()' - Compare two client connections.
*/
static int /* O - Result of comparison */
compare_clients(cupsd_client_t *a, /* I - First client */
cupsd_client_t *b, /* I - Second client */
void *data) /* I - User data (not used) */
{
(void)data;
if (a == b)
return (0);
else if (a < b)
return (-1);
else
return (1);
}
#ifdef HAVE_SSL
/*
* 'cupsd_start_tls()' - Start encryption on a connection.
*/
static int /* O - 0 on success, -1 on error */
cupsd_start_tls(cupsd_client_t *con, /* I - Client connection */
http_encryption_t e) /* I - Encryption mode */
{
if (httpEncryption(con->http, e))
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to encrypt connection: %s",
cupsLastErrorString());
return (-1);
}
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Connection now encrypted.");
return (0);
}
#endif /* HAVE_SSL */
/*
* 'get_file()' - Get a filename and state info.
*/
static char * /* O - Real filename */
get_file(cupsd_client_t *con, /* I - Client connection */
struct stat *filestats, /* O - File information */
char *filename, /* IO - Filename buffer */
size_t len) /* I - Buffer length */
{
int status; /* Status of filesystem calls */
char *ptr; /* Pointer info filename */
size_t plen; /* Remaining length after pointer */
char language[7], /* Language subdirectory, if any */
dest[1024]; /* Destination name */
int perm_check = 1; /* Do permissions check? */
/*
* Figure out the real filename...
*/
language[0] = '\0';
if (!strncmp(con->uri, "/ppd/", 5) && !strchr(con->uri + 5, '/'))
{
strlcpy(dest, con->uri + 5, sizeof(dest));
ptr = dest + strlen(dest) - 4;
if (ptr <= dest || strcmp(ptr, ".ppd"))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Disallowed path \"%s\".", con->uri);
return (NULL);
}
*ptr = '\0';
if (!cupsdFindPrinter(dest))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "No printer \"%s\" found.", dest);
return (NULL);
}
snprintf(filename, len, "%s%s", ServerRoot, con->uri);
perm_check = 0;
}
else if (!strncmp(con->uri, "/icons/", 7) && !strchr(con->uri + 7, '/'))
{
strlcpy(dest, con->uri + 7, sizeof(dest));
ptr = dest + strlen(dest) - 4;
if (ptr <= dest || strcmp(ptr, ".png"))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Disallowed path \"%s\".", con->uri);
return (NULL);
}
*ptr = '\0';
if (!cupsdFindDest(dest))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "No printer \"%s\" found.", dest);
return (NULL);
}
snprintf(filename, len, "%s/%s.png", CacheDir, dest);
if (access(filename, F_OK) < 0)
snprintf(filename, len, "%s/images/generic.png", DocumentRoot);
perm_check = 0;
}
else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
else if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
{
strlcpy(filename, ConfigurationFile, len);
perm_check = 0;
}
else if (!strncmp(con->uri, "/admin/log/", 11))
{
if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
strlcpy(filename, AccessLog, len);
else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
strlcpy(filename, ErrorLog, len);
else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
strlcpy(filename, PageLog, len);
else
return (NULL);
perm_check = 0;
}
else if (con->language)
{
snprintf(language, sizeof(language), "/%s", con->language->language);
snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
}
else
snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
/*
* Grab the status for this language; if there isn't a language-specific file
* then fallback to the default one...
*/
if ((status = lstat(filename, filestats)) != 0 && language[0] &&
strncmp(con->uri, "/icons/", 7) &&
strncmp(con->uri, "/ppd/", 5) &&
strncmp(con->uri, "/rss/", 5) &&
strncmp(con->uri, "/admin/conf/", 12) &&
strncmp(con->uri, "/admin/log/", 11))
{
/*
* Drop the country code...
*/
language[3] = '\0';
snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
if ((status = lstat(filename, filestats)) != 0)
{
/*
* Drop the language prefix and try the root directory...
*/
language[0] = '\0';
snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
status = lstat(filename, filestats);
}
}
/*
* If we've found a symlink, 404 the sucker to avoid disclosing information.
*/
if (!status && S_ISLNK(filestats->st_mode))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Symlinks such as \"%s\" are not allowed.", filename);
return (NULL);
}
/*
* Similarly, if the file/directory does not have world read permissions, do
* not allow access...
*/
if (!status && perm_check && !(filestats->st_mode & S_IROTH))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Files/directories such as \"%s\" must be world-readable.", filename);
return (NULL);
}
/*
* If we've found a directory, get the index.html file instead...
*/
if (!status && S_ISDIR(filestats->st_mode))
{
/*
* Make sure the URI ends with a slash...
*/
if (con->uri[strlen(con->uri) - 1] != '/')
strlcat(con->uri, "/", sizeof(con->uri));
/*
* Find the directory index file, trying every language...
*/
do
{
if (status && language[0])
{
/*
* Try a different language subset...
*/
if (language[3])
language[0] = '\0'; /* Strip country code */
else
language[0] = '\0'; /* Strip language */
}
/*
* Look for the index file...
*/
snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
ptr = filename + strlen(filename);
plen = len - (size_t)(ptr - filename);
strlcpy(ptr, "index.html", plen);
status = lstat(filename, filestats);
#ifdef HAVE_JAVA
if (status)
{
strlcpy(ptr, "index.class", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_JAVA */
#ifdef HAVE_PERL
if (status)
{
strlcpy(ptr, "index.pl", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_PERL */
#ifdef HAVE_PHP
if (status)
{
strlcpy(ptr, "index.php", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_PHP */
#ifdef HAVE_PYTHON
if (status)
{
strlcpy(ptr, "index.pyc", plen);
status = lstat(filename, filestats);
}
if (status)
{
strlcpy(ptr, "index.py", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_PYTHON */
}
while (status && language[0]);
/*
* If we've found a symlink, 404 the sucker to avoid disclosing information.
*/
if (!status && S_ISLNK(filestats->st_mode))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Symlinks such as \"%s\" are not allowed.", filename);
return (NULL);
}
/*
* Similarly, if the file/directory does not have world read permissions, do
* not allow access...
*/
if (!status && perm_check && !(filestats->st_mode & S_IROTH))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Files/directories such as \"%s\" must be world-readable.", filename);
return (NULL);
}
}
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT ", returning \"%s\".", filestats, filename, CUPS_LLCAST len, status ? "(null)" : filename);
if (status)
return (NULL);
else
return (filename);
}
/*
* 'install_cupsd_conf()' - Install a configuration file.
*/
static http_status_t /* O - Status */
install_cupsd_conf(cupsd_client_t *con) /* I - Connection */
{
char filename[1024]; /* Configuration filename */
cups_file_t *in, /* Input file */
*out; /* Output file */
char buffer[16384]; /* Copy buffer */
ssize_t bytes; /* Number of bytes */
/*
* Open the request file...
*/
if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to open request file \"%s\": %s",
con->filename, strerror(errno));
goto server_error;
}
/*
* Open the new config file...
*/
if ((out = cupsdCreateConfFile(ConfigurationFile, ConfigFilePerm)) == NULL)
{
cupsFileClose(in);
goto server_error;
}
cupsdLogClient(con, CUPSD_LOG_INFO, "Installing config file \"%s\"...",
ConfigurationFile);
/*
* Copy from the request to the new config file...
*/
while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
if (cupsFileWrite(out, buffer, (size_t)bytes) < bytes)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to copy to config file \"%s\": %s",
ConfigurationFile, strerror(errno));
cupsFileClose(in);
cupsFileClose(out);
snprintf(filename, sizeof(filename), "%s.N", ConfigurationFile);
cupsdUnlinkOrRemoveFile(filename);
goto server_error;
}
/*
* Close the files...
*/
cupsFileClose(in);
if (cupsdCloseCreatedConfFile(out, ConfigurationFile))
goto server_error;
/*
* Remove the request file...
*/
cupsdUnlinkOrRemoveFile(con->filename);
cupsdClearString(&con->filename);
/*
* Set the NeedReload flag...
*/
NeedReload = RELOAD_CUPSD;
ReloadTime = time(NULL);
/*
* Return that the file was created successfully...
*/
return (HTTP_STATUS_CREATED);
/*
* Common exit for errors...
*/
server_error:
cupsdUnlinkOrRemoveFile(con->filename);
cupsdClearString(&con->filename);
return (HTTP_STATUS_SERVER_ERROR);
}
/*
* 'is_cgi()' - Is the resource a CGI script/program?
*/
static int /* O - 1 = CGI, 0 = file */
is_cgi(cupsd_client_t *con, /* I - Client connection */
const char *filename, /* I - Real filename */
struct stat *filestats, /* I - File information */
mime_type_t *type) /* I - MIME type */
{
const char *options; /* Options on URL */
/*
* Get the options, if any...
*/
if ((options = strchr(con->uri, '?')) != NULL)
{
options ++;
cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
}
/*
* Check for known types...
*/
if (!type || _cups_strcasecmp(type->super, "application"))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename, filestats, type ? type->super : "unknown", type ? type->type : "unknown");
return (0);
}
if (!_cups_strcasecmp(type->type, "x-httpd-cgi") &&
(filestats->st_mode & 0111))
{
/*
* "application/x-httpd-cgi" is a CGI script.
*/
cupsdSetString(&con->command, filename);
if (options)
cupsdSetStringf(&con->options, " %s", options);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#ifdef HAVE_JAVA
else if (!_cups_strcasecmp(type->type, "x-httpd-java"))
{
/*
* "application/x-httpd-java" is a Java servlet.
*/
cupsdSetString(&con->command, CUPS_JAVA);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_JAVA */
#ifdef HAVE_PERL
else if (!_cups_strcasecmp(type->type, "x-httpd-perl"))
{
/*
* "application/x-httpd-perl" is a Perl page.
*/
cupsdSetString(&con->command, CUPS_PERL);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_PERL */
#ifdef HAVE_PHP
else if (!_cups_strcasecmp(type->type, "x-httpd-php"))
{
/*
* "application/x-httpd-php" is a PHP page.
*/
cupsdSetString(&con->command, CUPS_PHP);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_PHP */
#ifdef HAVE_PYTHON
else if (!_cups_strcasecmp(type->type, "x-httpd-python"))
{
/*
* "application/x-httpd-python" is a Python page.
*/
cupsdSetString(&con->command, CUPS_PYTHON);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_PYTHON */
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename, filestats, type->super, type->type);
return (0);
}
/*
* 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
*/
static int /* O - 0 if relative, 1 if absolute */
is_path_absolute(const char *path) /* I - Input path */
{
/*
* Check for a leading slash...
*/
if (path[0] != '/')
return (0);
/*
* Check for "<" or quotes in the path and reject since this is probably
* someone trying to inject HTML...
*/
if (strchr(path, '<') != NULL || strchr(path, '\"') != NULL || strchr(path, '\'') != NULL)
return (0);
/*
* Check for "/.." in the path...
*/
while ((path = strstr(path, "/..")) != NULL)
{
if (!path[3] || path[3] == '/')
return (0);
path ++;
}
/*
* If we haven't found any relative paths, return 1 indicating an
* absolute path...
*/
return (1);
}
/*
* 'pipe_command()' - Pipe the output of a command to the remote client.
*/
static int /* O - Process ID */
pipe_command(cupsd_client_t *con, /* I - Client connection */
int infile, /* I - Standard input for command */
int *outfile, /* O - Standard output for command */
char *command, /* I - Command to run */
char *options, /* I - Options for command */
int root) /* I - Run as root? */
{
int i; /* Looping var */
int pid; /* Process ID */
char *commptr, /* Command string pointer */
commch; /* Command string character */
char *uriptr; /* URI string pointer */
int fds[2]; /* Pipe FDs */
int argc; /* Number of arguments */
int envc; /* Number of environment variables */
char argbuf[10240], /* Argument buffer */
*argv[100], /* Argument strings */
*envp[MAX_ENV + 20]; /* Environment variables */
char auth_type[256], /* AUTH_TYPE environment variable */
content_length[1024], /* CONTENT_LENGTH environment variable */
content_type[1024], /* CONTENT_TYPE environment variable */
http_cookie[32768], /* HTTP_COOKIE environment variable */
http_referer[1024], /* HTTP_REFERER environment variable */
http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
lang[1024], /* LANG environment variable */
path_info[1024], /* PATH_INFO environment variable */
remote_addr[1024], /* REMOTE_ADDR environment variable */
remote_host[1024], /* REMOTE_HOST environment variable */
remote_user[1024], /* REMOTE_USER environment variable */
script_filename[1024], /* SCRIPT_FILENAME environment variable */
script_name[1024], /* SCRIPT_NAME environment variable */
server_name[1024], /* SERVER_NAME environment variable */
server_port[1024]; /* SERVER_PORT environment variable */
ipp_attribute_t *attr; /* attributes-natural-language attribute */
/*
* Parse a copy of the options string, which is of the form:
*
* argument+argument+argument
* ?argument+argument+argument
* param=value¶m=value
* ?param=value¶m=value
* /name?argument+argument+argument
* /name?param=value¶m=value
*
* If the string contains an "=" character after the initial name,
* then we treat it as a HTTP GET form request and make a copy of
* the remaining string for the environment variable.
*
* The string is always parsed out as command-line arguments, to
* be consistent with Apache...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile, outfile, command, options ? options : "(null)", root);
argv[0] = command;
if (options)
strlcpy(argbuf, options, sizeof(argbuf));
else
argbuf[0] = '\0';
if (argbuf[0] == '/')
{
/*
* Found some trailing path information, set PATH_INFO...
*/
if ((commptr = strchr(argbuf, '?')) == NULL)
commptr = argbuf + strlen(argbuf);
commch = *commptr;
*commptr = '\0';
snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
*commptr = commch;
}
else
{
commptr = argbuf;
path_info[0] = '\0';
if (*commptr == ' ')
commptr ++;
}
if (*commptr == '?' && con->operation == HTTP_STATE_GET && !con->query_string)
{
commptr ++;
cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
}
argc = 1;
if (*commptr)
{
argv[argc ++] = commptr;
for (; *commptr && argc < 99; commptr ++)
{
/*
* Break arguments whenever we see a + or space...
*/
if (*commptr == ' ' || *commptr == '+')
{
while (*commptr == ' ' || *commptr == '+')
*commptr++ = '\0';
/*
* If we don't have a blank string, save it as another argument...
*/
if (*commptr)
{
argv[argc] = commptr;
argc ++;
}
else
break;
}
else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
isxdigit(commptr[2] & 255))
{
/*
* Convert the %xx notation to the individual character.
*/
if (commptr[1] >= '0' && commptr[1] <= '9')
*commptr = (char)((commptr[1] - '0') << 4);
else
*commptr = (char)((tolower(commptr[1]) - 'a' + 10) << 4);
if (commptr[2] >= '0' && commptr[2] <= '9')
*commptr |= commptr[2] - '0';
else
*commptr |= tolower(commptr[2]) - 'a' + 10;
_cups_strcpy(commptr + 1, commptr + 3);
/*
* Check for a %00 and break if that is the case...
*/
if (!*commptr)
break;
}
}
}
argv[argc] = NULL;
/*
* Setup the environment variables as needed...
*/
if (con->username[0])
{
snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
httpGetField(con->http, HTTP_FIELD_AUTHORIZATION));
if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
*uriptr = '\0';
}
else
auth_type[0] = '\0';
if (con->request &&
(attr = ippFindAttribute(con->request, "attributes-natural-language",
IPP_TAG_LANGUAGE)) != NULL)
{
switch (strlen(attr->values[0].string.text))
{
default :
/*
* This is an unknown or badly formatted language code; use
* the POSIX locale...
*/
strlcpy(lang, "LANG=C", sizeof(lang));
break;
case 2 :
/*
* Just the language code (ll)...
*/
snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
attr->values[0].string.text);
break;
case 5 :
/*
* Language and country code (ll-cc)...
*/
snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
attr->values[0].string.text[0],
attr->values[0].string.text[1],
toupper(attr->values[0].string.text[3] & 255),
toupper(attr->values[0].string.text[4] & 255));
break;
}
}
else if (con->language)
snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
else
strlcpy(lang, "LANG=C", sizeof(lang));
strlcpy(remote_addr, "REMOTE_ADDR=", sizeof(remote_addr));
httpAddrString(httpGetAddress(con->http), remote_addr + 12,
sizeof(remote_addr) - 12);
snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
httpGetHostname(con->http, NULL, 0));
snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
if ((uriptr = strchr(script_name, '?')) != NULL)
*uriptr = '\0';
snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
DocumentRoot, script_name + 12);
snprintf(server_port, sizeof(server_port), "SERVER_PORT=%d", con->serverport);
if (httpGetField(con->http, HTTP_FIELD_HOST)[0])
{
char *nameptr; /* Pointer to ":port" */
snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
httpGetField(con->http, HTTP_FIELD_HOST));
if ((nameptr = strrchr(server_name, ':')) != NULL && !strchr(nameptr, ']'))
*nameptr = '\0'; /* Strip trailing ":port" */
}
else
snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
con->servername);
envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
if (auth_type[0])
envp[envc ++] = auth_type;
envp[envc ++] = lang;
envp[envc ++] = "REDIRECT_STATUS=1";
envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
envp[envc ++] = server_name;
envp[envc ++] = server_port;
envp[envc ++] = remote_addr;
envp[envc ++] = remote_host;
envp[envc ++] = script_name;
envp[envc ++] = script_filename;
if (path_info[0])
envp[envc ++] = path_info;
if (con->username[0])
{
snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
envp[envc ++] = remote_user;
}
if (httpGetVersion(con->http) == HTTP_VERSION_1_1)
envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
else if (httpGetVersion(con->http) == HTTP_VERSION_1_0)
envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
else
envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
if (httpGetCookie(con->http))
{
snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
httpGetCookie(con->http));
envp[envc ++] = http_cookie;
}
if (httpGetField(con->http, HTTP_FIELD_USER_AGENT)[0])
{
snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
httpGetField(con->http, HTTP_FIELD_USER_AGENT));
envp[envc ++] = http_user_agent;
}
if (httpGetField(con->http, HTTP_FIELD_REFERER)[0])
{
snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
httpGetField(con->http, HTTP_FIELD_REFERER));
envp[envc ++] = http_referer;
}
if (con->operation == HTTP_STATE_GET)
{
envp[envc ++] = "REQUEST_METHOD=GET";
if (con->query_string)
{
/*
* Add GET form variables after ?...
*/
envp[envc ++] = con->query_string;
}
else
envp[envc ++] = "QUERY_STRING=";
}
else
{
sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
CUPS_LLCAST con->bytes);
snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE));
envp[envc ++] = "REQUEST_METHOD=POST";
envp[envc ++] = content_length;
envp[envc ++] = content_type;
}
/*
* Tell the CGI if we are using encryption...
*/
if (httpIsEncrypted(con->http))
envp[envc ++] = "HTTPS=ON";
/*
* Terminate the environment array...
*/
envp[envc] = NULL;
if (LogLevel >= CUPSD_LOG_DEBUG)
{
for (i = 0; i < argc; i ++)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[CGI] argv[%d] = \"%s\"", i, argv[i]);
for (i = 0; i < envc; i ++)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[CGI] envp[%d] = \"%s\"", i, envp[i]);
}
/*
* Create a pipe for the output...
*/
if (cupsdOpenPipe(fds))
{
cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to create pipe for %s - %s",
argv[0], strerror(errno));
return (0);
}
/*
* Then execute the command...
*/
if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
-1, -1, root, DefaultProfile, NULL, &pid) < 0)
{
/*
* Error - can't fork!
*/
cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to start %s - %s", argv[0],
strerror(errno));
cupsdClosePipe(fds);
pid = 0;
}
else
{
/*
* Fork successful - return the PID...
*/
if (con->username[0])
cupsdAddCert(pid, con->username, con->type);
cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] Started %s (PID %d)", command, pid);
*outfile = fds[0];
close(fds[1]);
}
return (pid);
}
/*
* 'valid_host()' - Is the Host: field valid?
*/
static int /* O - 1 if valid, 0 if not */
valid_host(cupsd_client_t *con) /* I - Client connection */
{
cupsd_alias_t *a; /* Current alias */
cupsd_netif_t *netif; /* Current network interface */
const char *end; /* End character */
char *ptr; /* Pointer into host value */
/*
* Copy the Host: header for later use...
*/
strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),
sizeof(con->clientname));
if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))
{
*ptr++ = '\0';
con->clientport = atoi(ptr);
}
else
con->clientport = con->serverport;
/*
* Then validate...
*/
if (httpAddrLocalhost(httpGetAddress(con->http)))
{
/*
* Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
* addresses when accessing CUPS via the loopback interface...
*/
return (!_cups_strcasecmp(con->clientname, "localhost") ||
!_cups_strcasecmp(con->clientname, "localhost.") ||
#ifdef __linux
!_cups_strcasecmp(con->clientname, "localhost.localdomain") ||
#endif /* __linux */
!strcmp(con->clientname, "127.0.0.1") ||
!strcmp(con->clientname, "[::1]"));
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
/*
* Check if the hostname is something.local (Bonjour); if so, allow it.
*/
if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&
!end[1])
{
/*
* "." on end, work back to second-to-last "."...
*/
for (end --; end > con->clientname && *end != '.'; end --);
}
if (end && (!_cups_strcasecmp(end, ".local") ||
!_cups_strcasecmp(end, ".local.")))
return (1);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check if the hostname is an IP address...
*/
if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')
{
/*
* Possible IPv4/IPv6 address...
*/
http_addrlist_t *addrlist; /* List of addresses */
if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)
{
/*
* Good IPv4/IPv6 address...
*/
httpAddrFreeList(addrlist);
return (1);
}
}
/*
* Check for (alias) name matches...
*/
for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check for interface hostname matches...
*/
for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
netif;
netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
{
if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + netif->hostlen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
return (0);
}
/*
* 'write_file()' - Send a file via HTTP.
*/
static int /* O - 0 on failure, 1 on success */
write_file(cupsd_client_t *con, /* I - Client connection */
http_status_t code, /* I - HTTP status */
char *filename, /* I - Filename */
char *type, /* I - File type */
struct stat *filestats) /* O - File information */
{
con->file = open(filename, O_RDONLY);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code, filename, con->file, type ? type : "(null)", filestats);
if (con->file < 0)
return (0);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
con->pipe_pid = 0;
con->sent_header = 1;
httpClearFields(con->http);
httpSetLength(con->http, (size_t)filestats->st_size);
httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
httpGetDateString(filestats->st_mtime));
if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
return (0);
cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending file.");
return (1);
}
/*
* 'write_pipe()' - Flag that data is available on the CGI pipe.
*/
static void
write_pipe(cupsd_client_t *con) /* I - Client connection */
{
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d.", con->file);
con->file_ready = 1;
cupsdRemoveSelect(con->file);
cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "CGI data ready to be sent.");
}
| ./CrossVul/dataset_final_sorted/CWE-290/c/bad_3010_0 |
crossvul-cpp_data_good_3010_0 | /*
* Client routines for the CUPS scheduler.
*
* Copyright 2007-2015 by Apple Inc.
* Copyright 1997-2007 by Easy Software Products, all rights reserved.
*
* This file contains Kerberos support code, copyright 2006 by
* Jelmer Vernooij.
*
* These coded instructions, statements, and computer programs are the
* property of Apple Inc. and are protected by Federal copyright
* law. Distribution and use rights are outlined in the file "LICENSE.txt"
* which should have been included with this file. If this file is
* file is missing or damaged, see the license at "http://www.cups.org/".
*/
/*
* Include necessary headers...
*/
#define _CUPS_NO_DEPRECATED
#define _HTTP_NO_PRIVATE
#include "cupsd.h"
#ifdef __APPLE__
# include <libproc.h>
#endif /* __APPLE__ */
#ifdef HAVE_TCPD_H
# include <tcpd.h>
#endif /* HAVE_TCPD_H */
/*
* Local functions...
*/
static int check_if_modified(cupsd_client_t *con,
struct stat *filestats);
static int compare_clients(cupsd_client_t *a, cupsd_client_t *b,
void *data);
#ifdef HAVE_SSL
static int cupsd_start_tls(cupsd_client_t *con, http_encryption_t e);
#endif /* HAVE_SSL */
static char *get_file(cupsd_client_t *con, struct stat *filestats,
char *filename, size_t len);
static http_status_t install_cupsd_conf(cupsd_client_t *con);
static int is_cgi(cupsd_client_t *con, const char *filename,
struct stat *filestats, mime_type_t *type);
static int is_path_absolute(const char *path);
static int pipe_command(cupsd_client_t *con, int infile, int *outfile,
char *command, char *options, int root);
static int valid_host(cupsd_client_t *con);
static int write_file(cupsd_client_t *con, http_status_t code,
char *filename, char *type,
struct stat *filestats);
static void write_pipe(cupsd_client_t *con);
/*
* 'cupsdAcceptClient()' - Accept a new client.
*/
void
cupsdAcceptClient(cupsd_listener_t *lis)/* I - Listener socket */
{
const char *hostname; /* Hostname of client */
char name[256]; /* Hostname of client */
int count; /* Count of connections on a host */
cupsd_client_t *con, /* New client pointer */
*tempcon; /* Temporary client pointer */
socklen_t addrlen; /* Length of address */
http_addr_t temp; /* Temporary address variable */
static time_t last_dos = 0; /* Time of last DoS attack */
#ifdef HAVE_TCPD_H
struct request_info wrap_req; /* TCP wrappers request information */
#endif /* HAVE_TCPD_H */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis, lis->fd, cupsArrayCount(Clients));
/*
* Make sure we don't have a full set of clients already...
*/
if (cupsArrayCount(Clients) == MaxClients)
return;
/*
* Get a pointer to the next available client...
*/
if (!Clients)
Clients = cupsArrayNew(NULL, NULL);
if (!Clients)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to allocate memory for clients array!");
cupsdPauseListening();
return;
}
if (!ActiveClients)
ActiveClients = cupsArrayNew((cups_array_func_t)compare_clients, NULL);
if (!ActiveClients)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to allocate memory for active clients array!");
cupsdPauseListening();
return;
}
if ((con = calloc(1, sizeof(cupsd_client_t))) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to allocate memory for client!");
cupsdPauseListening();
return;
}
/*
* Accept the client and get the remote address...
*/
con->number = ++ LastClientNumber;
con->file = -1;
if ((con->http = httpAcceptConnection(lis->fd, 0)) == NULL)
{
if (errno == ENFILE || errno == EMFILE)
cupsdPauseListening();
cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to accept client connection - %s.",
strerror(errno));
free(con);
return;
}
/*
* Save the connected address and port number...
*/
addrlen = sizeof(con->clientaddr);
if (getsockname(httpGetFd(con->http), (struct sockaddr *)&con->clientaddr, &addrlen) || addrlen == 0)
con->clientaddr = lis->address;
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Server address is \"%s\".", httpAddrString(&con->clientaddr, name, sizeof(name)));
/*
* Check the number of clients on the same address...
*/
for (count = 0, tempcon = (cupsd_client_t *)cupsArrayFirst(Clients);
tempcon;
tempcon = (cupsd_client_t *)cupsArrayNext(Clients))
if (httpAddrEqual(httpGetAddress(tempcon->http), httpGetAddress(con->http)))
{
count ++;
if (count >= MaxClientsPerHost)
break;
}
if (count >= MaxClientsPerHost)
{
if ((time(NULL) - last_dos) >= 60)
{
last_dos = time(NULL);
cupsdLogMessage(CUPSD_LOG_WARN,
"Possible DoS attack - more than %d clients connecting "
"from %s.",
MaxClientsPerHost,
httpGetHostname(con->http, name, sizeof(name)));
}
httpClose(con->http);
free(con);
return;
}
/*
* Get the hostname or format the IP address as needed...
*/
if (HostNameLookups)
hostname = httpResolveHostname(con->http, NULL, 0);
else
hostname = httpGetHostname(con->http, NULL, 0);
if (hostname == NULL && HostNameLookups == 2)
{
/*
* Can't have an unresolved IP address with double-lookups enabled...
*/
httpClose(con->http);
cupsdLogClient(con, CUPSD_LOG_WARN,
"Name lookup failed - connection from %s closed!",
httpGetHostname(con->http, NULL, 0));
free(con);
return;
}
if (HostNameLookups == 2)
{
/*
* Do double lookups as needed...
*/
http_addrlist_t *addrlist, /* List of addresses */
*addr; /* Current address */
if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, NULL)) != NULL)
{
/*
* See if the hostname maps to the same IP address...
*/
for (addr = addrlist; addr; addr = addr->next)
if (httpAddrEqual(httpGetAddress(con->http), &(addr->addr)))
break;
}
else
addr = NULL;
httpAddrFreeList(addrlist);
if (!addr)
{
/*
* Can't have a hostname that doesn't resolve to the same IP address
* with double-lookups enabled...
*/
httpClose(con->http);
cupsdLogClient(con, CUPSD_LOG_WARN,
"IP lookup failed - connection from %s closed!",
httpGetHostname(con->http, NULL, 0));
free(con);
return;
}
}
#ifdef HAVE_TCPD_H
/*
* See if the connection is denied by TCP wrappers...
*/
request_init(&wrap_req, RQ_DAEMON, "cupsd", RQ_FILE, httpGetFd(con->http),
NULL);
fromhost(&wrap_req);
if (!hosts_access(&wrap_req))
{
httpClose(con->http);
cupsdLogClient(con, CUPSD_LOG_WARN,
"Connection from %s refused by /etc/hosts.allow and "
"/etc/hosts.deny rules.", httpGetHostname(con->http, NULL, 0));
free(con);
return;
}
#endif /* HAVE_TCPD_H */
#ifdef AF_LOCAL
if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
{
# ifdef __APPLE__
socklen_t peersize; /* Size of peer credentials */
pid_t peerpid; /* Peer process ID */
char peername[256]; /* Name of process */
peersize = sizeof(peerpid);
if (!getsockopt(httpGetFd(con->http), SOL_LOCAL, LOCAL_PEERPID, &peerpid,
&peersize))
{
if (!proc_name((int)peerpid, peername, sizeof(peername)))
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Accepted from %s (Domain ???[%d])",
httpGetHostname(con->http, NULL, 0), (int)peerpid);
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Accepted from %s (Domain %s[%d])",
httpGetHostname(con->http, NULL, 0), peername, (int)peerpid);
}
else
# endif /* __APPLE__ */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s (Domain)",
httpGetHostname(con->http, NULL, 0));
}
else
#endif /* AF_LOCAL */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s:%d (IPv%d)",
httpGetHostname(con->http, NULL, 0),
httpAddrPort(httpGetAddress(con->http)),
httpAddrFamily(httpGetAddress(con->http)) == AF_INET ? 4 : 6);
/*
* Get the local address the client connected to...
*/
addrlen = sizeof(temp);
if (getsockname(httpGetFd(con->http), (struct sockaddr *)&temp, &addrlen))
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to get local address - %s",
strerror(errno));
strlcpy(con->servername, "localhost", sizeof(con->servername));
con->serverport = LocalPort;
}
#ifdef AF_LOCAL
else if (httpAddrFamily(&temp) == AF_LOCAL)
{
strlcpy(con->servername, "localhost", sizeof(con->servername));
con->serverport = LocalPort;
}
#endif /* AF_LOCAL */
else
{
if (httpAddrLocalhost(&temp))
strlcpy(con->servername, "localhost", sizeof(con->servername));
else if (HostNameLookups)
httpAddrLookup(&temp, con->servername, sizeof(con->servername));
else
httpAddrString(&temp, con->servername, sizeof(con->servername));
con->serverport = httpAddrPort(&(lis->address));
}
/*
* Add the connection to the array of active clients...
*/
cupsArrayAdd(Clients, con);
/*
* Add the socket to the server select.
*/
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL,
con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
/*
* Temporarily suspend accept()'s until we lose a client...
*/
if (cupsArrayCount(Clients) == MaxClients)
cupsdPauseListening();
#ifdef HAVE_SSL
/*
* See if we are connecting on a secure port...
*/
if (lis->encryption == HTTP_ENCRYPTION_ALWAYS)
{
/*
* https connection; go secure...
*/
if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))
cupsdCloseClient(con);
}
else
con->auto_ssl = 1;
#endif /* HAVE_SSL */
}
/*
* 'cupsdCloseAllClients()' - Close all remote clients immediately.
*/
void
cupsdCloseAllClients(void)
{
cupsd_client_t *con; /* Current client */
cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients));
for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
con;
con = (cupsd_client_t *)cupsArrayNext(Clients))
if (cupsdCloseClient(con))
cupsdCloseClient(con);
}
/*
* 'cupsdCloseClient()' - Close a remote client.
*/
int /* O - 1 if partial close, 0 if fully closed */
cupsdCloseClient(cupsd_client_t *con) /* I - Client to close */
{
int partial; /* Do partial close for SSL? */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing connection.");
/*
* Flush pending writes before closing...
*/
httpFlushWrite(con->http);
partial = 0;
if (con->pipe_pid != 0)
{
/*
* Stop any CGI process...
*/
cupsdEndProcess(con->pipe_pid, 1);
con->pipe_pid = 0;
}
if (con->file >= 0)
{
cupsdRemoveSelect(con->file);
close(con->file);
con->file = -1;
}
/*
* Close the socket and clear the file from the input set for select()...
*/
if (httpGetFd(con->http) >= 0)
{
cupsArrayRemove(ActiveClients, con);
cupsdSetBusyState();
#ifdef HAVE_SSL
/*
* Shutdown encryption as needed...
*/
if (httpIsEncrypted(con->http))
partial = 1;
#endif /* HAVE_SSL */
if (partial)
{
/*
* Only do a partial close so that the encrypted client gets everything.
*/
httpShutdown(con->http);
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for socket close.");
}
else
{
/*
* Shut the socket down fully...
*/
cupsdRemoveSelect(httpGetFd(con->http));
httpClose(con->http);
con->http = NULL;
}
}
if (!partial)
{
/*
* Free memory...
*/
cupsdRemoveSelect(httpGetFd(con->http));
httpClose(con->http);
if (con->filename)
{
unlink(con->filename);
cupsdClearString(&con->filename);
}
cupsdClearString(&con->command);
cupsdClearString(&con->options);
cupsdClearString(&con->query_string);
if (con->request)
{
ippDelete(con->request);
con->request = NULL;
}
if (con->response)
{
ippDelete(con->response);
con->response = NULL;
}
if (con->language)
{
cupsLangFree(con->language);
con->language = NULL;
}
#ifdef HAVE_AUTHORIZATION_H
if (con->authref)
{
AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
con->authref = NULL;
}
#endif /* HAVE_AUTHORIZATION_H */
/*
* Re-enable new client connections if we are going back under the
* limit...
*/
if (cupsArrayCount(Clients) == MaxClients)
cupsdResumeListening();
/*
* Compact the list of clients as necessary...
*/
cupsArrayRemove(Clients, con);
free(con);
}
return (partial);
}
/*
* 'cupsdReadClient()' - Read data from a client.
*/
void
cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
{
char line[32768], /* Line from client... */
locale[64], /* Locale */
*ptr; /* Pointer into strings */
http_status_t status; /* Transfer status */
ipp_state_t ipp_state; /* State of IPP transfer */
int bytes; /* Number of bytes to POST */
char *filename; /* Name of file for GET/HEAD */
char buf[1024]; /* Buffer for real filename */
struct stat filestats; /* File information */
mime_type_t *type; /* MIME type of file */
cupsd_printer_t *p; /* Printer */
static unsigned request_id = 0; /* Request ID for temp files */
status = HTTP_STATUS_CONTINUE;
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdReadClient: error=%d, used=%d, state=%s, data_encoding=HTTP_ENCODING_%s, data_remaining=" CUPS_LLFMT ", request=%p(%s), file=%d", httpError(con->http), (int)httpGetReady(con->http), httpStateString(httpGetState(con->http)), httpIsChunked(con->http) ? "CHUNKED" : "LENGTH", CUPS_LLCAST httpGetRemaining(con->http), con->request, con->request ? ippStateString(ippGetState(con->request)) : "", con->file);
if (httpGetState(con->http) == HTTP_STATE_GET_SEND ||
httpGetState(con->http) == HTTP_STATE_POST_SEND ||
httpGetState(con->http) == HTTP_STATE_STATUS)
{
/*
* If we get called in the wrong state, then something went wrong with the
* connection and we need to shut it down...
*/
if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
{
/*
* Connection closed...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
cupsdCloseClient(con);
return;
}
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con->http)));
cupsdCloseClient(con);
return;
}
#ifdef HAVE_SSL
if (con->auto_ssl)
{
/*
* Automatically check for a SSL/TLS handshake...
*/
con->auto_ssl = 0;
if (recv(httpGetFd(con->http), buf, 1, MSG_PEEK) == 1 &&
(!buf[0] || !strchr("DGHOPT", buf[0])))
{
/*
* Encrypt this connection...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf[0] & 255);
if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))
cupsdCloseClient(con);
return;
}
}
#endif /* HAVE_SSL */
switch (httpGetState(con->http))
{
case HTTP_STATE_WAITING :
/*
* See if we've received a request line...
*/
con->operation = httpReadRequest(con->http, con->uri, sizeof(con->uri));
if (con->operation == HTTP_STATE_ERROR ||
con->operation == HTTP_STATE_UNKNOWN_METHOD ||
con->operation == HTTP_STATE_UNKNOWN_VERSION)
{
if (httpError(con->http))
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_WAITING Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_WAITING Closing on error: %s",
cupsLastErrorString());
cupsdCloseClient(con);
return;
}
/*
* Ignore blank request lines...
*/
if (con->operation == HTTP_STATE_WAITING)
break;
/*
* Clear other state variables...
*/
con->bytes = 0;
con->file = -1;
con->file_ready = 0;
con->pipe_pid = 0;
con->username[0] = '\0';
con->password[0] = '\0';
cupsdClearString(&con->command);
cupsdClearString(&con->options);
cupsdClearString(&con->query_string);
if (con->request)
{
ippDelete(con->request);
con->request = NULL;
}
if (con->response)
{
ippDelete(con->response);
con->response = NULL;
}
if (con->language)
{
cupsLangFree(con->language);
con->language = NULL;
}
#ifdef HAVE_GSSAPI
con->have_gss = 0;
con->gss_uid = 0;
#endif /* HAVE_GSSAPI */
/*
* Handle full URLs in the request line...
*/
if (strcmp(con->uri, "*"))
{
char scheme[HTTP_MAX_URI], /* Method/scheme */
userpass[HTTP_MAX_URI], /* Username:password */
hostname[HTTP_MAX_URI], /* Hostname */
resource[HTTP_MAX_URI]; /* Resource path */
int port; /* Port number */
/*
* Separate the URI into its components...
*/
if (httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,
scheme, sizeof(scheme),
userpass, sizeof(userpass),
hostname, sizeof(hostname), &port,
resource, sizeof(resource)) < HTTP_URI_STATUS_OK)
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
con->uri);
cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
/*
* Only allow URIs with the servername, localhost, or an IP
* address...
*/
if (strcmp(scheme, "file") &&
_cups_strcasecmp(hostname, ServerName) &&
_cups_strcasecmp(hostname, "localhost") &&
!cupsArrayFind(ServerAlias, hostname) &&
!isdigit(hostname[0]) && hostname[0] != '[')
{
/*
* Nope, we don't do proxies...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
con->uri);
cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
/*
* Copy the resource portion back into the URI; both resource and
* con->uri are HTTP_MAX_URI bytes in size...
*/
strlcpy(con->uri, resource, sizeof(con->uri));
}
/*
* Process the request...
*/
gettimeofday(&(con->start), NULL);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "%s %s HTTP/%d.%d",
httpStateString(con->operation) + 11, con->uri,
httpGetVersion(con->http) / 100,
httpGetVersion(con->http) % 100);
if (!cupsArrayFind(ActiveClients, con))
{
cupsArrayAdd(ActiveClients, con);
cupsdSetBusyState();
}
case HTTP_STATE_OPTIONS :
case HTTP_STATE_DELETE :
case HTTP_STATE_GET :
case HTTP_STATE_HEAD :
case HTTP_STATE_POST :
case HTTP_STATE_PUT :
case HTTP_STATE_TRACE :
/*
* Parse incoming parameters until the status changes...
*/
while ((status = httpUpdate(con->http)) == HTTP_STATUS_CONTINUE)
if (!httpGetReady(con->http))
break;
if (status != HTTP_STATUS_OK && status != HTTP_STATUS_CONTINUE)
{
if (httpError(con->http) && httpError(con->http) != EPIPE)
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing for error %d (%s) while reading headers.",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing on EOF while reading headers.");
cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
break;
default :
if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
{
/*
* Connection closed...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
cupsdCloseClient(con);
return;
}
break; /* Anti-compiler-warning-code */
}
/*
* Handle new transfers...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Read: status=%d", status);
if (status == HTTP_STATUS_OK)
{
if (httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE)[0])
{
/*
* Figure out the locale from the Accept-Language and Content-Type
* fields...
*/
if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
',')) != NULL)
*ptr = '\0';
if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
';')) != NULL)
*ptr = '\0';
if ((ptr = strstr(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
"charset=")) != NULL)
{
/*
* Combine language and charset, and trim any extra params in the
* content-type.
*/
snprintf(locale, sizeof(locale), "%s.%s",
httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE), ptr + 8);
if ((ptr = strchr(locale, ',')) != NULL)
*ptr = '\0';
}
else
snprintf(locale, sizeof(locale), "%s.UTF-8",
httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE));
con->language = cupsLangGet(locale);
}
else
con->language = cupsLangGet(DefaultLocale);
cupsdAuthorize(con);
if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
"Keep-Alive", 10) && KeepAlive)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_ON);
else if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
"close", 5))
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
if (!httpGetField(con->http, HTTP_FIELD_HOST)[0] &&
httpGetVersion(con->http) >= HTTP_VERSION_1_1)
{
/*
* HTTP/1.1 and higher require the "Host:" field...
*/
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Missing Host: field in request.");
cupsdCloseClient(con);
return;
}
}
else if (!valid_host(con))
{
/*
* Access to localhost must use "localhost" or the corresponding IPv4
* or IPv6 values in the Host: field.
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Request from \"%s\" using invalid Host: field \"%s\".",
httpGetHostname(con->http, NULL, 0), httpGetField(con->http, HTTP_FIELD_HOST));
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else if (con->operation == HTTP_STATE_OPTIONS)
{
/*
* Do OPTIONS command...
*/
if (con->best && con->best->type != CUPSD_AUTH_NONE)
{
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION), "Upgrade") && strstr(httpGetField(con->http, HTTP_FIELD_UPGRADE), "TLS/") != NULL && !httpIsEncrypted(con->http))
{
#ifdef HAVE_SSL
/*
* Do encryption stuff...
*/
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
{
cupsdCloseClient(con);
return;
}
#else
if (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
#endif /* HAVE_SSL */
}
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_ALLOW,
"GET, HEAD, OPTIONS, POST, PUT");
httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else if (!is_path_absolute(con->uri))
{
/*
* Protect against malicious users!
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Request for non-absolute resource \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
{
if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
"Upgrade") && !httpIsEncrypted(con->http))
{
#ifdef HAVE_SSL
/*
* Do encryption stuff...
*/
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL,
CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
{
cupsdCloseClient(con);
return;
}
#else
if (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
#endif /* HAVE_SSL */
}
if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_STATUS_OK)
{
cupsdSendError(con, status, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
if (httpGetExpect(con->http) &&
(con->operation == HTTP_STATE_POST || con->operation == HTTP_STATE_PUT))
{
if (httpGetExpect(con->http) == HTTP_STATUS_CONTINUE)
{
/*
* Send 100-continue header...
*/
if (httpWriteResponse(con->http, HTTP_STATUS_CONTINUE))
{
cupsdCloseClient(con);
return;
}
}
else
{
/*
* Send 417-expectation-failed header...
*/
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
cupsdSendError(con, HTTP_STATUS_EXPECTATION_FAILED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
}
switch (httpGetState(con->http))
{
case HTTP_STATE_GET_SEND :
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Processing GET %s", con->uri);
if ((!strncmp(con->uri, "/ppd/", 5) ||
!strncmp(con->uri, "/printers/", 10) ||
!strncmp(con->uri, "/classes/", 9)) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
{
/*
* Send PPD file - get the real printer name since printer
* names are not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
if (!strncmp(con->uri, "/ppd/", 5))
p = cupsdFindPrinter(con->uri + 5);
else if (!strncmp(con->uri, "/printers/", 10))
p = cupsdFindPrinter(con->uri + 10);
else
{
p = cupsdFindClass(con->uri + 9);
if (p)
{
int i; /* Looping var */
for (i = 0; i < p->num_printers; i ++)
{
if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
{
char ppdname[1024];/* PPD filename */
snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
ServerRoot, p->printers[i]->name);
if (!access(ppdname, 0))
{
p = p->printers[i];
break;
}
}
}
if (i >= p->num_printers)
p = NULL;
}
}
if (p)
{
snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
}
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
}
else if ((!strncmp(con->uri, "/icons/", 7) ||
!strncmp(con->uri, "/printers/", 10) ||
!strncmp(con->uri, "/classes/", 9)) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".png"))
{
/*
* Send icon file - get the real queue name since queue names are
* not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".png" */
if (!strncmp(con->uri, "/icons/", 7))
p = cupsdFindPrinter(con->uri + 7);
else if (!strncmp(con->uri, "/printers/", 10))
p = cupsdFindPrinter(con->uri + 10);
else
{
p = cupsdFindClass(con->uri + 9);
if (p)
{
int i; /* Looping var */
for (i = 0; i < p->num_printers; i ++)
{
if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
{
char ppdname[1024];/* PPD filename */
snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
ServerRoot, p->printers[i]->name);
if (!access(ppdname, 0))
{
p = p->printers[i];
break;
}
}
}
if (i >= p->num_printers)
p = NULL;
}
}
if (p)
snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
}
if ((!strncmp(con->uri, "/admin", 6) && strcmp(con->uri, "/admin/conf/cupsd.conf") && strncmp(con->uri, "/admin/log/", 11)) ||
!strncmp(con->uri, "/printers", 9) ||
!strncmp(con->uri, "/classes", 8) ||
!strncmp(con->uri, "/help", 5) ||
!strncmp(con->uri, "/jobs", 5))
{
if (!WebInterface)
{
/*
* Web interface is disabled. Show an appropriate message...
*/
if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* Send CGI output...
*/
if (!strncmp(con->uri, "/admin", 6))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
ServerBin);
cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
}
else if (!strncmp(con->uri, "/printers", 9))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
ServerBin);
if (con->uri[9] && con->uri[10])
cupsdSetString(&con->options, con->uri + 9);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/classes", 8))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
ServerBin);
if (con->uri[8] && con->uri[9])
cupsdSetString(&con->options, con->uri + 8);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/jobs", 5))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
else
{
cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
if (!cupsdSendCommand(con, con->command, con->options, 0))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
cupsdLogRequest(con, HTTP_STATUS_OK);
if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
}
else if (!strncmp(con->uri, "/admin/log/", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))
{
/*
* GET can only be done to configuration files directly under
* /admin/conf...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR, "Request for subdirectory \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else
{
/*
* Serve a file...
*/
if ((filename = get_file(con, &filestats, buf,
sizeof(buf))) == NULL)
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
type = mimeFileType(MimeDatabase, filename, NULL, NULL);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "filename=\"%s\", type=%s/%s", filename, type ? type->super : "", type ? type->type : "");
if (is_cgi(con, filename, &filestats, type))
{
/*
* Note: con->command and con->options were set by
* is_cgi()...
*/
if (!cupsdSendCommand(con, con->command, con->options, 0))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
cupsdLogRequest(con, HTTP_STATUS_OK);
if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
break;
}
if (!check_if_modified(con, &filestats))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
{
if (type == NULL)
strlcpy(line, "text/plain", sizeof(line));
else
snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
if (!write_file(con, HTTP_STATUS_OK, filename, line, &filestats))
{
cupsdCloseClient(con);
return;
}
}
}
break;
case HTTP_STATE_POST_RECV :
/*
* See if the POST request includes a Content-Length field, and if
* so check the length against any limits that are set...
*/
if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
MaxRequestSize > 0 &&
httpGetLength2(con->http) > MaxRequestSize)
{
/*
* Request too large...
*/
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else if (httpGetLength2(con->http) < 0)
{
/*
* Negative content lengths are invalid!
*/
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* See what kind of POST request this is; for IPP requests the
* content-type field will be "application/ipp"...
*/
if (!strcmp(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
"application/ipp"))
con->request = ippNew();
else if (!WebInterface)
{
/*
* Web interface is disabled. Show an appropriate message...
*/
if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else if ((!strncmp(con->uri, "/admin", 6) && strncmp(con->uri, "/admin/log/", 11)) ||
!strncmp(con->uri, "/printers", 9) ||
!strncmp(con->uri, "/classes", 8) ||
!strncmp(con->uri, "/help", 5) ||
!strncmp(con->uri, "/jobs", 5))
{
/*
* CGI request...
*/
if (!strncmp(con->uri, "/admin", 6))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
ServerBin);
cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
}
else if (!strncmp(con->uri, "/printers", 9))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
ServerBin);
if (con->uri[9] && con->uri[10])
cupsdSetString(&con->options, con->uri + 9);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/classes", 8))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
ServerBin);
if (con->uri[8] && con->uri[9])
cupsdSetString(&con->options, con->uri + 8);
else
cupsdSetString(&con->options, NULL);
}
else if (!strncmp(con->uri, "/jobs", 5))
{
cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
else
{
cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
ServerBin);
if (con->uri[5] && con->uri[6])
cupsdSetString(&con->options, con->uri + 5);
else
cupsdSetString(&con->options, NULL);
}
if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
}
else
{
/*
* POST to a file...
*/
if ((filename = get_file(con, &filestats, buf,
sizeof(buf))) == NULL)
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
type = mimeFileType(MimeDatabase, filename, NULL, NULL);
if (!is_cgi(con, filename, &filestats, type))
{
/*
* Only POST to CGI's...
*/
if (!cupsdSendError(con, HTTP_STATUS_UNAUTHORIZED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
break;
case HTTP_STATE_PUT_RECV :
/*
* Validate the resource name...
*/
if (strcmp(con->uri, "/admin/conf/cupsd.conf"))
{
/*
* PUT can only be done to the cupsd.conf file...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Disallowed PUT request for \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* See if the PUT request includes a Content-Length field, and if
* so check the length against any limits that are set...
*/
if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
MaxRequestSize > 0 &&
httpGetLength2(con->http) > MaxRequestSize)
{
/*
* Request too large...
*/
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
else if (httpGetLength2(con->http) < 0)
{
/*
* Negative content lengths are invalid!
*/
if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
break;
}
/*
* Open a temporary file to hold the request...
*/
cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
request_id ++);
con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
if (con->file < 0)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to create request file \"%s\": %s",
con->filename, strerror(errno));
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
fchmod(con->file, 0640);
fchown(con->file, RunUser, Group);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
break;
case HTTP_STATE_DELETE :
case HTTP_STATE_TRACE :
cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
case HTTP_STATE_HEAD :
if (!strncmp(con->uri, "/printers/", 10) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
{
/*
* Send PPD file - get the real printer name since printer
* names are not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
break;
}
}
else if (!strncmp(con->uri, "/printers/", 10) &&
!strcmp(con->uri + strlen(con->uri) - 4, ".png"))
{
/*
* Send PNG file - get the real printer name since printer
* names are not case sensitive but filenames can be...
*/
con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
else
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
break;
}
}
else if (!WebInterface)
{
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_OK);
break;
}
if ((!strncmp(con->uri, "/admin", 6) && strcmp(con->uri, "/admin/conf/cupsd.conf") && strncmp(con->uri, "/admin/log/", 11)) ||
!strncmp(con->uri, "/printers", 9) ||
!strncmp(con->uri, "/classes", 8) ||
!strncmp(con->uri, "/help", 5) ||
!strncmp(con->uri, "/jobs", 5))
{
/*
* CGI output...
*/
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_OK, "text/html", CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_OK);
}
else if (!strncmp(con->uri, "/admin/log/", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))
{
/*
* HEAD can only be done to configuration files under
* /admin/conf...
*/
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Request for subdirectory \"%s\".", con->uri);
if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_FORBIDDEN);
break;
}
else if ((filename = get_file(con, &filestats, buf,
sizeof(buf))) == NULL)
{
httpClearFields(con->http);
if (!cupsdSendHeader(con, HTTP_STATUS_NOT_FOUND, "text/html",
CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
}
else if (!check_if_modified(con, &filestats))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_NOT_MODIFIED);
}
else
{
/*
* Serve a file...
*/
type = mimeFileType(MimeDatabase, filename, NULL, NULL);
if (type == NULL)
strlcpy(line, "text/plain", sizeof(line));
else
snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
httpGetDateString(filestats.st_mtime));
httpSetLength(con->http, (size_t)filestats.st_size);
if (!cupsdSendHeader(con, HTTP_STATUS_OK, line, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
cupsdLogRequest(con, HTTP_STATUS_OK);
}
break;
default :
break; /* Anti-compiler-warning-code */
}
}
}
/*
* Handle any incoming data...
*/
switch (httpGetState(con->http))
{
case HTTP_STATE_PUT_RECV :
do
{
if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
{
if (httpError(con->http) && httpError(con->http) != EPIPE)
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_PUT_RECV Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_PUT_RECV Closing on EOF.");
cupsdCloseClient(con);
return;
}
else if (bytes > 0)
{
con->bytes += bytes;
if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)
{
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
if (write(con->file, line, (size_t)bytes) < bytes)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to write %d bytes to \"%s\": %s", bytes,
con->filename, strerror(errno));
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
else if (httpGetState(con->http) == HTTP_STATE_PUT_RECV)
{
cupsdCloseClient(con);
return;
}
}
while (httpGetState(con->http) == HTTP_STATE_PUT_RECV && httpGetReady(con->http));
if (httpGetState(con->http) == HTTP_STATE_STATUS)
{
/*
* End of file, see how big it is...
*/
fstat(con->file, &filestats);
close(con->file);
con->file = -1;
if (filestats.st_size > MaxRequestSize &&
MaxRequestSize > 0)
{
/*
* Request is too big; remove it and send an error...
*/
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
/*
* Install the configuration file...
*/
status = install_cupsd_conf(con);
/*
* Return the status to the client...
*/
if (!cupsdSendError(con, status, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
break;
case HTTP_STATE_POST_RECV :
do
{
if (con->request && con->file < 0)
{
/*
* Grab any request data from the connection...
*/
if (!httpWait(con->http, 0))
return;
if ((ipp_state = ippRead(con->http, con->request)) == IPP_STATE_ERROR)
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "IPP read error: %s",
cupsLastErrorString());
cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
else if (ipp_state != IPP_STATE_DATA)
{
if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
{
cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
cupsdCloseClient(con);
return;
}
if (httpGetReady(con->http))
continue;
break;
}
else
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "%d.%d %s %d",
con->request->request.op.version[0],
con->request->request.op.version[1],
ippOpString(con->request->request.op.operation_id),
con->request->request.op.request_id);
con->bytes += (off_t)ippLength(con->request);
}
}
if (con->file < 0 && httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
/*
* Create a file as needed for the request data...
*/
cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
request_id ++);
con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
if (con->file < 0)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to create request file \"%s\": %s",
con->filename, strerror(errno));
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
fchmod(con->file, 0640);
fchown(con->file, RunUser, Group);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
}
if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
if (!httpWait(con->http, 0))
return;
else if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
{
if (httpError(con->http) && httpError(con->http) != EPIPE)
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_POST_SEND Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
else
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"HTTP_STATE_POST_SEND Closing on EOF.");
cupsdCloseClient(con);
return;
}
else if (bytes > 0)
{
con->bytes += bytes;
if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)
{
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
if (write(con->file, line, (size_t)bytes) < bytes)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to write %d bytes to \"%s\": %s",
bytes, con->filename, strerror(errno));
close(con->file);
con->file = -1;
unlink(con->filename);
cupsdClearString(&con->filename);
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE,
CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
else if (httpGetState(con->http) == HTTP_STATE_POST_RECV)
return;
else if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing on unexpected state %s.",
httpStateString(httpGetState(con->http)));
cupsdCloseClient(con);
return;
}
}
}
while (httpGetState(con->http) == HTTP_STATE_POST_RECV && httpGetReady(con->http));
if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
{
if (con->file >= 0)
{
fstat(con->file, &filestats);
close(con->file);
con->file = -1;
if (filestats.st_size > MaxRequestSize &&
MaxRequestSize > 0)
{
/*
* Request is too big; remove it and send an error...
*/
unlink(con->filename);
cupsdClearString(&con->filename);
if (con->request)
{
/*
* Delete any IPP request data...
*/
ippDelete(con->request);
con->request = NULL;
}
if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else if (filestats.st_size == 0)
{
/*
* Don't allow empty file...
*/
unlink(con->filename);
cupsdClearString(&con->filename);
}
if (con->command)
{
if (!cupsdSendCommand(con, con->command, con->options, 0))
{
if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
cupsdLogRequest(con, HTTP_STATUS_OK);
}
}
if (con->request)
{
cupsdProcessIPPRequest(con);
if (con->filename)
{
unlink(con->filename);
cupsdClearString(&con->filename);
}
return;
}
}
break;
default :
break; /* Anti-compiler-warning-code */
}
if (httpGetState(con->http) == HTTP_STATE_WAITING)
{
if (!httpGetKeepAlive(con->http))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing because Keep-Alive is disabled.");
cupsdCloseClient(con);
}
else
{
cupsArrayRemove(ActiveClients, con);
cupsdSetBusyState();
}
}
}
/*
* 'cupsdSendCommand()' - Send output from a command via HTTP.
*/
int /* O - 1 on success, 0 on failure */
cupsdSendCommand(
cupsd_client_t *con, /* I - Client connection */
char *command, /* I - Command to run */
char *options, /* I - Command-line options */
int root) /* I - Run as root? */
{
int fd; /* Standard input file descriptor */
if (con->filename)
{
fd = open(con->filename, O_RDONLY);
if (fd < 0)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to open \"%s\" for reading: %s",
con->filename ? con->filename : "/dev/null",
strerror(errno));
return (0);
}
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
}
else
fd = -1;
con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
con->pipe_status = HTTP_STATUS_OK;
httpClearFields(con->http);
if (fd >= 0)
close(fd);
cupsdLogClient(con, CUPSD_LOG_INFO, "Started \"%s\" (pid=%d, file=%d)",
command, con->pipe_pid, con->file);
if (con->pipe_pid == 0)
return (0);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
con->sent_header = 0;
con->file_ready = 0;
con->got_fields = 0;
con->header_used = 0;
return (1);
}
/*
* 'cupsdSendError()' - Send an error message via HTTP.
*/
int /* O - 1 if successful, 0 otherwise */
cupsdSendError(cupsd_client_t *con, /* I - Connection */
http_status_t code, /* I - Error code */
int auth_type)/* I - Authentication type */
{
char location[HTTP_MAX_VALUE]; /* Location field */
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdSendError code=%d, auth_type=%d", code, auth_type);
#ifdef HAVE_SSL
/*
* Force client to upgrade for authentication if that is how the
* server is configured...
*/
if (code == HTTP_STATUS_UNAUTHORIZED &&
DefaultEncryption == HTTP_ENCRYPTION_REQUIRED &&
_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost") &&
!httpIsEncrypted(con->http))
{
code = HTTP_STATUS_UPGRADE_REQUIRED;
}
#endif /* HAVE_SSL */
/*
* Put the request in the access_log file...
*/
cupsdLogRequest(con, code);
/*
* To work around bugs in some proxies, don't use Keep-Alive for some
* error messages...
*
* Kerberos authentication doesn't work without Keep-Alive, so
* never disable it in that case.
*/
strlcpy(location, httpGetField(con->http, HTTP_FIELD_LOCATION), sizeof(location));
httpClearFields(con->http);
httpSetField(con->http, HTTP_FIELD_LOCATION, location);
if (code >= HTTP_STATUS_BAD_REQUEST && con->type != CUPSD_AUTH_NEGOTIATE)
httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
if (httpGetVersion(con->http) >= HTTP_VERSION_1_1 &&
httpGetKeepAlive(con->http) == HTTP_KEEPALIVE_OFF)
httpSetField(con->http, HTTP_FIELD_CONNECTION, "close");
if (code >= HTTP_STATUS_BAD_REQUEST)
{
/*
* Send a human-readable error message.
*/
char message[4096], /* Message for user */
urltext[1024], /* URL redirection text */
redirect[1024]; /* Redirection link */
const char *text; /* Status-specific text */
redirect[0] = '\0';
if (code == HTTP_STATUS_UNAUTHORIZED)
text = _cupsLangString(con->language,
_("Enter your username and password or the "
"root username and password to access this "
"page. If you are using Kerberos authentication, "
"make sure you have a valid Kerberos ticket."));
else if (code == HTTP_STATUS_UPGRADE_REQUIRED)
{
text = urltext;
snprintf(urltext, sizeof(urltext),
_cupsLangString(con->language,
_("You must access this page using the URL "
"<A HREF=\"https://%s:%d%s\">"
"https://%s:%d%s</A>.")),
con->servername, con->serverport, con->uri,
con->servername, con->serverport, con->uri);
snprintf(redirect, sizeof(redirect),
"<META HTTP-EQUIV=\"Refresh\" "
"CONTENT=\"3;URL=https://%s:%d%s\">\n",
con->servername, con->serverport, con->uri);
}
else if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
text = _cupsLangString(con->language,
_("The web interface is currently disabled. Run "
"\"cupsctl WebInterface=yes\" to enable it."));
else
text = "";
snprintf(message, sizeof(message),
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
"\"http://www.w3.org/TR/html4/loose.dtd\">\n"
"<HTML>\n"
"<HEAD>\n"
"\t<META HTTP-EQUIV=\"Content-Type\" "
"CONTENT=\"text/html; charset=utf-8\">\n"
"\t<TITLE>%s - " CUPS_SVERSION "</TITLE>\n"
"\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
"HREF=\"/cups.css\">\n"
"%s"
"</HEAD>\n"
"<BODY>\n"
"<H1>%s</H1>\n"
"<P>%s</P>\n"
"</BODY>\n"
"</HTML>\n",
_httpStatus(con->language, code), redirect,
_httpStatus(con->language, code), text);
/*
* Send an error message back to the client. If the error code is a
* 400 or 500 series, make sure the message contains some text, too!
*/
size_t length = strlen(message); /* Length of message */
httpSetLength(con->http, length);
if (!cupsdSendHeader(con, code, "text/html", auth_type))
return (0);
if (httpWrite2(con->http, message, length) < 0)
return (0);
if (httpFlushWrite(con->http) < 0)
return (0);
}
else
{
httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
if (!cupsdSendHeader(con, code, NULL, auth_type))
return (0);
}
return (1);
}
/*
* 'cupsdSendHeader()' - Send an HTTP request.
*/
int /* O - 1 on success, 0 on failure */
cupsdSendHeader(
cupsd_client_t *con, /* I - Client to send to */
http_status_t code, /* I - HTTP status code */
char *type, /* I - MIME type of document */
int auth_type) /* I - Type of authentication */
{
char auth_str[1024]; /* Authorization string */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code, type, auth_type);
/*
* Send the HTTP status header...
*/
if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
{
/*
* Treat our special "web interface is disabled" status as "200 OK" for web
* browsers.
*/
code = HTTP_STATUS_OK;
}
if (ServerHeader)
httpSetField(con->http, HTTP_FIELD_SERVER, ServerHeader);
if (code == HTTP_STATUS_METHOD_NOT_ALLOWED)
httpSetField(con->http, HTTP_FIELD_ALLOW, "GET, HEAD, OPTIONS, POST, PUT");
if (code == HTTP_STATUS_UNAUTHORIZED)
{
if (auth_type == CUPSD_AUTH_NONE)
{
if (!con->best || con->best->type <= CUPSD_AUTH_NONE)
auth_type = cupsdDefaultAuthType();
else
auth_type = con->best->type;
}
auth_str[0] = '\0';
if (auth_type == CUPSD_AUTH_BASIC)
strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
#ifdef HAVE_GSSAPI
else if (auth_type == CUPSD_AUTH_NEGOTIATE)
{
# ifdef AF_LOCAL
if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
else
# endif /* AF_LOCAL */
strlcpy(auth_str, "Negotiate", sizeof(auth_str));
}
#endif /* HAVE_GSSAPI */
if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE &&
!_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost"))
{
/*
* Add a "trc" (try root certification) parameter for local non-Kerberos
* requests when the request requires system group membership - then the
* client knows the root certificate can/should be used.
*
* Also, for macOS we also look for @AUTHKEY and add an "authkey"
* parameter as needed...
*/
char *name, /* Current user name */
*auth_key; /* Auth key buffer */
size_t auth_size; /* Size of remaining buffer */
auth_key = auth_str + strlen(auth_str);
auth_size = sizeof(auth_str) - (size_t)(auth_key - auth_str);
for (name = (char *)cupsArrayFirst(con->best->names);
name;
name = (char *)cupsArrayNext(con->best->names))
{
#ifdef HAVE_AUTHORIZATION_H
if (!_cups_strncasecmp(name, "@AUTHKEY(", 9))
{
snprintf(auth_key, auth_size, ", authkey=\"%s\"", name + 9);
/* end parenthesis is stripped in conf.c */
break;
}
else
#endif /* HAVE_AUTHORIZATION_H */
if (!_cups_strcasecmp(name, "@SYSTEM"))
{
#ifdef HAVE_AUTHORIZATION_H
if (SystemGroupAuthKey)
snprintf(auth_key, auth_size,
", authkey=\"%s\"",
SystemGroupAuthKey);
else
#else
strlcpy(auth_key, ", trc=\"y\"", auth_size);
#endif /* HAVE_AUTHORIZATION_H */
break;
}
}
}
if (auth_str[0])
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "WWW-Authenticate: %s", auth_str);
httpSetField(con->http, HTTP_FIELD_WWW_AUTHENTICATE, auth_str);
}
}
if (con->language && strcmp(con->language->language, "C"))
httpSetField(con->http, HTTP_FIELD_CONTENT_LANGUAGE, con->language->language);
if (type)
{
if (!strcmp(type, "text/html"))
httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, "text/html; charset=utf-8");
else
httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, type);
}
return (!httpWriteResponse(con->http, code));
}
/*
* 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
*/
void
cupsdUpdateCGI(void)
{
char *ptr, /* Pointer to end of line in buffer */
message[1024]; /* Pointer to message text */
int loglevel; /* Log level for message */
while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
message, sizeof(message))) != NULL)
{
if (loglevel == CUPSD_LOG_INFO)
cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
if (!strchr(CGIStatusBuffer->buffer, '\n'))
break;
}
if (ptr == NULL && !CGIStatusBuffer->bufused)
{
/*
* Fatal error on pipe - should never happen!
*/
cupsdLogMessage(CUPSD_LOG_CRIT,
"cupsdUpdateCGI: error reading from CGI error pipe - %s",
strerror(errno));
}
}
/*
* 'cupsdWriteClient()' - Write data to a client as needed.
*/
void
cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
{
int bytes, /* Number of bytes written */
field_col; /* Current column */
char *bufptr, /* Pointer into buffer */
*bufend; /* Pointer to end of buffer */
ipp_state_t ipp_state; /* IPP state value */
cupsdLogClient(con, CUPSD_LOG_DEBUG, "con->http=%p", con->http);
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"cupsdWriteClient "
"error=%d, "
"used=%d, "
"state=%s, "
"data_encoding=HTTP_ENCODING_%s, "
"data_remaining=" CUPS_LLFMT ", "
"response=%p(%s), "
"pipe_pid=%d, "
"file=%d",
httpError(con->http), (int)httpGetReady(con->http),
httpStateString(httpGetState(con->http)),
httpIsChunked(con->http) ? "CHUNKED" : "LENGTH",
CUPS_LLCAST httpGetLength2(con->http),
con->response,
con->response ? ippStateString(ippGetState(con->request)) : "",
con->pipe_pid, con->file);
if (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
httpGetState(con->http) != HTTP_STATE_POST_SEND)
{
/*
* If we get called in the wrong state, then something went wrong with the
* connection and we need to shut it down...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP write state %s.",
httpStateString(httpGetState(con->http)));
cupsdCloseClient(con);
return;
}
if (con->pipe_pid)
{
/*
* Make sure we select on the CGI output...
*/
cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
if (!con->file_ready)
{
/*
* Try again later when there is CGI output available...
*/
cupsdRemoveSelect(httpGetFd(con->http));
return;
}
con->file_ready = 0;
}
bytes = (ssize_t)(sizeof(con->header) - (size_t)con->header_used);
if (!con->pipe_pid && bytes > (ssize_t)httpGetRemaining(con->http))
{
/*
* Limit GET bytes to original size of file (STR #3265)...
*/
bytes = (ssize_t)httpGetRemaining(con->http);
}
if (con->response && con->response->state != IPP_STATE_DATA)
{
size_t wused = httpGetPending(con->http); /* Previous write buffer use */
do
{
/*
* Write a single attribute or the IPP message header...
*/
ipp_state = ippWrite(con->http, con->response);
/*
* If the write buffer has been flushed, stop buffering up attributes...
*/
if (httpGetPending(con->http) <= wused)
break;
}
while (ipp_state != IPP_STATE_DATA && ipp_state != IPP_STATE_ERROR);
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Writing IPP response, ipp_state=%s, old "
"wused=" CUPS_LLFMT ", new wused=" CUPS_LLFMT,
ippStateString(ipp_state),
CUPS_LLCAST wused, CUPS_LLCAST httpGetPending(con->http));
if (httpGetPending(con->http) > 0)
httpFlushWrite(con->http);
bytes = ipp_state != IPP_STATE_ERROR &&
(con->file >= 0 || ipp_state != IPP_STATE_DATA);
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT,
(int)bytes, httpGetState(con->http),
CUPS_LLCAST httpGetLength2(con->http));
}
else if ((bytes = read(con->file, con->header + con->header_used, (size_t)bytes)) > 0)
{
con->header_used += bytes;
if (con->pipe_pid && !con->got_fields)
{
/*
* Inspect the data for Content-Type and other fields.
*/
for (bufptr = con->header, bufend = con->header + con->header_used,
field_col = 0;
!con->got_fields && bufptr < bufend;
bufptr ++)
{
if (*bufptr == '\n')
{
/*
* Send line to client...
*/
if (bufptr > con->header && bufptr[-1] == '\r')
bufptr[-1] = '\0';
*bufptr++ = '\0';
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Script header: %s", con->header);
if (!con->sent_header)
{
/*
* Handle redirection and CGI status codes...
*/
http_field_t field; /* HTTP field */
char *value = strchr(con->header, ':');
/* Value of field */
if (value)
{
*value++ = '\0';
while (isspace(*value & 255))
value ++;
}
field = httpFieldValue(con->header);
if (field != HTTP_FIELD_UNKNOWN && value)
{
httpSetField(con->http, field, value);
if (field == HTTP_FIELD_LOCATION)
{
con->pipe_status = HTTP_STATUS_SEE_OTHER;
con->sent_header = 2;
}
else
con->sent_header = 1;
}
else if (!_cups_strcasecmp(con->header, "Status") && value)
{
con->pipe_status = (http_status_t)atoi(value);
con->sent_header = 2;
}
else if (!_cups_strcasecmp(con->header, "Set-Cookie") && value)
{
httpSetCookie(con->http, value);
con->sent_header = 1;
}
}
/*
* Update buffer...
*/
con->header_used -= bufptr - con->header;
if (con->header_used > 0)
memmove(con->header, bufptr, (size_t)con->header_used);
bufptr = con->header - 1;
/*
* See if the line was empty...
*/
if (field_col == 0)
{
con->got_fields = 1;
if (httpGetVersion(con->http) == HTTP_VERSION_1_1 &&
!httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0])
httpSetLength(con->http, 0);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending status %d for CGI.", con->pipe_status);
if (con->pipe_status == HTTP_STATUS_OK)
{
if (!cupsdSendHeader(con, con->pipe_status, NULL, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
else
{
if (!cupsdSendError(con, con->pipe_status, CUPSD_AUTH_NONE))
{
cupsdCloseClient(con);
return;
}
}
}
else
field_col = 0;
}
else if (*bufptr != '\r')
field_col ++;
}
if (!con->got_fields)
return;
}
if (con->header_used > 0)
{
if (httpWrite2(con->http, con->header, (size_t)con->header_used) < 0)
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
cupsdCloseClient(con);
return;
}
if (httpIsChunked(con->http))
httpFlushWrite(con->http);
con->bytes += con->header_used;
if (httpGetState(con->http) == HTTP_STATE_WAITING)
bytes = 0;
else
bytes = con->header_used;
con->header_used = 0;
}
}
if (bytes <= 0 ||
(httpGetState(con->http) != HTTP_STATE_GET_SEND &&
httpGetState(con->http) != HTTP_STATE_POST_SEND))
{
if (!con->sent_header && con->pipe_pid)
cupsdSendError(con, HTTP_STATUS_SERVER_ERROR, CUPSD_AUTH_NONE);
else
{
cupsdLogRequest(con, HTTP_STATUS_OK);
if (httpIsChunked(con->http) && (!con->pipe_pid || con->sent_header > 0))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending 0-length chunk.");
if (httpWrite2(con->http, "", 0) < 0)
{
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
httpError(con->http), strerror(httpError(con->http)));
cupsdCloseClient(con);
return;
}
}
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Flushing write buffer.");
httpFlushWrite(con->http);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "New state is %s", httpStateString(httpGetState(con->http)));
}
cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
if (con->file >= 0)
{
cupsdRemoveSelect(con->file);
if (con->pipe_pid)
cupsdEndProcess(con->pipe_pid, 0);
close(con->file);
con->file = -1;
con->pipe_pid = 0;
}
if (con->filename)
{
unlink(con->filename);
cupsdClearString(&con->filename);
}
if (con->request)
{
ippDelete(con->request);
con->request = NULL;
}
if (con->response)
{
ippDelete(con->response);
con->response = NULL;
}
cupsdClearString(&con->command);
cupsdClearString(&con->options);
cupsdClearString(&con->query_string);
if (!httpGetKeepAlive(con->http))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG,
"Closing because Keep-Alive is disabled.");
cupsdCloseClient(con);
return;
}
else
{
cupsArrayRemove(ActiveClients, con);
cupsdSetBusyState();
}
}
}
/*
* 'check_if_modified()' - Decode an "If-Modified-Since" line.
*/
static int /* O - 1 if modified since */
check_if_modified(
cupsd_client_t *con, /* I - Client connection */
struct stat *filestats) /* I - File information */
{
const char *ptr; /* Pointer into field */
time_t date; /* Time/date value */
off_t size; /* Size/length value */
size = 0;
date = 0;
ptr = httpGetField(con->http, HTTP_FIELD_IF_MODIFIED_SINCE);
if (*ptr == '\0')
return (1);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "check_if_modified: filestats=%p(" CUPS_LLFMT ", %d)) If-Modified-Since=\"%s\"", filestats, CUPS_LLCAST filestats->st_size, (int)filestats->st_mtime, ptr);
while (*ptr != '\0')
{
while (isspace(*ptr) || *ptr == ';')
ptr ++;
if (_cups_strncasecmp(ptr, "length=", 7) == 0)
{
ptr += 7;
size = strtoll(ptr, NULL, 10);
while (isdigit(*ptr))
ptr ++;
}
else if (isalpha(*ptr))
{
date = httpGetDateTime(ptr);
while (*ptr != '\0' && *ptr != ';')
ptr ++;
}
else
ptr ++;
}
return ((size != filestats->st_size && size != 0) ||
(date < filestats->st_mtime && date != 0) ||
(size == 0 && date == 0));
}
/*
* 'compare_clients()' - Compare two client connections.
*/
static int /* O - Result of comparison */
compare_clients(cupsd_client_t *a, /* I - First client */
cupsd_client_t *b, /* I - Second client */
void *data) /* I - User data (not used) */
{
(void)data;
if (a == b)
return (0);
else if (a < b)
return (-1);
else
return (1);
}
#ifdef HAVE_SSL
/*
* 'cupsd_start_tls()' - Start encryption on a connection.
*/
static int /* O - 0 on success, -1 on error */
cupsd_start_tls(cupsd_client_t *con, /* I - Client connection */
http_encryption_t e) /* I - Encryption mode */
{
if (httpEncryption(con->http, e))
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to encrypt connection: %s",
cupsLastErrorString());
return (-1);
}
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Connection now encrypted.");
return (0);
}
#endif /* HAVE_SSL */
/*
* 'get_file()' - Get a filename and state info.
*/
static char * /* O - Real filename */
get_file(cupsd_client_t *con, /* I - Client connection */
struct stat *filestats, /* O - File information */
char *filename, /* IO - Filename buffer */
size_t len) /* I - Buffer length */
{
int status; /* Status of filesystem calls */
char *ptr; /* Pointer info filename */
size_t plen; /* Remaining length after pointer */
char language[7], /* Language subdirectory, if any */
dest[1024]; /* Destination name */
int perm_check = 1; /* Do permissions check? */
/*
* Figure out the real filename...
*/
language[0] = '\0';
if (!strncmp(con->uri, "/ppd/", 5) && !strchr(con->uri + 5, '/'))
{
strlcpy(dest, con->uri + 5, sizeof(dest));
ptr = dest + strlen(dest) - 4;
if (ptr <= dest || strcmp(ptr, ".ppd"))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Disallowed path \"%s\".", con->uri);
return (NULL);
}
*ptr = '\0';
if (!cupsdFindPrinter(dest))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "No printer \"%s\" found.", dest);
return (NULL);
}
snprintf(filename, len, "%s%s", ServerRoot, con->uri);
perm_check = 0;
}
else if (!strncmp(con->uri, "/icons/", 7) && !strchr(con->uri + 7, '/'))
{
strlcpy(dest, con->uri + 7, sizeof(dest));
ptr = dest + strlen(dest) - 4;
if (ptr <= dest || strcmp(ptr, ".png"))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Disallowed path \"%s\".", con->uri);
return (NULL);
}
*ptr = '\0';
if (!cupsdFindDest(dest))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "No printer \"%s\" found.", dest);
return (NULL);
}
snprintf(filename, len, "%s/%s.png", CacheDir, dest);
if (access(filename, F_OK) < 0)
snprintf(filename, len, "%s/images/generic.png", DocumentRoot);
perm_check = 0;
}
else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
else if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
{
strlcpy(filename, ConfigurationFile, len);
perm_check = 0;
}
else if (!strncmp(con->uri, "/admin/log/", 11))
{
if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
strlcpy(filename, AccessLog, len);
else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
strlcpy(filename, ErrorLog, len);
else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
strlcpy(filename, PageLog, len);
else
return (NULL);
perm_check = 0;
}
else if (con->language)
{
snprintf(language, sizeof(language), "/%s", con->language->language);
snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
}
else
snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
/*
* Grab the status for this language; if there isn't a language-specific file
* then fallback to the default one...
*/
if ((status = lstat(filename, filestats)) != 0 && language[0] &&
strncmp(con->uri, "/icons/", 7) &&
strncmp(con->uri, "/ppd/", 5) &&
strncmp(con->uri, "/rss/", 5) &&
strncmp(con->uri, "/admin/conf/", 12) &&
strncmp(con->uri, "/admin/log/", 11))
{
/*
* Drop the country code...
*/
language[3] = '\0';
snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
if ((status = lstat(filename, filestats)) != 0)
{
/*
* Drop the language prefix and try the root directory...
*/
language[0] = '\0';
snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
status = lstat(filename, filestats);
}
}
/*
* If we've found a symlink, 404 the sucker to avoid disclosing information.
*/
if (!status && S_ISLNK(filestats->st_mode))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Symlinks such as \"%s\" are not allowed.", filename);
return (NULL);
}
/*
* Similarly, if the file/directory does not have world read permissions, do
* not allow access...
*/
if (!status && perm_check && !(filestats->st_mode & S_IROTH))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Files/directories such as \"%s\" must be world-readable.", filename);
return (NULL);
}
/*
* If we've found a directory, get the index.html file instead...
*/
if (!status && S_ISDIR(filestats->st_mode))
{
/*
* Make sure the URI ends with a slash...
*/
if (con->uri[strlen(con->uri) - 1] != '/')
strlcat(con->uri, "/", sizeof(con->uri));
/*
* Find the directory index file, trying every language...
*/
do
{
if (status && language[0])
{
/*
* Try a different language subset...
*/
if (language[3])
language[0] = '\0'; /* Strip country code */
else
language[0] = '\0'; /* Strip language */
}
/*
* Look for the index file...
*/
snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
if ((ptr = strchr(filename, '?')) != NULL)
*ptr = '\0';
ptr = filename + strlen(filename);
plen = len - (size_t)(ptr - filename);
strlcpy(ptr, "index.html", plen);
status = lstat(filename, filestats);
#ifdef HAVE_JAVA
if (status)
{
strlcpy(ptr, "index.class", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_JAVA */
#ifdef HAVE_PERL
if (status)
{
strlcpy(ptr, "index.pl", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_PERL */
#ifdef HAVE_PHP
if (status)
{
strlcpy(ptr, "index.php", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_PHP */
#ifdef HAVE_PYTHON
if (status)
{
strlcpy(ptr, "index.pyc", plen);
status = lstat(filename, filestats);
}
if (status)
{
strlcpy(ptr, "index.py", plen);
status = lstat(filename, filestats);
}
#endif /* HAVE_PYTHON */
}
while (status && language[0]);
/*
* If we've found a symlink, 404 the sucker to avoid disclosing information.
*/
if (!status && S_ISLNK(filestats->st_mode))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Symlinks such as \"%s\" are not allowed.", filename);
return (NULL);
}
/*
* Similarly, if the file/directory does not have world read permissions, do
* not allow access...
*/
if (!status && perm_check && !(filestats->st_mode & S_IROTH))
{
cupsdLogClient(con, CUPSD_LOG_INFO, "Files/directories such as \"%s\" must be world-readable.", filename);
return (NULL);
}
}
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT ", returning \"%s\".", filestats, filename, CUPS_LLCAST len, status ? "(null)" : filename);
if (status)
return (NULL);
else
return (filename);
}
/*
* 'install_cupsd_conf()' - Install a configuration file.
*/
static http_status_t /* O - Status */
install_cupsd_conf(cupsd_client_t *con) /* I - Connection */
{
char filename[1024]; /* Configuration filename */
cups_file_t *in, /* Input file */
*out; /* Output file */
char buffer[16384]; /* Copy buffer */
ssize_t bytes; /* Number of bytes */
/*
* Open the request file...
*/
if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
{
cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to open request file \"%s\": %s",
con->filename, strerror(errno));
goto server_error;
}
/*
* Open the new config file...
*/
if ((out = cupsdCreateConfFile(ConfigurationFile, ConfigFilePerm)) == NULL)
{
cupsFileClose(in);
goto server_error;
}
cupsdLogClient(con, CUPSD_LOG_INFO, "Installing config file \"%s\"...",
ConfigurationFile);
/*
* Copy from the request to the new config file...
*/
while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
if (cupsFileWrite(out, buffer, (size_t)bytes) < bytes)
{
cupsdLogClient(con, CUPSD_LOG_ERROR,
"Unable to copy to config file \"%s\": %s",
ConfigurationFile, strerror(errno));
cupsFileClose(in);
cupsFileClose(out);
snprintf(filename, sizeof(filename), "%s.N", ConfigurationFile);
cupsdUnlinkOrRemoveFile(filename);
goto server_error;
}
/*
* Close the files...
*/
cupsFileClose(in);
if (cupsdCloseCreatedConfFile(out, ConfigurationFile))
goto server_error;
/*
* Remove the request file...
*/
cupsdUnlinkOrRemoveFile(con->filename);
cupsdClearString(&con->filename);
/*
* Set the NeedReload flag...
*/
NeedReload = RELOAD_CUPSD;
ReloadTime = time(NULL);
/*
* Return that the file was created successfully...
*/
return (HTTP_STATUS_CREATED);
/*
* Common exit for errors...
*/
server_error:
cupsdUnlinkOrRemoveFile(con->filename);
cupsdClearString(&con->filename);
return (HTTP_STATUS_SERVER_ERROR);
}
/*
* 'is_cgi()' - Is the resource a CGI script/program?
*/
static int /* O - 1 = CGI, 0 = file */
is_cgi(cupsd_client_t *con, /* I - Client connection */
const char *filename, /* I - Real filename */
struct stat *filestats, /* I - File information */
mime_type_t *type) /* I - MIME type */
{
const char *options; /* Options on URL */
/*
* Get the options, if any...
*/
if ((options = strchr(con->uri, '?')) != NULL)
{
options ++;
cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
}
/*
* Check for known types...
*/
if (!type || _cups_strcasecmp(type->super, "application"))
{
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename, filestats, type ? type->super : "unknown", type ? type->type : "unknown");
return (0);
}
if (!_cups_strcasecmp(type->type, "x-httpd-cgi") &&
(filestats->st_mode & 0111))
{
/*
* "application/x-httpd-cgi" is a CGI script.
*/
cupsdSetString(&con->command, filename);
if (options)
cupsdSetStringf(&con->options, " %s", options);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#ifdef HAVE_JAVA
else if (!_cups_strcasecmp(type->type, "x-httpd-java"))
{
/*
* "application/x-httpd-java" is a Java servlet.
*/
cupsdSetString(&con->command, CUPS_JAVA);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_JAVA */
#ifdef HAVE_PERL
else if (!_cups_strcasecmp(type->type, "x-httpd-perl"))
{
/*
* "application/x-httpd-perl" is a Perl page.
*/
cupsdSetString(&con->command, CUPS_PERL);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_PERL */
#ifdef HAVE_PHP
else if (!_cups_strcasecmp(type->type, "x-httpd-php"))
{
/*
* "application/x-httpd-php" is a PHP page.
*/
cupsdSetString(&con->command, CUPS_PHP);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_PHP */
#ifdef HAVE_PYTHON
else if (!_cups_strcasecmp(type->type, "x-httpd-python"))
{
/*
* "application/x-httpd-python" is a Python page.
*/
cupsdSetString(&con->command, CUPS_PYTHON);
if (options)
cupsdSetStringf(&con->options, " %s %s", filename, options);
else
cupsdSetStringf(&con->options, " %s", filename);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
return (1);
}
#endif /* HAVE_PYTHON */
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename, filestats, type->super, type->type);
return (0);
}
/*
* 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
*/
static int /* O - 0 if relative, 1 if absolute */
is_path_absolute(const char *path) /* I - Input path */
{
/*
* Check for a leading slash...
*/
if (path[0] != '/')
return (0);
/*
* Check for "<" or quotes in the path and reject since this is probably
* someone trying to inject HTML...
*/
if (strchr(path, '<') != NULL || strchr(path, '\"') != NULL || strchr(path, '\'') != NULL)
return (0);
/*
* Check for "/.." in the path...
*/
while ((path = strstr(path, "/..")) != NULL)
{
if (!path[3] || path[3] == '/')
return (0);
path ++;
}
/*
* If we haven't found any relative paths, return 1 indicating an
* absolute path...
*/
return (1);
}
/*
* 'pipe_command()' - Pipe the output of a command to the remote client.
*/
static int /* O - Process ID */
pipe_command(cupsd_client_t *con, /* I - Client connection */
int infile, /* I - Standard input for command */
int *outfile, /* O - Standard output for command */
char *command, /* I - Command to run */
char *options, /* I - Options for command */
int root) /* I - Run as root? */
{
int i; /* Looping var */
int pid; /* Process ID */
char *commptr, /* Command string pointer */
commch; /* Command string character */
char *uriptr; /* URI string pointer */
int fds[2]; /* Pipe FDs */
int argc; /* Number of arguments */
int envc; /* Number of environment variables */
char argbuf[10240], /* Argument buffer */
*argv[100], /* Argument strings */
*envp[MAX_ENV + 20]; /* Environment variables */
char auth_type[256], /* AUTH_TYPE environment variable */
content_length[1024], /* CONTENT_LENGTH environment variable */
content_type[1024], /* CONTENT_TYPE environment variable */
http_cookie[32768], /* HTTP_COOKIE environment variable */
http_referer[1024], /* HTTP_REFERER environment variable */
http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
lang[1024], /* LANG environment variable */
path_info[1024], /* PATH_INFO environment variable */
remote_addr[1024], /* REMOTE_ADDR environment variable */
remote_host[1024], /* REMOTE_HOST environment variable */
remote_user[1024], /* REMOTE_USER environment variable */
script_filename[1024], /* SCRIPT_FILENAME environment variable */
script_name[1024], /* SCRIPT_NAME environment variable */
server_name[1024], /* SERVER_NAME environment variable */
server_port[1024]; /* SERVER_PORT environment variable */
ipp_attribute_t *attr; /* attributes-natural-language attribute */
/*
* Parse a copy of the options string, which is of the form:
*
* argument+argument+argument
* ?argument+argument+argument
* param=value¶m=value
* ?param=value¶m=value
* /name?argument+argument+argument
* /name?param=value¶m=value
*
* If the string contains an "=" character after the initial name,
* then we treat it as a HTTP GET form request and make a copy of
* the remaining string for the environment variable.
*
* The string is always parsed out as command-line arguments, to
* be consistent with Apache...
*/
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile, outfile, command, options ? options : "(null)", root);
argv[0] = command;
if (options)
strlcpy(argbuf, options, sizeof(argbuf));
else
argbuf[0] = '\0';
if (argbuf[0] == '/')
{
/*
* Found some trailing path information, set PATH_INFO...
*/
if ((commptr = strchr(argbuf, '?')) == NULL)
commptr = argbuf + strlen(argbuf);
commch = *commptr;
*commptr = '\0';
snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
*commptr = commch;
}
else
{
commptr = argbuf;
path_info[0] = '\0';
if (*commptr == ' ')
commptr ++;
}
if (*commptr == '?' && con->operation == HTTP_STATE_GET && !con->query_string)
{
commptr ++;
cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
}
argc = 1;
if (*commptr)
{
argv[argc ++] = commptr;
for (; *commptr && argc < 99; commptr ++)
{
/*
* Break arguments whenever we see a + or space...
*/
if (*commptr == ' ' || *commptr == '+')
{
while (*commptr == ' ' || *commptr == '+')
*commptr++ = '\0';
/*
* If we don't have a blank string, save it as another argument...
*/
if (*commptr)
{
argv[argc] = commptr;
argc ++;
}
else
break;
}
else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
isxdigit(commptr[2] & 255))
{
/*
* Convert the %xx notation to the individual character.
*/
if (commptr[1] >= '0' && commptr[1] <= '9')
*commptr = (char)((commptr[1] - '0') << 4);
else
*commptr = (char)((tolower(commptr[1]) - 'a' + 10) << 4);
if (commptr[2] >= '0' && commptr[2] <= '9')
*commptr |= commptr[2] - '0';
else
*commptr |= tolower(commptr[2]) - 'a' + 10;
_cups_strcpy(commptr + 1, commptr + 3);
/*
* Check for a %00 and break if that is the case...
*/
if (!*commptr)
break;
}
}
}
argv[argc] = NULL;
/*
* Setup the environment variables as needed...
*/
if (con->username[0])
{
snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
httpGetField(con->http, HTTP_FIELD_AUTHORIZATION));
if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
*uriptr = '\0';
}
else
auth_type[0] = '\0';
if (con->request &&
(attr = ippFindAttribute(con->request, "attributes-natural-language",
IPP_TAG_LANGUAGE)) != NULL)
{
switch (strlen(attr->values[0].string.text))
{
default :
/*
* This is an unknown or badly formatted language code; use
* the POSIX locale...
*/
strlcpy(lang, "LANG=C", sizeof(lang));
break;
case 2 :
/*
* Just the language code (ll)...
*/
snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
attr->values[0].string.text);
break;
case 5 :
/*
* Language and country code (ll-cc)...
*/
snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
attr->values[0].string.text[0],
attr->values[0].string.text[1],
toupper(attr->values[0].string.text[3] & 255),
toupper(attr->values[0].string.text[4] & 255));
break;
}
}
else if (con->language)
snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
else
strlcpy(lang, "LANG=C", sizeof(lang));
strlcpy(remote_addr, "REMOTE_ADDR=", sizeof(remote_addr));
httpAddrString(httpGetAddress(con->http), remote_addr + 12,
sizeof(remote_addr) - 12);
snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
httpGetHostname(con->http, NULL, 0));
snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
if ((uriptr = strchr(script_name, '?')) != NULL)
*uriptr = '\0';
snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
DocumentRoot, script_name + 12);
snprintf(server_port, sizeof(server_port), "SERVER_PORT=%d", con->serverport);
if (httpGetField(con->http, HTTP_FIELD_HOST)[0])
{
char *nameptr; /* Pointer to ":port" */
snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
httpGetField(con->http, HTTP_FIELD_HOST));
if ((nameptr = strrchr(server_name, ':')) != NULL && !strchr(nameptr, ']'))
*nameptr = '\0'; /* Strip trailing ":port" */
}
else
snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
con->servername);
envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
if (auth_type[0])
envp[envc ++] = auth_type;
envp[envc ++] = lang;
envp[envc ++] = "REDIRECT_STATUS=1";
envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
envp[envc ++] = server_name;
envp[envc ++] = server_port;
envp[envc ++] = remote_addr;
envp[envc ++] = remote_host;
envp[envc ++] = script_name;
envp[envc ++] = script_filename;
if (path_info[0])
envp[envc ++] = path_info;
if (con->username[0])
{
snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
envp[envc ++] = remote_user;
}
if (httpGetVersion(con->http) == HTTP_VERSION_1_1)
envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
else if (httpGetVersion(con->http) == HTTP_VERSION_1_0)
envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
else
envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
if (httpGetCookie(con->http))
{
snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
httpGetCookie(con->http));
envp[envc ++] = http_cookie;
}
if (httpGetField(con->http, HTTP_FIELD_USER_AGENT)[0])
{
snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
httpGetField(con->http, HTTP_FIELD_USER_AGENT));
envp[envc ++] = http_user_agent;
}
if (httpGetField(con->http, HTTP_FIELD_REFERER)[0])
{
snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
httpGetField(con->http, HTTP_FIELD_REFERER));
envp[envc ++] = http_referer;
}
if (con->operation == HTTP_STATE_GET)
{
envp[envc ++] = "REQUEST_METHOD=GET";
if (con->query_string)
{
/*
* Add GET form variables after ?...
*/
envp[envc ++] = con->query_string;
}
else
envp[envc ++] = "QUERY_STRING=";
}
else
{
sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
CUPS_LLCAST con->bytes);
snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE));
envp[envc ++] = "REQUEST_METHOD=POST";
envp[envc ++] = content_length;
envp[envc ++] = content_type;
}
/*
* Tell the CGI if we are using encryption...
*/
if (httpIsEncrypted(con->http))
envp[envc ++] = "HTTPS=ON";
/*
* Terminate the environment array...
*/
envp[envc] = NULL;
if (LogLevel >= CUPSD_LOG_DEBUG)
{
for (i = 0; i < argc; i ++)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[CGI] argv[%d] = \"%s\"", i, argv[i]);
for (i = 0; i < envc; i ++)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"[CGI] envp[%d] = \"%s\"", i, envp[i]);
}
/*
* Create a pipe for the output...
*/
if (cupsdOpenPipe(fds))
{
cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to create pipe for %s - %s",
argv[0], strerror(errno));
return (0);
}
/*
* Then execute the command...
*/
if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
-1, -1, root, DefaultProfile, NULL, &pid) < 0)
{
/*
* Error - can't fork!
*/
cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to start %s - %s", argv[0],
strerror(errno));
cupsdClosePipe(fds);
pid = 0;
}
else
{
/*
* Fork successful - return the PID...
*/
if (con->username[0])
cupsdAddCert(pid, con->username, con->type);
cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] Started %s (PID %d)", command, pid);
*outfile = fds[0];
close(fds[1]);
}
return (pid);
}
/*
* 'valid_host()' - Is the Host: field valid?
*/
static int /* O - 1 if valid, 0 if not */
valid_host(cupsd_client_t *con) /* I - Client connection */
{
cupsd_alias_t *a; /* Current alias */
cupsd_netif_t *netif; /* Current network interface */
const char *end; /* End character */
char *ptr; /* Pointer into host value */
/*
* Copy the Host: header for later use...
*/
strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),
sizeof(con->clientname));
if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))
{
*ptr++ = '\0';
con->clientport = atoi(ptr);
}
else
con->clientport = con->serverport;
/*
* Then validate...
*/
if (httpAddrLocalhost(httpGetAddress(con->http)))
{
/*
* Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
* addresses when accessing CUPS via the loopback interface...
*/
return (!_cups_strcasecmp(con->clientname, "localhost") ||
!_cups_strcasecmp(con->clientname, "localhost.") ||
!strcmp(con->clientname, "127.0.0.1") ||
!strcmp(con->clientname, "[::1]"));
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
/*
* Check if the hostname is something.local (Bonjour); if so, allow it.
*/
if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&
!end[1])
{
/*
* "." on end, work back to second-to-last "."...
*/
for (end --; end > con->clientname && *end != '.'; end --);
}
if (end && (!_cups_strcasecmp(end, ".local") ||
!_cups_strcasecmp(end, ".local.")))
return (1);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check if the hostname is an IP address...
*/
if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')
{
/*
* Possible IPv4/IPv6 address...
*/
http_addrlist_t *addrlist; /* List of addresses */
if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)
{
/*
* Good IPv4/IPv6 address...
*/
httpAddrFreeList(addrlist);
return (1);
}
}
/*
* Check for (alias) name matches...
*/
for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
a;
a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
{
/*
* "ServerAlias *" allows all host values through...
*/
if (!strcmp(a->name, "*"))
return (1);
if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + a->namelen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Check for interface hostname matches...
*/
for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
netif;
netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
{
if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))
{
/*
* Prefix matches; check the character at the end - it must be "." or nul.
*/
end = con->clientname + netif->hostlen;
if (!*end || (*end == '.' && !end[1]))
return (1);
}
}
return (0);
}
/*
* 'write_file()' - Send a file via HTTP.
*/
static int /* O - 0 on failure, 1 on success */
write_file(cupsd_client_t *con, /* I - Client connection */
http_status_t code, /* I - HTTP status */
char *filename, /* I - Filename */
char *type, /* I - File type */
struct stat *filestats) /* O - File information */
{
con->file = open(filename, O_RDONLY);
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code, filename, con->file, type ? type : "(null)", filestats);
if (con->file < 0)
return (0);
fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
con->pipe_pid = 0;
con->sent_header = 1;
httpClearFields(con->http);
httpSetLength(con->http, (size_t)filestats->st_size);
httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
httpGetDateString(filestats->st_mtime));
if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
return (0);
cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending file.");
return (1);
}
/*
* 'write_pipe()' - Flag that data is available on the CGI pipe.
*/
static void
write_pipe(cupsd_client_t *con) /* I - Client connection */
{
cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d.", con->file);
con->file_ready = 1;
cupsdRemoveSelect(con->file);
cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
cupsdLogClient(con, CUPSD_LOG_DEBUG, "CGI data ready to be sent.");
}
| ./CrossVul/dataset_final_sorted/CWE-290/c/good_3010_0 |
crossvul-cpp_data_bad_4121_0 | /*
* cotp.c
*
* ISO 8073 Connection Oriented Transport Protocol over TCP (RFC1006)
*
* Partial implementation of the ISO 8073 COTP (ISO TP0) protocol for MMS.
*
* Copyright 2013-2018 Michael Zillgith
*
* This file is part of libIEC61850.
*
* libIEC61850 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.
*
* libIEC61850 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 libIEC61850. If not, see <http://www.gnu.org/licenses/>.
*
* See COPYING file for the complete license text.
*/
#include "libiec61850_platform_includes.h"
#include "stack_config.h"
#include "cotp.h"
#include "byte_buffer.h"
#include "buffer_chain.h"
#define TPKT_RFC1006_HEADER_SIZE 4
#define COTP_DATA_HEADER_SIZE 3
#ifdef CONFIG_COTP_MAX_TPDU_SIZE
#define COTP_MAX_TPDU_SIZE CONFIG_COTP_MAX_TPDU_SIZE
#else
#define COTP_MAX_TPDU_SIZE 8192
#endif
#ifndef DEBUG_COTP
#define DEBUG_COTP 0
#endif
static bool
addPayloadToBuffer(CotpConnection* self, uint8_t* buffer, int payloadLength);
static uint16_t
getUint16(uint8_t* buffer)
{
return (buffer[0] * 0x100) + buffer[1];
}
static uint8_t
getUint8(uint8_t* buffer)
{
return buffer[0];
}
static void
writeOptions(CotpConnection* self)
{
/* max size = 11 byte */
uint8_t* buffer = self->writeBuffer->buffer;
int bufPos = self->writeBuffer->size;
if (self->options.tpduSize != 0) {
if (DEBUG_COTP)
printf("COTP: send TPDU size: %i\n", CotpConnection_getTpduSize(self));
buffer[bufPos++] = 0xc0;
buffer[bufPos++] = 0x01;
buffer[bufPos++] = self->options.tpduSize;
}
if (self->options.tSelDst.size != 0) {
buffer[bufPos++] = 0xc2;
buffer[bufPos++] = (uint8_t) self->options.tSelDst.size;
int i;
for (i = 0; i < self->options.tSelDst.size; i++)
buffer[bufPos++] = (uint8_t) self->options.tSelDst.value[i];
}
if (self->options.tSelSrc.size != 0) {
buffer[bufPos++] = 0xc1;
buffer[bufPos++] = (uint8_t) self->options.tSelSrc.size;
int i;
for (i = 0; i < self->options.tSelSrc.size; i++)
buffer[bufPos++] = (uint8_t) self->options.tSelSrc.value[i];
}
self->writeBuffer->size = bufPos;
}
static int
getOptionsLength(CotpConnection* self)
{
int optionsLength = 0;
if (self->options.tpduSize != 0)
optionsLength += 3;
if (self->options.tSelDst.size != 0)
optionsLength += (2 + self->options.tSelDst.size);
if (self->options.tSelSrc.size != 0)
optionsLength += (2 + self->options.tSelSrc.size);
return optionsLength;
}
static void
writeStaticConnectResponseHeader(CotpConnection* self, int optionsLength)
{
/* always same size (7) and same position in buffer */
uint8_t* buffer = self->writeBuffer->buffer;
buffer[4] = 6 + optionsLength;
buffer[5] = 0xd0;
buffer[6] = (uint8_t) (self->remoteRef / 0x100);
buffer[7] = (uint8_t) (self->remoteRef & 0xff);
buffer[8] = (uint8_t) (self->localRef / 0x100);
buffer[9] = (uint8_t) (self->localRef & 0xff);
buffer[10] = (uint8_t) (self->protocolClass);
self->writeBuffer->size = 11;
}
static void
writeRfc1006Header(CotpConnection* self, int len)
{
uint8_t* buffer = self->writeBuffer->buffer;
buffer[0] = 0x03;
buffer[1] = 0x00;
buffer[2] = (uint8_t) (len / 0x100);
buffer[3] = (uint8_t) (len & 0xff);
self->writeBuffer->size = 4;
}
static void
writeDataTpduHeader(CotpConnection* self, int isLastUnit)
{
/* always 3 byte starting from byte 5 in buffer */
uint8_t* buffer = self->writeBuffer->buffer;
buffer[4] = 0x02;
buffer[5] = 0xf0;
if (isLastUnit)
buffer[6] = 0x80;
else
buffer[6] = 0x00;
self->writeBuffer->size = 7;
}
static int
writeToSocket(CotpConnection* self, uint8_t* buf, int size)
{
#if (CONFIG_MMS_SUPPORT_TLS == 1)
if (self->tlsSocket)
return TLSSocket_write(self->tlsSocket, buf, size);
else
return Socket_write(self->socket, buf, size);
#else
return Socket_write(self->socket, buf, size);
#endif
}
static bool
sendBuffer(CotpConnection* self)
{
int remainingSize = ByteBuffer_getSize(self->writeBuffer);
uint8_t* buffer = ByteBuffer_getBuffer(self->writeBuffer);
bool retVal = false;
do {
int sentBytes = writeToSocket(self, buffer, remainingSize);
if (sentBytes == -1)
goto exit_function;
buffer += sentBytes;
remainingSize -= sentBytes;
} while (remainingSize > 0);
retVal = true;
ByteBuffer_setSize(self->writeBuffer, 0);
exit_function:
return retVal;
}
CotpIndication
CotpConnection_sendDataMessage(CotpConnection* self, BufferChain payload)
{
CotpIndication retValue = COTP_OK;
int fragments = 1;
int fragmentPayloadSize = CotpConnection_getTpduSize(self) - COTP_DATA_HEADER_SIZE;
if (payload->length > fragmentPayloadSize) { /* Check if segmentation is required? */
fragments = payload->length / fragmentPayloadSize;
if ((payload->length % fragmentPayloadSize) != 0)
fragments += 1;
}
int currentBufPos = 0;
int currentLimit;
int lastUnit;
BufferChain currentChain = payload;
int currentChainIndex = 0;
if (DEBUG_COTP)
printf("\nCOTP: nextBufferPart: len:%i partLen:%i\n", currentChain->length, currentChain->partLength);
uint8_t* buffer = self->writeBuffer->buffer;
while (fragments > 0) {
if (fragments > 1) {
currentLimit = currentBufPos + fragmentPayloadSize;
lastUnit = 0;
}
else {
currentLimit = payload->length;
lastUnit = 1;
}
writeRfc1006Header(self, 7 + (currentLimit - currentBufPos));
writeDataTpduHeader(self, lastUnit);
int bufPos = 7;
int i;
for (i = currentBufPos; i < currentLimit; i++) {
if (currentChainIndex >= currentChain->partLength) {
currentChain = currentChain->nextPart;
if (DEBUG_COTP)
printf("\nCOTP: nextBufferPart: len:%i partLen:%i\n", currentChain->length, currentChain->partLength);
currentChainIndex = 0;
}
buffer[bufPos++] = currentChain->buffer[currentChainIndex];
currentChainIndex++;
currentBufPos++;
}
self->writeBuffer->size = bufPos;
if (DEBUG_COTP)
printf("COTP: Send COTP fragment %i bufpos: %i\n", fragments, currentBufPos);
if (!sendBuffer(self)) {
retValue = COTP_ERROR;
if (DEBUG_COTP)
printf("COTP: sending message failed!\n");
goto exit_function;
}
fragments--;
}
exit_function:
if (DEBUG_COTP)
printf("COTP: message transmission finished (fragments=%i, return=%i)\n", fragments, retValue);
return retValue;
}
static void
allocateWriteBuffer(CotpConnection* self)
{
if (self->writeBuffer == NULL )
self->writeBuffer = ByteBuffer_create(NULL,
CotpConnection_getTpduSize(self) + TPKT_RFC1006_HEADER_SIZE);
}
/* client side */
CotpIndication
CotpConnection_sendConnectionRequestMessage(CotpConnection* self, IsoConnectionParameters isoParameters)
{
allocateWriteBuffer(self);
self->options.tSelDst = isoParameters->remoteTSelector;
self->options.tSelSrc = isoParameters->localTSelector;
int cotpRequestSize = getOptionsLength(self) + 6;
int conRequestSize = cotpRequestSize + 5;
if(self->writeBuffer->maxSize < conRequestSize)
return COTP_ERROR;
uint8_t* buffer = self->writeBuffer->buffer;
writeRfc1006Header(self, conRequestSize);
/* LI */
buffer[4] = (uint8_t) cotpRequestSize;
/* TPDU CODE */
buffer[5] = 0xe0;
/* DST REF */
buffer[6] = 0x00;
buffer[7] = 0x00;
/* SRC REF */
buffer[8] = (uint8_t) (self->localRef / 0x100);
buffer[9] = (uint8_t) (self->localRef & 0xff);
/* Class */
buffer[10] = 0x00;
self->writeBuffer->size = 11;
writeOptions(self);
if (sendBuffer(self))
return COTP_OK;
else
return COTP_ERROR;
}
CotpIndication
CotpConnection_sendConnectionResponseMessage(CotpConnection* self)
{
allocateWriteBuffer(self);
int optionsLength = getOptionsLength(self);
int messageLength = 11 + optionsLength;
writeRfc1006Header(self, messageLength);
writeStaticConnectResponseHeader(self, optionsLength);
writeOptions(self);
if (sendBuffer(self))
return COTP_OK;
else
return COTP_ERROR;
}
static bool
parseOptions(CotpConnection* self, uint8_t* buffer, int bufLen)
{
int bufPos = 0;
while (bufPos < bufLen) {
uint8_t optionType = buffer[bufPos++];
uint8_t optionLen = buffer[bufPos++];
if (optionLen > (bufLen - bufPos)) {
if (DEBUG_COTP)
printf("COTP: option to long optionLen:%i bufPos:%i bufLen:%i\n", optionLen, bufPos, bufLen);
goto cpo_error;
}
if (DEBUG_COTP)
printf("COTP: option: %02x len: %02x\n", optionType, optionLen);
switch (optionType) {
case 0xc0:
if (optionLen == 1) {
int requestedTpduSize = (1 << buffer[bufPos++]);
CotpConnection_setTpduSize(self, requestedTpduSize);
if (DEBUG_COTP)
printf("COTP: requested TPDU size: %i\n", requestedTpduSize);
}
else
goto cpo_error;
break;
case 0xc1: /* remote T-selector */
if (optionLen < 5) {
self->options.tSelSrc.size = optionLen;
int i;
for (i = 0; i < optionLen; i++)
self->options.tSelSrc.value[i] = buffer[bufPos++];
}
else
goto cpo_error;
break;
case 0xc2: /* local T-selector */
if (optionLen < 5) {
self->options.tSelDst.size = optionLen;
int i;
for (i = 0; i < optionLen; i++)
self->options.tSelDst.value[i] = buffer[bufPos++];
}
else
goto cpo_error;
break;
case 0xc6: /* additional option selection */
if (optionLen == 1)
bufPos++; /* ignore value */
else
goto cpo_error;
break;
default:
if (DEBUG_COTP)
printf("COTP: Unknown option %02x\n", optionType);
bufPos += optionLen; /* ignore value */
break;
}
}
return true;
cpo_error:
if (DEBUG_COTP)
printf("COTP: cotp_parse_options: error parsing options!\n");
return false;
}
void
CotpConnection_init(CotpConnection* self, Socket socket,
ByteBuffer* payloadBuffer, ByteBuffer* readBuffer, ByteBuffer* writeBuffer)
{
self->state = 0;
self->socket = socket;
#if (CONFIG_MMS_SUPPORT_TLS == 1)
self->tlsSocket = NULL;
#endif
self->remoteRef = -1;
self->localRef = 1;
self->protocolClass = -1;
self->options.tpduSize = 0;
TSelector tsel;
tsel.size = 2;
tsel.value[0] = 0;
tsel.value[1] = 1;
self->options.tSelSrc = tsel;
self->options.tSelDst = tsel;
self->payload = payloadBuffer;
CotpConnection_resetPayload(self);
/* default TPDU size is maximum size */
CotpConnection_setTpduSize(self, COTP_MAX_TPDU_SIZE);
self->writeBuffer = writeBuffer;
self->readBuffer = readBuffer;
self->packetSize = 0;
}
int /* in byte */
CotpConnection_getTpduSize(CotpConnection* self)
{
return (1 << self->options.tpduSize);
}
void
CotpConnection_setTpduSize(CotpConnection* self, int tpduSize /* in byte */)
{
int newTpduSize = 1;
if (tpduSize > COTP_MAX_TPDU_SIZE)
tpduSize = COTP_MAX_TPDU_SIZE;
while ((1 << newTpduSize) < tpduSize)
newTpduSize++;
if ((1 << newTpduSize) > tpduSize)
newTpduSize--;
self->options.tpduSize = newTpduSize;
}
ByteBuffer*
CotpConnection_getPayload(CotpConnection* self)
{
return self->payload;
}
int
CotpConnection_getRemoteRef(CotpConnection* self)
{
return self->remoteRef;
}
int
CotpConnection_getLocalRef(CotpConnection* self)
{
return self->localRef;
}
/*
CR TPDU (from RFC 0905):
1 2 3 4 5 6 7 8 p p+1...end
+--+------+---------+---------+---+---+------+-------+---------+
|LI|CR CDT| DST - REF |SRC-REF|CLASS |VARIAB.|USER |
| |1110 |0000 0000|0000 0000| | |OPTION|PART |DATA |
+--+------+---------+---------+---+---+------+-------+---------+
*/
static bool
parseConnectRequestTpdu(CotpConnection* self, uint8_t* buffer, uint8_t len)
{
if (len < 6)
return false;
self->remoteRef = getUint16(buffer + 2);
self->protocolClass = getUint8(buffer + 4);
return parseOptions(self, buffer + 5, len - 6);
}
static bool
parseConnectConfirmTpdu(CotpConnection* self, uint8_t* buffer, uint8_t len)
{
if (len < 6)
return false;
self->remoteRef = getUint16(buffer);
self->protocolClass = getUint8(buffer + 4);
return parseOptions(self, buffer + 5, len - 6);
}
static bool
parseDataTpdu(CotpConnection* self, uint8_t* buffer, uint8_t len)
{
if (len != 2)
return false;
uint8_t flowControl = getUint8(buffer);
if (flowControl & 0x80)
self->isLastDataUnit = true;
else
self->isLastDataUnit = false;
return true;
}
static bool
addPayloadToBuffer(CotpConnection* self, uint8_t* buffer, int payloadLength)
{
if (payloadLength < 1) {
if (DEBUG_COTP)
printf("COTP: missing payload\n");
return false;
}
if (DEBUG_COTP)
printf("COTP: add to payload buffer (cur size: %i, len: %i)\n", self->payload->size, payloadLength);
if ((self->payload->size + payloadLength) > self->payload->maxSize)
return false;
memcpy(self->payload->buffer + self->payload->size, buffer, payloadLength);
self->payload->size += payloadLength;
return true;
}
static CotpIndication
parseCotpMessage(CotpConnection* self)
{
uint8_t* buffer = self->readBuffer->buffer + 4;
int tpduLength = self->readBuffer->size - 4;
uint8_t len;
uint8_t tpduType;
len = buffer[0];
if (len > tpduLength) {
if (DEBUG_COTP)
printf("COTP: parseCotpMessage: len=%d tpduLength=%d\n", len, tpduLength);
return COTP_ERROR;
}
tpduType = buffer[1];
switch (tpduType) {
case 0xe0:
if (parseConnectRequestTpdu(self, buffer + 2, len))
return COTP_CONNECT_INDICATION;
else
return COTP_ERROR;
case 0xd0:
if (parseConnectConfirmTpdu(self, buffer + 2, len))
return COTP_CONNECT_INDICATION;
else
return COTP_ERROR;
case 0xf0:
if (parseDataTpdu(self, buffer + 2, len)) {
if (addPayloadToBuffer(self, buffer + 3, tpduLength - 3) != 1)
return COTP_ERROR;
if (self->isLastDataUnit)
return COTP_DATA_INDICATION;
else
return COTP_MORE_FRAGMENTS_FOLLOW;
}
else
return COTP_ERROR;
default:
return COTP_ERROR;
}
}
CotpIndication
CotpConnection_parseIncomingMessage(CotpConnection* self)
{
CotpIndication indication = parseCotpMessage(self);
self->readBuffer->size = 0;
self->packetSize = 0;
return indication;
}
void
CotpConnection_resetPayload(CotpConnection* self)
{
self->payload->size = 0;
}
static int
readFromSocket(CotpConnection* self, uint8_t* buf, int size)
{
#if (CONFIG_MMS_SUPPORT_TLS == 1)
if (self->tlsSocket)
return TLSSocket_read(self->tlsSocket, buf, size);
else
return Socket_read(self->socket, buf, size);
#else
return Socket_read(self->socket, buf, size);
#endif
}
TpktState
CotpConnection_readToTpktBuffer(CotpConnection* self)
{
uint8_t* buffer = self->readBuffer->buffer;
int bufferSize = self->readBuffer->maxSize;
int bufPos = self->readBuffer->size;
assert (bufferSize > 4);
int readBytes;
if (bufPos < 4) {
readBytes = readFromSocket(self, buffer + bufPos, 4 - bufPos);
if (readBytes < 0)
goto exit_closed;
if (DEBUG_COTP) {
if (readBytes > 0)
printf("TPKT: read %i bytes from socket\n", readBytes);
}
bufPos += readBytes;
if (bufPos == 4) {
if ((buffer[0] == 3) && (buffer[1] == 0)) {
self->packetSize = (buffer[2] * 0x100) + buffer[3];
if (DEBUG_COTP)
printf("TPKT: header complete (msg size = %i)\n", self->packetSize);
if (self->packetSize > bufferSize) {
if (DEBUG_COTP) printf("TPKT: packet too large\n");
goto exit_error;
}
}
else {
if (DEBUG_COTP) printf("TPKT: failed to decode TPKT header.\n");
goto exit_error;
}
}
else
goto exit_waiting;
}
readBytes = readFromSocket(self, buffer + bufPos, self->packetSize - bufPos);
if (readBytes < 0)
goto exit_closed;
bufPos += readBytes;
if (bufPos < self->packetSize)
goto exit_waiting;
if (DEBUG_COTP) printf("TPKT: message complete (size = %i)\n", self->packetSize);
self->readBuffer->size = bufPos;
return TPKT_PACKET_COMPLETE;
exit_closed:
if (DEBUG_COTP) printf("TPKT: socket closed or socket error\n");
return TPKT_ERROR;
exit_error:
if (DEBUG_COTP) printf("TPKT: Error parsing message\n");
return TPKT_ERROR;
exit_waiting:
if (DEBUG_COTP)
if (bufPos != 0)
printf("TPKT: waiting (read %i of %i)\n", bufPos, self->packetSize);
self->readBuffer->size = bufPos;
return TPKT_WAITING;
}
| ./CrossVul/dataset_final_sorted/CWE-122/c/bad_4121_0 |
crossvul-cpp_data_good_4121_0 | /*
* cotp.c
*
* ISO 8073 Connection Oriented Transport Protocol over TCP (RFC1006)
*
* Partial implementation of the ISO 8073 COTP (ISO TP0) protocol for MMS.
*
* Copyright 2013-2018 Michael Zillgith
*
* This file is part of libIEC61850.
*
* libIEC61850 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.
*
* libIEC61850 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 libIEC61850. If not, see <http://www.gnu.org/licenses/>.
*
* See COPYING file for the complete license text.
*/
#include "libiec61850_platform_includes.h"
#include "stack_config.h"
#include "cotp.h"
#include "byte_buffer.h"
#include "buffer_chain.h"
#define TPKT_RFC1006_HEADER_SIZE 4
#define COTP_DATA_HEADER_SIZE 3
#ifdef CONFIG_COTP_MAX_TPDU_SIZE
#define COTP_MAX_TPDU_SIZE CONFIG_COTP_MAX_TPDU_SIZE
#else
#define COTP_MAX_TPDU_SIZE 8192
#endif
#ifndef DEBUG_COTP
#define DEBUG_COTP 0
#endif
static bool
addPayloadToBuffer(CotpConnection* self, uint8_t* buffer, int payloadLength);
static uint16_t
getUint16(uint8_t* buffer)
{
return (buffer[0] * 0x100) + buffer[1];
}
static uint8_t
getUint8(uint8_t* buffer)
{
return buffer[0];
}
static void
writeOptions(CotpConnection* self)
{
/* max size = 11 byte */
uint8_t* buffer = self->writeBuffer->buffer;
int bufPos = self->writeBuffer->size;
if (self->options.tpduSize != 0) {
if (DEBUG_COTP)
printf("COTP: send TPDU size: %i\n", CotpConnection_getTpduSize(self));
buffer[bufPos++] = 0xc0;
buffer[bufPos++] = 0x01;
buffer[bufPos++] = self->options.tpduSize;
}
if (self->options.tSelDst.size != 0) {
buffer[bufPos++] = 0xc2;
buffer[bufPos++] = (uint8_t) self->options.tSelDst.size;
int i;
for (i = 0; i < self->options.tSelDst.size; i++)
buffer[bufPos++] = (uint8_t) self->options.tSelDst.value[i];
}
if (self->options.tSelSrc.size != 0) {
buffer[bufPos++] = 0xc1;
buffer[bufPos++] = (uint8_t) self->options.tSelSrc.size;
int i;
for (i = 0; i < self->options.tSelSrc.size; i++)
buffer[bufPos++] = (uint8_t) self->options.tSelSrc.value[i];
}
self->writeBuffer->size = bufPos;
}
static int
getOptionsLength(CotpConnection* self)
{
int optionsLength = 0;
if (self->options.tpduSize != 0)
optionsLength += 3;
if (self->options.tSelDst.size != 0)
optionsLength += (2 + self->options.tSelDst.size);
if (self->options.tSelSrc.size != 0)
optionsLength += (2 + self->options.tSelSrc.size);
return optionsLength;
}
static void
writeStaticConnectResponseHeader(CotpConnection* self, int optionsLength)
{
/* always same size (7) and same position in buffer */
uint8_t* buffer = self->writeBuffer->buffer;
buffer[4] = 6 + optionsLength;
buffer[5] = 0xd0;
buffer[6] = (uint8_t) (self->remoteRef / 0x100);
buffer[7] = (uint8_t) (self->remoteRef & 0xff);
buffer[8] = (uint8_t) (self->localRef / 0x100);
buffer[9] = (uint8_t) (self->localRef & 0xff);
buffer[10] = (uint8_t) (self->protocolClass);
self->writeBuffer->size = 11;
}
static void
writeRfc1006Header(CotpConnection* self, int len)
{
uint8_t* buffer = self->writeBuffer->buffer;
buffer[0] = 0x03;
buffer[1] = 0x00;
buffer[2] = (uint8_t) (len / 0x100);
buffer[3] = (uint8_t) (len & 0xff);
self->writeBuffer->size = 4;
}
static void
writeDataTpduHeader(CotpConnection* self, int isLastUnit)
{
/* always 3 byte starting from byte 5 in buffer */
uint8_t* buffer = self->writeBuffer->buffer;
buffer[4] = 0x02;
buffer[5] = 0xf0;
if (isLastUnit)
buffer[6] = 0x80;
else
buffer[6] = 0x00;
self->writeBuffer->size = 7;
}
static int
writeToSocket(CotpConnection* self, uint8_t* buf, int size)
{
#if (CONFIG_MMS_SUPPORT_TLS == 1)
if (self->tlsSocket)
return TLSSocket_write(self->tlsSocket, buf, size);
else
return Socket_write(self->socket, buf, size);
#else
return Socket_write(self->socket, buf, size);
#endif
}
static bool
sendBuffer(CotpConnection* self)
{
int remainingSize = ByteBuffer_getSize(self->writeBuffer);
uint8_t* buffer = ByteBuffer_getBuffer(self->writeBuffer);
bool retVal = false;
do {
int sentBytes = writeToSocket(self, buffer, remainingSize);
if (sentBytes == -1)
goto exit_function;
buffer += sentBytes;
remainingSize -= sentBytes;
} while (remainingSize > 0);
retVal = true;
ByteBuffer_setSize(self->writeBuffer, 0);
exit_function:
return retVal;
}
CotpIndication
CotpConnection_sendDataMessage(CotpConnection* self, BufferChain payload)
{
CotpIndication retValue = COTP_OK;
int fragments = 1;
int fragmentPayloadSize = CotpConnection_getTpduSize(self) - COTP_DATA_HEADER_SIZE;
if (payload->length > fragmentPayloadSize) { /* Check if segmentation is required? */
fragments = payload->length / fragmentPayloadSize;
if ((payload->length % fragmentPayloadSize) != 0)
fragments += 1;
}
int currentBufPos = 0;
int currentLimit;
int lastUnit;
BufferChain currentChain = payload;
int currentChainIndex = 0;
if (DEBUG_COTP)
printf("\nCOTP: nextBufferPart: len:%i partLen:%i\n", currentChain->length, currentChain->partLength);
uint8_t* buffer = self->writeBuffer->buffer;
while (fragments > 0) {
if (fragments > 1) {
currentLimit = currentBufPos + fragmentPayloadSize;
lastUnit = 0;
}
else {
currentLimit = payload->length;
lastUnit = 1;
}
writeRfc1006Header(self, 7 + (currentLimit - currentBufPos));
writeDataTpduHeader(self, lastUnit);
int bufPos = 7;
int i;
for (i = currentBufPos; i < currentLimit; i++) {
if (currentChainIndex >= currentChain->partLength) {
currentChain = currentChain->nextPart;
if (DEBUG_COTP)
printf("\nCOTP: nextBufferPart: len:%i partLen:%i\n", currentChain->length, currentChain->partLength);
currentChainIndex = 0;
}
buffer[bufPos++] = currentChain->buffer[currentChainIndex];
currentChainIndex++;
currentBufPos++;
}
self->writeBuffer->size = bufPos;
if (DEBUG_COTP)
printf("COTP: Send COTP fragment %i bufpos: %i\n", fragments, currentBufPos);
if (!sendBuffer(self)) {
retValue = COTP_ERROR;
if (DEBUG_COTP)
printf("COTP: sending message failed!\n");
goto exit_function;
}
fragments--;
}
exit_function:
if (DEBUG_COTP)
printf("COTP: message transmission finished (fragments=%i, return=%i)\n", fragments, retValue);
return retValue;
}
static void
allocateWriteBuffer(CotpConnection* self)
{
if (self->writeBuffer == NULL )
self->writeBuffer = ByteBuffer_create(NULL,
CotpConnection_getTpduSize(self) + TPKT_RFC1006_HEADER_SIZE);
}
/* client side */
CotpIndication
CotpConnection_sendConnectionRequestMessage(CotpConnection* self, IsoConnectionParameters isoParameters)
{
allocateWriteBuffer(self);
self->options.tSelDst = isoParameters->remoteTSelector;
self->options.tSelSrc = isoParameters->localTSelector;
int cotpRequestSize = getOptionsLength(self) + 6;
int conRequestSize = cotpRequestSize + 5;
if(self->writeBuffer->maxSize < conRequestSize)
return COTP_ERROR;
uint8_t* buffer = self->writeBuffer->buffer;
writeRfc1006Header(self, conRequestSize);
/* LI */
buffer[4] = (uint8_t) cotpRequestSize;
/* TPDU CODE */
buffer[5] = 0xe0;
/* DST REF */
buffer[6] = 0x00;
buffer[7] = 0x00;
/* SRC REF */
buffer[8] = (uint8_t) (self->localRef / 0x100);
buffer[9] = (uint8_t) (self->localRef & 0xff);
/* Class */
buffer[10] = 0x00;
self->writeBuffer->size = 11;
writeOptions(self);
if (sendBuffer(self))
return COTP_OK;
else
return COTP_ERROR;
}
CotpIndication
CotpConnection_sendConnectionResponseMessage(CotpConnection* self)
{
allocateWriteBuffer(self);
int optionsLength = getOptionsLength(self);
int messageLength = 11 + optionsLength;
writeRfc1006Header(self, messageLength);
writeStaticConnectResponseHeader(self, optionsLength);
writeOptions(self);
if (sendBuffer(self))
return COTP_OK;
else
return COTP_ERROR;
}
static bool
parseOptions(CotpConnection* self, uint8_t* buffer, int bufLen)
{
int bufPos = 0;
while (bufPos < bufLen) {
uint8_t optionType = buffer[bufPos++];
uint8_t optionLen = buffer[bufPos++];
if (optionLen > (bufLen - bufPos)) {
if (DEBUG_COTP)
printf("COTP: option to long optionLen:%i bufPos:%i bufLen:%i\n", optionLen, bufPos, bufLen);
goto cpo_error;
}
if (DEBUG_COTP)
printf("COTP: option: %02x len: %02x\n", optionType, optionLen);
switch (optionType) {
case 0xc0:
if (optionLen == 1) {
int requestedTpduSize = (1 << buffer[bufPos++]);
CotpConnection_setTpduSize(self, requestedTpduSize);
if (DEBUG_COTP)
printf("COTP: requested TPDU size: %i\n", requestedTpduSize);
}
else
goto cpo_error;
break;
case 0xc1: /* remote T-selector */
if (optionLen < 5) {
self->options.tSelSrc.size = optionLen;
int i;
for (i = 0; i < optionLen; i++)
self->options.tSelSrc.value[i] = buffer[bufPos++];
}
else
goto cpo_error;
break;
case 0xc2: /* local T-selector */
if (optionLen < 5) {
self->options.tSelDst.size = optionLen;
int i;
for (i = 0; i < optionLen; i++)
self->options.tSelDst.value[i] = buffer[bufPos++];
}
else
goto cpo_error;
break;
case 0xc6: /* additional option selection */
if (optionLen == 1)
bufPos++; /* ignore value */
else
goto cpo_error;
break;
default:
if (DEBUG_COTP)
printf("COTP: Unknown option %02x\n", optionType);
bufPos += optionLen; /* ignore value */
break;
}
}
return true;
cpo_error:
if (DEBUG_COTP)
printf("COTP: cotp_parse_options: error parsing options!\n");
return false;
}
void
CotpConnection_init(CotpConnection* self, Socket socket,
ByteBuffer* payloadBuffer, ByteBuffer* readBuffer, ByteBuffer* writeBuffer)
{
self->state = 0;
self->socket = socket;
#if (CONFIG_MMS_SUPPORT_TLS == 1)
self->tlsSocket = NULL;
#endif
self->remoteRef = -1;
self->localRef = 1;
self->protocolClass = -1;
self->options.tpduSize = 0;
TSelector tsel;
tsel.size = 2;
tsel.value[0] = 0;
tsel.value[1] = 1;
self->options.tSelSrc = tsel;
self->options.tSelDst = tsel;
self->payload = payloadBuffer;
CotpConnection_resetPayload(self);
/* default TPDU size is maximum size */
CotpConnection_setTpduSize(self, COTP_MAX_TPDU_SIZE);
self->writeBuffer = writeBuffer;
self->readBuffer = readBuffer;
self->packetSize = 0;
}
int /* in byte */
CotpConnection_getTpduSize(CotpConnection* self)
{
return (1 << self->options.tpduSize);
}
void
CotpConnection_setTpduSize(CotpConnection* self, int tpduSize /* in byte */)
{
int newTpduSize = 1;
if (tpduSize > COTP_MAX_TPDU_SIZE)
tpduSize = COTP_MAX_TPDU_SIZE;
while ((1 << newTpduSize) < tpduSize)
newTpduSize++;
if ((1 << newTpduSize) > tpduSize)
newTpduSize--;
self->options.tpduSize = newTpduSize;
}
ByteBuffer*
CotpConnection_getPayload(CotpConnection* self)
{
return self->payload;
}
int
CotpConnection_getRemoteRef(CotpConnection* self)
{
return self->remoteRef;
}
int
CotpConnection_getLocalRef(CotpConnection* self)
{
return self->localRef;
}
/*
CR TPDU (from RFC 0905):
1 2 3 4 5 6 7 8 p p+1...end
+--+------+---------+---------+---+---+------+-------+---------+
|LI|CR CDT| DST - REF |SRC-REF|CLASS |VARIAB.|USER |
| |1110 |0000 0000|0000 0000| | |OPTION|PART |DATA |
+--+------+---------+---------+---+---+------+-------+---------+
*/
static bool
parseConnectRequestTpdu(CotpConnection* self, uint8_t* buffer, uint8_t len)
{
if (len < 6)
return false;
self->remoteRef = getUint16(buffer + 2);
self->protocolClass = getUint8(buffer + 4);
return parseOptions(self, buffer + 5, len - 6);
}
static bool
parseConnectConfirmTpdu(CotpConnection* self, uint8_t* buffer, uint8_t len)
{
if (len < 6)
return false;
self->remoteRef = getUint16(buffer);
self->protocolClass = getUint8(buffer + 4);
return parseOptions(self, buffer + 5, len - 6);
}
static bool
parseDataTpdu(CotpConnection* self, uint8_t* buffer, uint8_t len)
{
if (len != 2)
return false;
uint8_t flowControl = getUint8(buffer);
if (flowControl & 0x80)
self->isLastDataUnit = true;
else
self->isLastDataUnit = false;
return true;
}
static bool
addPayloadToBuffer(CotpConnection* self, uint8_t* buffer, int payloadLength)
{
if (payloadLength < 1) {
if (DEBUG_COTP)
printf("COTP: missing payload\n");
return false;
}
if (DEBUG_COTP)
printf("COTP: add to payload buffer (cur size: %i, len: %i)\n", self->payload->size, payloadLength);
if ((self->payload->size + payloadLength) > self->payload->maxSize)
return false;
memcpy(self->payload->buffer + self->payload->size, buffer, payloadLength);
self->payload->size += payloadLength;
return true;
}
static CotpIndication
parseCotpMessage(CotpConnection* self)
{
uint8_t* buffer = self->readBuffer->buffer + 4;
int tpduLength = self->readBuffer->size - 4;
uint8_t len;
uint8_t tpduType;
len = buffer[0];
if (len > tpduLength) {
if (DEBUG_COTP)
printf("COTP: parseCotpMessage: len=%d tpduLength=%d\n", len, tpduLength);
return COTP_ERROR;
}
tpduType = buffer[1];
switch (tpduType) {
case 0xe0:
if (parseConnectRequestTpdu(self, buffer + 2, len))
return COTP_CONNECT_INDICATION;
else
return COTP_ERROR;
case 0xd0:
if (parseConnectConfirmTpdu(self, buffer + 2, len))
return COTP_CONNECT_INDICATION;
else
return COTP_ERROR;
case 0xf0:
if (parseDataTpdu(self, buffer + 2, len)) {
if (addPayloadToBuffer(self, buffer + 3, tpduLength - 3) != 1)
return COTP_ERROR;
if (self->isLastDataUnit)
return COTP_DATA_INDICATION;
else
return COTP_MORE_FRAGMENTS_FOLLOW;
}
else
return COTP_ERROR;
default:
return COTP_ERROR;
}
}
CotpIndication
CotpConnection_parseIncomingMessage(CotpConnection* self)
{
CotpIndication indication = parseCotpMessage(self);
self->readBuffer->size = 0;
self->packetSize = 0;
return indication;
}
void
CotpConnection_resetPayload(CotpConnection* self)
{
self->payload->size = 0;
}
static int
readFromSocket(CotpConnection* self, uint8_t* buf, int size)
{
#if (CONFIG_MMS_SUPPORT_TLS == 1)
if (self->tlsSocket)
return TLSSocket_read(self->tlsSocket, buf, size);
else
return Socket_read(self->socket, buf, size);
#else
return Socket_read(self->socket, buf, size);
#endif
}
TpktState
CotpConnection_readToTpktBuffer(CotpConnection* self)
{
uint8_t* buffer = self->readBuffer->buffer;
int bufferSize = self->readBuffer->maxSize;
int bufPos = self->readBuffer->size;
assert (bufferSize > 4);
int readBytes;
if (bufPos < 4) {
readBytes = readFromSocket(self, buffer + bufPos, 4 - bufPos);
if (readBytes < 0)
goto exit_closed;
if (DEBUG_COTP) {
if (readBytes > 0)
printf("TPKT: read %i bytes from socket\n", readBytes);
}
bufPos += readBytes;
if (bufPos == 4) {
if ((buffer[0] == 3) && (buffer[1] == 0)) {
self->packetSize = (buffer[2] * 0x100) + buffer[3];
if (DEBUG_COTP)
printf("TPKT: header complete (msg size = %i)\n", self->packetSize);
if (self->packetSize > bufferSize) {
if (DEBUG_COTP) printf("TPKT: packet too large\n");
goto exit_error;
}
}
else {
if (DEBUG_COTP) printf("TPKT: failed to decode TPKT header.\n");
goto exit_error;
}
}
else
goto exit_waiting;
}
if (self->packetSize <= bufPos)
goto exit_error;
readBytes = readFromSocket(self, buffer + bufPos, self->packetSize - bufPos);
if (readBytes < 0)
goto exit_closed;
bufPos += readBytes;
if (bufPos < self->packetSize)
goto exit_waiting;
if (DEBUG_COTP) printf("TPKT: message complete (size = %i)\n", self->packetSize);
self->readBuffer->size = bufPos;
return TPKT_PACKET_COMPLETE;
exit_closed:
if (DEBUG_COTP) printf("TPKT: socket closed or socket error\n");
return TPKT_ERROR;
exit_error:
if (DEBUG_COTP) printf("TPKT: Error parsing message\n");
return TPKT_ERROR;
exit_waiting:
if (DEBUG_COTP)
if (bufPos != 0)
printf("TPKT: waiting (read %i of %i)\n", bufPos, self->packetSize);
self->readBuffer->size = bufPos;
return TPKT_WAITING;
}
| ./CrossVul/dataset_final_sorted/CWE-122/c/good_4121_0 |
crossvul-cpp_data_bad_1571_9 | /*
Copyright (c) 2005, 2013, Oracle and/or its affiliates. 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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
MySQL Slap
A simple program designed to work as if multiple clients querying the database,
then reporting the timing of each stage.
MySQL slap runs three stages:
1) Create schema,table, and optionally any SP or data you want to beign
the test with. (single client)
2) Load test (many clients)
3) Cleanup (disconnection, drop table if specified, single client)
Examples:
Supply your own create and query SQL statements, with 50 clients
querying (200 selects for each):
mysqlslap --delimiter=";" \
--create="CREATE TABLE A (a int);INSERT INTO A VALUES (23)" \
--query="SELECT * FROM A" --concurrency=50 --iterations=200
Let the program build the query SQL statement with a table of two int
columns, three varchar columns, five clients querying (20 times each),
don't create the table or insert the data (using the previous test's
schema and data):
mysqlslap --concurrency=5 --iterations=20 \
--number-int-cols=2 --number-char-cols=3 \
--auto-generate-sql
Tell the program to load the create, insert and query SQL statements from
the specified files, where the create.sql file has multiple table creation
statements delimited by ';' and multiple insert statements delimited by ';'.
The --query file will have multiple queries delimited by ';', run all the
load statements, and then run all the queries in the query file
with five clients (five times each):
mysqlslap --concurrency=5 \
--iterations=5 --query=query.sql --create=create.sql \
--delimiter=";"
TODO:
Add language for better tests
String length for files and those put on the command line are not
setup to handle binary data.
More stats
Break up tests and run them on multiple hosts at once.
Allow output to be fed into a database directly.
*/
#define SLAP_VERSION "1.0"
#define HUGE_STRING_LENGTH 8196
#define RAND_STRING_SIZE 126
/* Types */
#define SELECT_TYPE 0
#define UPDATE_TYPE 1
#define INSERT_TYPE 2
#define UPDATE_TYPE_REQUIRES_PREFIX 3
#define CREATE_TABLE_TYPE 4
#define SELECT_TYPE_REQUIRES_PREFIX 5
#define DELETE_TYPE_REQUIRES_PREFIX 6
#include "client_priv.h"
#include "my_default.h"
#include <mysqld_error.h>
#include <my_dir.h>
#include <signal.h>
#include <stdarg.h>
#include <sslopt-vars.h>
#include <sys/types.h>
#ifndef _WIN32
#include <sys/wait.h>
#endif
#include <ctype.h>
#include <welcome_copyright_notice.h> /* ORACLE_WELCOME_COPYRIGHT_NOTICE */
#ifdef _WIN32
#define srandom srand
#define random rand
#define snprintf _snprintf
#endif
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
static char *shared_memory_base_name=0;
#endif
/* Global Thread counter */
uint thread_counter;
pthread_mutex_t counter_mutex;
pthread_cond_t count_threshhold;
uint master_wakeup;
pthread_mutex_t sleeper_mutex;
pthread_cond_t sleep_threshhold;
static char **defaults_argv;
char **primary_keys;
unsigned long long primary_keys_number_of;
static char *host= NULL, *opt_password= NULL, *user= NULL,
*user_supplied_query= NULL,
*user_supplied_pre_statements= NULL,
*user_supplied_post_statements= NULL,
*default_engine= NULL,
*pre_system= NULL,
*post_system= NULL,
*opt_mysql_unix_port= NULL;
static char *opt_plugin_dir= 0, *opt_default_auth= 0;
static uint opt_enable_cleartext_plugin= 0;
static my_bool using_opt_enable_cleartext_plugin= 0;
const char *delimiter= "\n";
const char *create_schema_string= "mysqlslap";
static my_bool opt_preserve= TRUE, opt_no_drop= FALSE;
static my_bool debug_info_flag= 0, debug_check_flag= 0;
static my_bool opt_only_print= FALSE;
static my_bool opt_compress= FALSE, tty_password= FALSE,
opt_silent= FALSE,
auto_generate_sql_autoincrement= FALSE,
auto_generate_sql_guid_primary= FALSE,
auto_generate_sql= FALSE;
const char *auto_generate_sql_type= "mixed";
static unsigned long connect_flags= CLIENT_MULTI_RESULTS |
CLIENT_MULTI_STATEMENTS |
CLIENT_REMEMBER_OPTIONS;
static int verbose, delimiter_length;
static uint commit_rate;
static uint detach_rate;
const char *num_int_cols_opt;
const char *num_char_cols_opt;
/* Yes, we do set defaults here */
static unsigned int num_int_cols= 1;
static unsigned int num_char_cols= 1;
static unsigned int num_int_cols_index= 0;
static unsigned int num_char_cols_index= 0;
static unsigned int iterations;
static uint my_end_arg= 0;
static char *default_charset= (char*) MYSQL_DEFAULT_CHARSET_NAME;
static ulonglong actual_queries= 0;
static ulonglong auto_actual_queries;
static ulonglong auto_generate_sql_unique_write_number;
static ulonglong auto_generate_sql_unique_query_number;
static unsigned int auto_generate_sql_secondary_indexes;
static ulonglong num_of_query;
static ulonglong auto_generate_sql_number;
const char *concurrency_str= NULL;
static char *create_string;
uint *concurrency;
const char *default_dbug_option="d:t:o,/tmp/mysqlslap.trace";
const char *opt_csv_str;
File csv_file;
static uint opt_protocol= 0;
static int get_options(int *argc,char ***argv);
static uint opt_mysql_port= 0;
static const char *load_default_groups[]= { "mysqlslap","client",0 };
typedef struct statement statement;
struct statement {
char *string;
size_t length;
unsigned char type;
char *option;
size_t option_length;
statement *next;
};
typedef struct option_string option_string;
struct option_string {
char *string;
size_t length;
char *option;
size_t option_length;
option_string *next;
};
typedef struct stats stats;
struct stats {
long int timing;
uint users;
unsigned long long rows;
};
typedef struct thread_context thread_context;
struct thread_context {
statement *stmt;
ulonglong limit;
};
typedef struct conclusions conclusions;
struct conclusions {
char *engine;
long int avg_timing;
long int max_timing;
long int min_timing;
uint users;
unsigned long long avg_rows;
/* The following are not used yet */
unsigned long long max_rows;
unsigned long long min_rows;
};
static option_string *engine_options= NULL;
static statement *pre_statements= NULL;
static statement *post_statements= NULL;
static statement *create_statements= NULL,
*query_statements= NULL;
/* Prototypes */
void print_conclusions(conclusions *con);
void print_conclusions_csv(conclusions *con);
void generate_stats(conclusions *con, option_string *eng, stats *sptr);
uint parse_comma(const char *string, uint **range);
uint parse_delimiter(const char *script, statement **stmt, char delm);
uint parse_option(const char *origin, option_string **stmt, char delm);
static int drop_schema(MYSQL *mysql, const char *db);
uint get_random_string(char *buf);
static statement *build_table_string(void);
static statement *build_insert_string(void);
static statement *build_update_string(void);
static statement * build_select_string(my_bool key);
static int generate_primary_key_list(MYSQL *mysql, option_string *engine_stmt);
static int drop_primary_key_list(void);
static int create_schema(MYSQL *mysql, const char *db, statement *stmt,
option_string *engine_stmt);
static int run_scheduler(stats *sptr, statement *stmts, uint concur,
ulonglong limit);
pthread_handler_t run_task(void *p);
void statement_cleanup(statement *stmt);
void option_cleanup(option_string *stmt);
void concurrency_loop(MYSQL *mysql, uint current, option_string *eptr);
static int run_statements(MYSQL *mysql, statement *stmt);
int slap_connect(MYSQL *mysql);
static int run_query(MYSQL *mysql, const char *query, int len);
static const char ALPHANUMERICS[]=
"0123456789ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstuvwxyz";
#define ALPHANUMERICS_SIZE (sizeof(ALPHANUMERICS)-1)
static long int timedif(struct timeval a, struct timeval b)
{
int us, s;
us = a.tv_usec - b.tv_usec;
us /= 1000;
s = a.tv_sec - b.tv_sec;
s *= 1000;
return s + us;
}
#ifdef _WIN32
static int gettimeofday(struct timeval *tp, void *tzp)
{
unsigned int ticks;
ticks= GetTickCount();
tp->tv_usec= ticks*1000;
tp->tv_sec= ticks/1000;
return 0;
}
#endif
int main(int argc, char **argv)
{
MYSQL mysql;
option_string *eptr;
MY_INIT(argv[0]);
my_getopt_use_args_separator= TRUE;
if (load_defaults("my",load_default_groups,&argc,&argv))
{
my_end(0);
exit(1);
}
my_getopt_use_args_separator= FALSE;
defaults_argv=argv;
if (get_options(&argc,&argv))
{
free_defaults(defaults_argv);
my_end(0);
exit(1);
}
/* Seed the random number generator if we will be using it. */
if (auto_generate_sql)
srandom((uint)time(NULL));
/* globals? Yes, so we only have to run strlen once */
delimiter_length= strlen(delimiter);
if (argc > 2)
{
fprintf(stderr,"%s: Too many arguments\n",my_progname);
free_defaults(defaults_argv);
my_end(0);
exit(1);
}
mysql_init(&mysql);
if (opt_compress)
mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
#ifdef HAVE_OPENSSL
if (opt_use_ssl)
{
mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(&mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(&mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
}
#endif
if (opt_protocol)
mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
if (shared_memory_base_name)
mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);
mysql_options(&mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(&mysql, MYSQL_OPT_CONNECT_ATTR_ADD,
"program_name", "mysqlslap");
if (using_opt_enable_cleartext_plugin)
mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN,
(char*) &opt_enable_cleartext_plugin);
if (!opt_only_print)
{
if (!(mysql_real_connect(&mysql, host, user, opt_password,
NULL, opt_mysql_port,
opt_mysql_unix_port, connect_flags)))
{
fprintf(stderr,"%s: Error when connecting to server: %s\n",
my_progname,mysql_error(&mysql));
free_defaults(defaults_argv);
my_end(0);
exit(1);
}
}
pthread_mutex_init(&counter_mutex, NULL);
pthread_cond_init(&count_threshhold, NULL);
pthread_mutex_init(&sleeper_mutex, NULL);
pthread_cond_init(&sleep_threshhold, NULL);
/* Main iterations loop */
eptr= engine_options;
do
{
/* For the final stage we run whatever queries we were asked to run */
uint *current;
if (verbose >= 2)
printf("Starting Concurrency Test\n");
if (*concurrency)
{
for (current= concurrency; current && *current; current++)
concurrency_loop(&mysql, *current, eptr);
}
else
{
uint infinite= 1;
do {
concurrency_loop(&mysql, infinite, eptr);
}
while (infinite++);
}
if (!opt_preserve)
drop_schema(&mysql, create_schema_string);
} while (eptr ? (eptr= eptr->next) : 0);
pthread_mutex_destroy(&counter_mutex);
pthread_cond_destroy(&count_threshhold);
pthread_mutex_destroy(&sleeper_mutex);
pthread_cond_destroy(&sleep_threshhold);
if (!opt_only_print)
mysql_close(&mysql); /* Close & free connection */
/* now free all the strings we created */
my_free(opt_password);
my_free(concurrency);
statement_cleanup(create_statements);
statement_cleanup(query_statements);
statement_cleanup(pre_statements);
statement_cleanup(post_statements);
option_cleanup(engine_options);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
my_free(shared_memory_base_name);
#endif
free_defaults(defaults_argv);
my_end(my_end_arg);
return 0;
}
void concurrency_loop(MYSQL *mysql, uint current, option_string *eptr)
{
unsigned int x;
stats *head_sptr;
stats *sptr;
conclusions conclusion;
unsigned long long client_limit;
int sysret;
head_sptr= (stats *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(stats) * iterations,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
memset(&conclusion, 0, sizeof(conclusions));
if (auto_actual_queries)
client_limit= auto_actual_queries;
else if (num_of_query)
client_limit= num_of_query / current;
else
client_limit= actual_queries;
for (x= 0, sptr= head_sptr; x < iterations; x++, sptr++)
{
/*
We might not want to load any data, such as when we are calling
a stored_procedure that doesn't use data, or we know we already have
data in the table.
*/
if (!opt_preserve)
drop_schema(mysql, create_schema_string);
/* First we create */
if (create_statements)
create_schema(mysql, create_schema_string, create_statements, eptr);
/*
If we generated GUID we need to build a list of them from creation that
we can later use.
*/
if (verbose >= 2)
printf("Generating primary key list\n");
if (auto_generate_sql_autoincrement || auto_generate_sql_guid_primary)
generate_primary_key_list(mysql, eptr);
if (commit_rate)
run_query(mysql, "SET AUTOCOMMIT=0", strlen("SET AUTOCOMMIT=0"));
if (pre_system)
if ((sysret= system(pre_system)) != 0)
fprintf(stderr, "Warning: Execution of pre_system option returned %d.\n",
sysret);
/*
Pre statements are always run after all other logic so they can
correct/adjust any item that they want.
*/
if (pre_statements)
run_statements(mysql, pre_statements);
run_scheduler(sptr, query_statements, current, client_limit);
if (post_statements)
run_statements(mysql, post_statements);
if (post_system)
if ((sysret= system(post_system)) != 0)
fprintf(stderr, "Warning: Execution of post_system option returned %d.\n",
sysret);
/* We are finished with this run */
if (auto_generate_sql_autoincrement || auto_generate_sql_guid_primary)
drop_primary_key_list();
}
if (verbose >= 2)
printf("Generating stats\n");
generate_stats(&conclusion, eptr, head_sptr);
if (!opt_silent)
print_conclusions(&conclusion);
if (opt_csv_str)
print_conclusions_csv(&conclusion);
my_free(head_sptr);
}
static struct my_option my_long_options[] =
{
{"help", '?', "Display this help and exit.", 0, 0, 0, GET_NO_ARG, NO_ARG,
0, 0, 0, 0, 0, 0},
{"auto-generate-sql", 'a',
"Generate SQL where not supplied by file or command line.",
&auto_generate_sql, &auto_generate_sql,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"auto-generate-sql-add-autoincrement", OPT_SLAP_AUTO_GENERATE_ADD_AUTO,
"Add an AUTO_INCREMENT column to auto-generated tables.",
&auto_generate_sql_autoincrement,
&auto_generate_sql_autoincrement,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"auto-generate-sql-execute-number", OPT_SLAP_AUTO_GENERATE_EXECUTE_QUERIES,
"Set this number to generate a set number of queries to run.",
&auto_actual_queries, &auto_actual_queries,
0, GET_ULL, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"auto-generate-sql-guid-primary", OPT_SLAP_AUTO_GENERATE_GUID_PRIMARY,
"Add GUID based primary keys to auto-generated tables.",
&auto_generate_sql_guid_primary,
&auto_generate_sql_guid_primary,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"auto-generate-sql-load-type", OPT_SLAP_AUTO_GENERATE_SQL_LOAD_TYPE,
"Specify test load type: mixed, update, write, key, or read; default is mixed.",
&auto_generate_sql_type, &auto_generate_sql_type,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"auto-generate-sql-secondary-indexes",
OPT_SLAP_AUTO_GENERATE_SECONDARY_INDEXES,
"Number of secondary indexes to add to auto-generated tables.",
&auto_generate_sql_secondary_indexes,
&auto_generate_sql_secondary_indexes, 0,
GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"auto-generate-sql-unique-query-number",
OPT_SLAP_AUTO_GENERATE_UNIQUE_QUERY_NUM,
"Number of unique queries to generate for automatic tests.",
&auto_generate_sql_unique_query_number,
&auto_generate_sql_unique_query_number,
0, GET_ULL, REQUIRED_ARG, 10, 0, 0, 0, 0, 0},
{"auto-generate-sql-unique-write-number",
OPT_SLAP_AUTO_GENERATE_UNIQUE_WRITE_NUM,
"Number of unique queries to generate for auto-generate-sql-write-number.",
&auto_generate_sql_unique_write_number,
&auto_generate_sql_unique_write_number,
0, GET_ULL, REQUIRED_ARG, 10, 0, 0, 0, 0, 0},
{"auto-generate-sql-write-number", OPT_SLAP_AUTO_GENERATE_WRITE_NUM,
"Number of row inserts to perform for each thread (default is 100).",
&auto_generate_sql_number, &auto_generate_sql_number,
0, GET_ULL, REQUIRED_ARG, 100, 0, 0, 0, 0, 0},
{"commit", OPT_SLAP_COMMIT, "Commit records every X number of statements.",
&commit_rate, &commit_rate, 0, GET_UINT, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"compress", 'C', "Use compression in server/client protocol.",
&opt_compress, &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
0, 0, 0},
{"concurrency", 'c', "Number of clients to simulate for query to run.",
&concurrency_str, &concurrency_str, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"create", OPT_SLAP_CREATE_STRING, "File or string to use create tables.",
&create_string, &create_string, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"create-schema", OPT_CREATE_SLAP_SCHEMA, "Schema to run tests in.",
&create_schema_string, &create_schema_string, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"csv", OPT_SLAP_CSV,
"Generate CSV output to named file or to stdout if no file is named.",
NULL, NULL, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
#ifdef DBUG_OFF
{"debug", '#', "This is a non-debug version. Catch this and exit.",
0, 0, 0, GET_DISABLED, OPT_ARG, 0, 0, 0, 0, 0, 0},
#else
{"debug", '#', "Output debug log. Often this is 'd:t:o,filename'.",
&default_dbug_option, &default_dbug_option, 0, GET_STR,
OPT_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"debug-check", OPT_DEBUG_CHECK, "Check memory and open file usage at exit.",
&debug_check_flag, &debug_check_flag, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"debug-info", 'T', "Print some debug info at exit.", &debug_info_flag,
&debug_info_flag, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"default_auth", OPT_DEFAULT_AUTH,
"Default authentication client-side plugin to use.",
&opt_default_auth, &opt_default_auth, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"delimiter", 'F',
"Delimiter to use in SQL statements supplied in file or command line.",
&delimiter, &delimiter, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"detach", OPT_SLAP_DETACH,
"Detach (close and reopen) connections after X number of requests.",
&detach_rate, &detach_rate, 0, GET_UINT, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"enable_cleartext_plugin", OPT_ENABLE_CLEARTEXT_PLUGIN,
"Enable/disable the clear text authentication plugin.",
&opt_enable_cleartext_plugin, &opt_enable_cleartext_plugin,
0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0},
{"engine", 'e', "Storage engine to use for creating the table.",
&default_engine, &default_engine, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"host", 'h', "Connect to host.", &host, &host, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"iterations", 'i', "Number of times to run the tests.", &iterations,
&iterations, 0, GET_UINT, REQUIRED_ARG, 1, 0, 0, 0, 0, 0},
{"no-drop", OPT_SLAP_NO_DROP, "Do not drop the schema after the test.",
&opt_no_drop, &opt_no_drop, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"number-char-cols", 'x',
"Number of VARCHAR columns to create in table if specifying --auto-generate-sql.",
&num_char_cols_opt, &num_char_cols_opt, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"number-int-cols", 'y',
"Number of INT columns to create in table if specifying --auto-generate-sql.",
&num_int_cols_opt, &num_int_cols_opt, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"number-of-queries", OPT_MYSQL_NUMBER_OF_QUERY,
"Limit each client to this number of queries (this is not exact).",
&num_of_query, &num_of_query, 0,
GET_ULL, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"only-print", OPT_MYSQL_ONLY_PRINT,
"Do not connect to the databases, but instead print out what would have "
"been done.",
&opt_only_print, &opt_only_print, 0, GET_BOOL, NO_ARG,
0, 0, 0, 0, 0, 0},
{"password", 'p',
"Password to use when connecting to server. If password is not given it's "
"asked from the tty.", 0, 0, 0, GET_PASSWORD, OPT_ARG, 0, 0, 0, 0, 0, 0},
#ifdef _WIN32
{"pipe", 'W', "Use named pipes to connect to server.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"plugin_dir", OPT_PLUGIN_DIR, "Directory for client-side plugins.",
&opt_plugin_dir, &opt_plugin_dir, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"port", 'P', "Port number to use for connection.", &opt_mysql_port,
&opt_mysql_port, 0, GET_UINT, REQUIRED_ARG, MYSQL_PORT, 0, 0, 0, 0,
0},
{"post-query", OPT_SLAP_POST_QUERY,
"Query to run or file containing query to execute after tests have completed.",
&user_supplied_post_statements, &user_supplied_post_statements,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"post-system", OPT_SLAP_POST_SYSTEM,
"system() string to execute after tests have completed.",
&post_system, &post_system,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"pre-query", OPT_SLAP_PRE_QUERY,
"Query to run or file containing query to execute before running tests.",
&user_supplied_pre_statements, &user_supplied_pre_statements,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"pre-system", OPT_SLAP_PRE_SYSTEM,
"system() string to execute before running tests.",
&pre_system, &pre_system,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"protocol", OPT_MYSQL_PROTOCOL,
"The protocol to use for connection (tcp, socket, pipe, memory).",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"query", 'q', "Query to run or file containing query to run.",
&user_supplied_query, &user_supplied_query,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
{"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
"Base name of shared memory.", &shared_memory_base_name,
&shared_memory_base_name, 0, GET_STR_ALLOC, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
#endif
{"silent", 's', "Run program in silent mode - no output.",
&opt_silent, &opt_silent, 0, GET_BOOL, NO_ARG,
0, 0, 0, 0, 0, 0},
{"socket", 'S', "The socket file to use for connection.",
&opt_mysql_unix_port, &opt_mysql_unix_port, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#include <sslopt-longopts.h>
{"user", 'u', "User for login if not current user.", &user,
&user, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"verbose", 'v',
"More verbose output; you can use this multiple times to get even more "
"verbose output.", &verbose, &verbose, 0, GET_NO_ARG, NO_ARG,
0, 0, 0, 0, 0, 0},
{"version", 'V', "Output version information and exit.", 0, 0, 0,
GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
static void print_version(void)
{
printf("%s Ver %s Distrib %s, for %s (%s)\n",my_progname, SLAP_VERSION,
MYSQL_SERVER_VERSION,SYSTEM_TYPE,MACHINE_TYPE);
}
static void usage(void)
{
print_version();
puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2005"));
puts("Run a query multiple times against the server.\n");
printf("Usage: %s [OPTIONS]\n",my_progname);
print_defaults("my",load_default_groups);
my_print_help(my_long_options);
}
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
char *argument)
{
DBUG_ENTER("get_one_option");
switch(optid) {
case 'v':
verbose++;
break;
case 'p':
if (argument == disabled_my_option)
argument= (char*) ""; /* Don't require password */
if (argument)
{
char *start= argument;
my_free(opt_password);
opt_password= my_strdup(PSI_NOT_INSTRUMENTED,
argument,MYF(MY_FAE));
while (*argument) *argument++= 'x'; /* Destroy argument */
if (*start)
start[1]= 0; /* Cut length of argument */
tty_password= 0;
}
else
tty_password= 1;
break;
case 'W':
#ifdef _WIN32
opt_protocol= MYSQL_PROTOCOL_PIPE;
#endif
break;
case OPT_MYSQL_PROTOCOL:
opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
opt->name);
break;
case '#':
DBUG_PUSH(argument ? argument : default_dbug_option);
debug_check_flag= 1;
break;
case OPT_SLAP_CSV:
if (!argument)
argument= (char *)"-"; /* use stdout */
opt_csv_str= argument;
break;
#include <sslopt-case.h>
case 'V':
print_version();
exit(0);
break;
case '?':
case 'I': /* Info */
usage();
exit(0);
case OPT_ENABLE_CLEARTEXT_PLUGIN:
using_opt_enable_cleartext_plugin= TRUE;
break;
}
DBUG_RETURN(0);
}
uint
get_random_string(char *buf)
{
char *buf_ptr= buf;
int x;
DBUG_ENTER("get_random_string");
for (x= RAND_STRING_SIZE; x > 0; x--)
*buf_ptr++= ALPHANUMERICS[random() % ALPHANUMERICS_SIZE];
DBUG_RETURN(buf_ptr - buf);
}
/*
build_table_string
This function builds a create table query if the user opts to not supply
a file or string containing a create table statement
*/
static statement *
build_table_string(void)
{
char buf[HUGE_STRING_LENGTH];
unsigned int col_count;
statement *ptr;
DYNAMIC_STRING table_string;
DBUG_ENTER("build_table_string");
DBUG_PRINT("info", ("num int cols %u num char cols %u",
num_int_cols, num_char_cols));
init_dynamic_string(&table_string, "", 1024, 1024);
dynstr_append(&table_string, "CREATE TABLE `t1` (");
if (auto_generate_sql_autoincrement)
{
dynstr_append(&table_string, "id serial");
if (num_int_cols || num_char_cols)
dynstr_append(&table_string, ",");
}
if (auto_generate_sql_guid_primary)
{
dynstr_append(&table_string, "id varchar(32) primary key");
if (num_int_cols || num_char_cols || auto_generate_sql_guid_primary)
dynstr_append(&table_string, ",");
}
if (auto_generate_sql_secondary_indexes)
{
unsigned int count;
for (count= 0; count < auto_generate_sql_secondary_indexes; count++)
{
if (count) /* Except for the first pass we add a comma */
dynstr_append(&table_string, ",");
if (snprintf(buf, HUGE_STRING_LENGTH, "id%d varchar(32) unique key", count)
> HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in create table\n");
exit(1);
}
dynstr_append(&table_string, buf);
}
if (num_int_cols || num_char_cols)
dynstr_append(&table_string, ",");
}
if (num_int_cols)
for (col_count= 1; col_count <= num_int_cols; col_count++)
{
if (num_int_cols_index)
{
if (snprintf(buf, HUGE_STRING_LENGTH, "intcol%d INT(32), INDEX(intcol%d)",
col_count, col_count) > HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in create table\n");
exit(1);
}
}
else
{
if (snprintf(buf, HUGE_STRING_LENGTH, "intcol%d INT(32) ", col_count)
> HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in create table\n");
exit(1);
}
}
dynstr_append(&table_string, buf);
if (col_count < num_int_cols || num_char_cols > 0)
dynstr_append(&table_string, ",");
}
if (num_char_cols)
for (col_count= 1; col_count <= num_char_cols; col_count++)
{
if (num_char_cols_index)
{
if (snprintf(buf, HUGE_STRING_LENGTH,
"charcol%d VARCHAR(128), INDEX(charcol%d) ",
col_count, col_count) > HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in creating table\n");
exit(1);
}
}
else
{
if (snprintf(buf, HUGE_STRING_LENGTH, "charcol%d VARCHAR(128)",
col_count) > HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in creating table\n");
exit(1);
}
}
dynstr_append(&table_string, buf);
if (col_count < num_char_cols)
dynstr_append(&table_string, ",");
}
dynstr_append(&table_string, ")");
ptr= (statement *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(statement),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->string = (char *)my_malloc(PSI_NOT_INSTRUMENTED,
table_string.length+1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->length= table_string.length+1;
ptr->type= CREATE_TABLE_TYPE;
my_stpcpy(ptr->string, table_string.str);
dynstr_free(&table_string);
DBUG_RETURN(ptr);
}
/*
build_update_string()
This function builds insert statements when the user opts to not supply
an insert file or string containing insert data
*/
static statement *
build_update_string(void)
{
char buf[HUGE_STRING_LENGTH];
unsigned int col_count;
statement *ptr;
DYNAMIC_STRING update_string;
DBUG_ENTER("build_update_string");
init_dynamic_string(&update_string, "", 1024, 1024);
dynstr_append(&update_string, "UPDATE t1 SET ");
if (num_int_cols)
for (col_count= 1; col_count <= num_int_cols; col_count++)
{
if (snprintf(buf, HUGE_STRING_LENGTH, "intcol%d = %ld", col_count,
random()) > HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in creating update\n");
exit(1);
}
dynstr_append(&update_string, buf);
if (col_count < num_int_cols || num_char_cols > 0)
dynstr_append_mem(&update_string, ",", 1);
}
if (num_char_cols)
for (col_count= 1; col_count <= num_char_cols; col_count++)
{
char rand_buffer[RAND_STRING_SIZE];
int buf_len= get_random_string(rand_buffer);
if (snprintf(buf, HUGE_STRING_LENGTH, "charcol%d = '%.*s'", col_count,
buf_len, rand_buffer)
> HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in creating update\n");
exit(1);
}
dynstr_append(&update_string, buf);
if (col_count < num_char_cols)
dynstr_append_mem(&update_string, ",", 1);
}
if (auto_generate_sql_autoincrement || auto_generate_sql_guid_primary)
dynstr_append(&update_string, " WHERE id = ");
ptr= (statement *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(statement),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->string= (char *)my_malloc(PSI_NOT_INSTRUMENTED,
update_string.length + 1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->length= update_string.length+1;
if (auto_generate_sql_autoincrement || auto_generate_sql_guid_primary)
ptr->type= UPDATE_TYPE_REQUIRES_PREFIX ;
else
ptr->type= UPDATE_TYPE;
my_stpcpy(ptr->string, update_string.str);
dynstr_free(&update_string);
DBUG_RETURN(ptr);
}
/*
build_insert_string()
This function builds insert statements when the user opts to not supply
an insert file or string containing insert data
*/
static statement *
build_insert_string(void)
{
char buf[HUGE_STRING_LENGTH];
unsigned int col_count;
statement *ptr;
DYNAMIC_STRING insert_string;
DBUG_ENTER("build_insert_string");
init_dynamic_string(&insert_string, "", 1024, 1024);
dynstr_append(&insert_string, "INSERT INTO t1 VALUES (");
if (auto_generate_sql_autoincrement)
{
dynstr_append(&insert_string, "NULL");
if (num_int_cols || num_char_cols)
dynstr_append(&insert_string, ",");
}
if (auto_generate_sql_guid_primary)
{
dynstr_append(&insert_string, "uuid()");
if (num_int_cols || num_char_cols)
dynstr_append(&insert_string, ",");
}
if (auto_generate_sql_secondary_indexes)
{
unsigned int count;
for (count= 0; count < auto_generate_sql_secondary_indexes; count++)
{
if (count) /* Except for the first pass we add a comma */
dynstr_append(&insert_string, ",");
dynstr_append(&insert_string, "uuid()");
}
if (num_int_cols || num_char_cols)
dynstr_append(&insert_string, ",");
}
if (num_int_cols)
for (col_count= 1; col_count <= num_int_cols; col_count++)
{
if (snprintf(buf, HUGE_STRING_LENGTH, "%ld", random()) > HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in creating insert\n");
exit(1);
}
dynstr_append(&insert_string, buf);
if (col_count < num_int_cols || num_char_cols > 0)
dynstr_append_mem(&insert_string, ",", 1);
}
if (num_char_cols)
for (col_count= 1; col_count <= num_char_cols; col_count++)
{
int buf_len= get_random_string(buf);
dynstr_append_mem(&insert_string, "'", 1);
dynstr_append_mem(&insert_string, buf, buf_len);
dynstr_append_mem(&insert_string, "'", 1);
if (col_count < num_char_cols)
dynstr_append_mem(&insert_string, ",", 1);
}
dynstr_append_mem(&insert_string, ")", 1);
ptr= (statement *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(statement),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->string= (char *)my_malloc(PSI_NOT_INSTRUMENTED,
insert_string.length + 1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->length= insert_string.length+1;
ptr->type= INSERT_TYPE;
my_stpcpy(ptr->string, insert_string.str);
dynstr_free(&insert_string);
DBUG_RETURN(ptr);
}
/*
build_select_string()
This function builds a query if the user opts to not supply a query
statement or file containing a query statement
*/
static statement *
build_select_string(my_bool key)
{
char buf[HUGE_STRING_LENGTH];
unsigned int col_count;
statement *ptr;
static DYNAMIC_STRING query_string;
DBUG_ENTER("build_select_string");
init_dynamic_string(&query_string, "", 1024, 1024);
dynstr_append_mem(&query_string, "SELECT ", 7);
for (col_count= 1; col_count <= num_int_cols; col_count++)
{
if (snprintf(buf, HUGE_STRING_LENGTH, "intcol%d", col_count)
> HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in creating select\n");
exit(1);
}
dynstr_append(&query_string, buf);
if (col_count < num_int_cols || num_char_cols > 0)
dynstr_append_mem(&query_string, ",", 1);
}
for (col_count= 1; col_count <= num_char_cols; col_count++)
{
if (snprintf(buf, HUGE_STRING_LENGTH, "charcol%d", col_count)
> HUGE_STRING_LENGTH)
{
fprintf(stderr, "Memory Allocation error in creating select\n");
exit(1);
}
dynstr_append(&query_string, buf);
if (col_count < num_char_cols)
dynstr_append_mem(&query_string, ",", 1);
}
dynstr_append(&query_string, " FROM t1");
if ((key) &&
(auto_generate_sql_autoincrement || auto_generate_sql_guid_primary))
dynstr_append(&query_string, " WHERE id = ");
ptr= (statement *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(statement),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->string= (char *)my_malloc(PSI_NOT_INSTRUMENTED,
query_string.length + 1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr->length= query_string.length+1;
if ((key) &&
(auto_generate_sql_autoincrement || auto_generate_sql_guid_primary))
ptr->type= SELECT_TYPE_REQUIRES_PREFIX;
else
ptr->type= SELECT_TYPE;
my_stpcpy(ptr->string, query_string.str);
dynstr_free(&query_string);
DBUG_RETURN(ptr);
}
static int
get_options(int *argc,char ***argv)
{
int ho_error;
char *tmp_string;
MY_STAT sbuf; /* Stat information for the data file */
DBUG_ENTER("get_options");
if ((ho_error= handle_options(argc, argv, my_long_options, get_one_option)))
exit(ho_error);
if (debug_info_flag)
my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
if (debug_check_flag)
my_end_arg= MY_CHECK_ERROR;
if (!user)
user= (char *)"root";
/*
If something is created and --no-drop is not specified, we drop the
schema.
*/
if (!opt_no_drop && (create_string || auto_generate_sql))
opt_preserve= FALSE;
if (auto_generate_sql && (create_string || user_supplied_query))
{
fprintf(stderr,
"%s: Can't use --auto-generate-sql when create and query strings are specified!\n",
my_progname);
exit(1);
}
if (auto_generate_sql && auto_generate_sql_guid_primary &&
auto_generate_sql_autoincrement)
{
fprintf(stderr,
"%s: Either auto-generate-sql-guid-primary or auto-generate-sql-add-autoincrement can be used!\n",
my_progname);
exit(1);
}
/*
We are testing to make sure that if someone specified a key search
that we actually added a key!
*/
if (auto_generate_sql && auto_generate_sql_type[0] == 'k')
if ( auto_generate_sql_autoincrement == FALSE &&
auto_generate_sql_guid_primary == FALSE)
{
fprintf(stderr,
"%s: Can't perform key test without a primary key!\n",
my_progname);
exit(1);
}
if (auto_generate_sql && num_of_query && auto_actual_queries)
{
fprintf(stderr,
"%s: Either auto-generate-sql-execute-number or number-of-queries can be used!\n",
my_progname);
exit(1);
}
parse_comma(concurrency_str ? concurrency_str : "1", &concurrency);
if (opt_csv_str)
{
opt_silent= TRUE;
if (opt_csv_str[0] == '-')
{
csv_file= my_fileno(stdout);
}
else
{
if ((csv_file= my_open(opt_csv_str, O_CREAT|O_WRONLY|O_APPEND, MYF(0)))
== -1)
{
fprintf(stderr,"%s: Could not open csv file: %sn\n",
my_progname, opt_csv_str);
exit(1);
}
}
}
if (opt_only_print)
opt_silent= TRUE;
if (num_int_cols_opt)
{
option_string *str;
parse_option(num_int_cols_opt, &str, ',');
num_int_cols= atoi(str->string);
if (str->option)
num_int_cols_index= atoi(str->option);
option_cleanup(str);
}
if (num_char_cols_opt)
{
option_string *str;
parse_option(num_char_cols_opt, &str, ',');
num_char_cols= atoi(str->string);
if (str->option)
num_char_cols_index= atoi(str->option);
else
num_char_cols_index= 0;
option_cleanup(str);
}
if (auto_generate_sql)
{
unsigned long long x= 0;
statement *ptr_statement;
if (verbose >= 2)
printf("Building Create Statements for Auto\n");
create_statements= build_table_string();
/*
Pre-populate table
*/
for (ptr_statement= create_statements, x= 0;
x < auto_generate_sql_unique_write_number;
x++, ptr_statement= ptr_statement->next)
{
ptr_statement->next= build_insert_string();
}
if (verbose >= 2)
printf("Building Query Statements for Auto\n");
if (auto_generate_sql_type[0] == 'r')
{
if (verbose >= 2)
printf("Generating SELECT Statements for Auto\n");
query_statements= build_select_string(FALSE);
for (ptr_statement= query_statements, x= 0;
x < auto_generate_sql_unique_query_number;
x++, ptr_statement= ptr_statement->next)
{
ptr_statement->next= build_select_string(FALSE);
}
}
else if (auto_generate_sql_type[0] == 'k')
{
if (verbose >= 2)
printf("Generating SELECT for keys Statements for Auto\n");
query_statements= build_select_string(TRUE);
for (ptr_statement= query_statements, x= 0;
x < auto_generate_sql_unique_query_number;
x++, ptr_statement= ptr_statement->next)
{
ptr_statement->next= build_select_string(TRUE);
}
}
else if (auto_generate_sql_type[0] == 'w')
{
/*
We generate a number of strings in case the engine is
Archive (since strings which were identical one after another
would be too easily optimized).
*/
if (verbose >= 2)
printf("Generating INSERT Statements for Auto\n");
query_statements= build_insert_string();
for (ptr_statement= query_statements, x= 0;
x < auto_generate_sql_unique_query_number;
x++, ptr_statement= ptr_statement->next)
{
ptr_statement->next= build_insert_string();
}
}
else if (auto_generate_sql_type[0] == 'u')
{
query_statements= build_update_string();
for (ptr_statement= query_statements, x= 0;
x < auto_generate_sql_unique_query_number;
x++, ptr_statement= ptr_statement->next)
{
ptr_statement->next= build_update_string();
}
}
else /* Mixed mode is default */
{
int coin= 0;
query_statements= build_insert_string();
/*
This logic should be extended to do a more mixed load,
at the moment it results in "every other".
*/
for (ptr_statement= query_statements, x= 0;
x < auto_generate_sql_unique_query_number;
x++, ptr_statement= ptr_statement->next)
{
if (coin)
{
ptr_statement->next= build_insert_string();
coin= 0;
}
else
{
ptr_statement->next= build_select_string(TRUE);
coin= 1;
}
}
}
}
else
{
if (create_string && my_stat(create_string, &sbuf, MYF(0)))
{
File data_file;
if (!MY_S_ISREG(sbuf.st_mode))
{
fprintf(stderr,"%s: Create file was not a regular file\n",
my_progname);
exit(1);
}
if ((data_file= my_open(create_string, O_RDWR, MYF(0))) == -1)
{
fprintf(stderr,"%s: Could not open create file\n", my_progname);
exit(1);
}
tmp_string= (char *)my_malloc(PSI_NOT_INSTRUMENTED,
sbuf.st_size + 1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
my_read(data_file, (uchar*) tmp_string, sbuf.st_size, MYF(0));
tmp_string[sbuf.st_size]= '\0';
my_close(data_file,MYF(0));
parse_delimiter(tmp_string, &create_statements, delimiter[0]);
my_free(tmp_string);
}
else if (create_string)
{
parse_delimiter(create_string, &create_statements, delimiter[0]);
}
if (user_supplied_query && my_stat(user_supplied_query, &sbuf, MYF(0)))
{
File data_file;
if (!MY_S_ISREG(sbuf.st_mode))
{
fprintf(stderr,"%s: User query supplied file was not a regular file\n",
my_progname);
exit(1);
}
if ((data_file= my_open(user_supplied_query, O_RDWR, MYF(0))) == -1)
{
fprintf(stderr,"%s: Could not open query supplied file\n", my_progname);
exit(1);
}
tmp_string= (char *)my_malloc(PSI_NOT_INSTRUMENTED,
sbuf.st_size + 1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
my_read(data_file, (uchar*) tmp_string, sbuf.st_size, MYF(0));
tmp_string[sbuf.st_size]= '\0';
my_close(data_file,MYF(0));
if (user_supplied_query)
actual_queries= parse_delimiter(tmp_string, &query_statements,
delimiter[0]);
my_free(tmp_string);
}
else if (user_supplied_query)
{
actual_queries= parse_delimiter(user_supplied_query, &query_statements,
delimiter[0]);
}
}
if (user_supplied_pre_statements && my_stat(user_supplied_pre_statements, &sbuf, MYF(0)))
{
File data_file;
if (!MY_S_ISREG(sbuf.st_mode))
{
fprintf(stderr,"%s: User query supplied file was not a regular file\n",
my_progname);
exit(1);
}
if ((data_file= my_open(user_supplied_pre_statements, O_RDWR, MYF(0))) == -1)
{
fprintf(stderr,"%s: Could not open query supplied file\n", my_progname);
exit(1);
}
tmp_string= (char *)my_malloc(PSI_NOT_INSTRUMENTED,
sbuf.st_size + 1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
my_read(data_file, (uchar*) tmp_string, sbuf.st_size, MYF(0));
tmp_string[sbuf.st_size]= '\0';
my_close(data_file,MYF(0));
if (user_supplied_pre_statements)
(void)parse_delimiter(tmp_string, &pre_statements,
delimiter[0]);
my_free(tmp_string);
}
else if (user_supplied_pre_statements)
{
(void)parse_delimiter(user_supplied_pre_statements,
&pre_statements,
delimiter[0]);
}
if (user_supplied_post_statements && my_stat(user_supplied_post_statements, &sbuf, MYF(0)))
{
File data_file;
if (!MY_S_ISREG(sbuf.st_mode))
{
fprintf(stderr,"%s: User query supplied file was not a regular file\n",
my_progname);
exit(1);
}
if ((data_file= my_open(user_supplied_post_statements, O_RDWR, MYF(0))) == -1)
{
fprintf(stderr,"%s: Could not open query supplied file\n", my_progname);
exit(1);
}
tmp_string= (char *)my_malloc(PSI_NOT_INSTRUMENTED,
sbuf.st_size + 1,
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
my_read(data_file, (uchar*) tmp_string, sbuf.st_size, MYF(0));
tmp_string[sbuf.st_size]= '\0';
my_close(data_file,MYF(0));
if (user_supplied_post_statements)
(void)parse_delimiter(tmp_string, &post_statements,
delimiter[0]);
my_free(tmp_string);
}
else if (user_supplied_post_statements)
{
(void)parse_delimiter(user_supplied_post_statements, &post_statements,
delimiter[0]);
}
if (verbose >= 2)
printf("Parsing engines to use.\n");
if (default_engine)
parse_option(default_engine, &engine_options, ',');
if (tty_password)
opt_password= get_tty_password(NullS);
DBUG_RETURN(0);
}
static int run_query(MYSQL *mysql, const char *query, int len)
{
if (opt_only_print)
{
printf("%.*s;\n", len, query);
return 0;
}
if (verbose >= 3)
printf("%.*s;\n", len, query);
return mysql_real_query(mysql, query, len);
}
static int
generate_primary_key_list(MYSQL *mysql, option_string *engine_stmt)
{
MYSQL_RES *result;
MYSQL_ROW row;
unsigned long long counter;
DBUG_ENTER("generate_primary_key_list");
/*
Blackhole is a special case, this allows us to test the upper end
of the server during load runs.
*/
if (opt_only_print || (engine_stmt &&
strstr(engine_stmt->string, "blackhole")))
{
primary_keys_number_of= 1;
primary_keys= (char **)my_malloc(PSI_NOT_INSTRUMENTED,
(uint)(sizeof(char *) *
primary_keys_number_of),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
/* Yes, we strdup a const string to simplify the interface */
primary_keys[0]= my_strdup(PSI_NOT_INSTRUMENTED,
"796c4422-1d94-102a-9d6d-00e0812d", MYF(0));
}
else
{
if (run_query(mysql, "SELECT id from t1", strlen("SELECT id from t1")))
{
fprintf(stderr,"%s: Cannot select GUID primary keys. (%s)\n", my_progname,
mysql_error(mysql));
exit(1);
}
if (!(result= mysql_store_result(mysql)))
{
fprintf(stderr, "%s: Error when storing result: %d %s\n",
my_progname, mysql_errno(mysql), mysql_error(mysql));
exit(1);
}
primary_keys_number_of= mysql_num_rows(result);
/* So why check this? Blackhole :) */
if (primary_keys_number_of)
{
/*
We create the structure and loop and create the items.
*/
primary_keys= (char **)my_malloc(PSI_NOT_INSTRUMENTED,
(uint)(sizeof(char *) *
primary_keys_number_of),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
row= mysql_fetch_row(result);
for (counter= 0; counter < primary_keys_number_of;
counter++, row= mysql_fetch_row(result))
primary_keys[counter]= my_strdup(PSI_NOT_INSTRUMENTED,
row[0], MYF(0));
}
mysql_free_result(result);
}
DBUG_RETURN(0);
}
static int
drop_primary_key_list(void)
{
unsigned long long counter;
if (primary_keys_number_of)
{
for (counter= 0; counter < primary_keys_number_of; counter++)
my_free(primary_keys[counter]);
my_free(primary_keys);
}
return 0;
}
static int
create_schema(MYSQL *mysql, const char *db, statement *stmt,
option_string *engine_stmt)
{
char query[HUGE_STRING_LENGTH];
statement *ptr;
statement *after_create;
int len;
ulonglong count;
DBUG_ENTER("create_schema");
len= snprintf(query, HUGE_STRING_LENGTH, "CREATE SCHEMA `%s`", db);
if (verbose >= 2)
printf("Loading Pre-data\n");
if (run_query(mysql, query, len))
{
fprintf(stderr,"%s: Cannot create schema %s : %s\n", my_progname, db,
mysql_error(mysql));
exit(1);
}
if (opt_only_print)
{
printf("use %s;\n", db);
}
else
{
if (verbose >= 3)
printf("%s;\n", query);
if (mysql_select_db(mysql, db))
{
fprintf(stderr,"%s: Cannot select schema '%s': %s\n",my_progname, db,
mysql_error(mysql));
exit(1);
}
}
if (engine_stmt)
{
len= snprintf(query, HUGE_STRING_LENGTH, "set storage_engine=`%s`",
engine_stmt->string);
if (run_query(mysql, query, len))
{
fprintf(stderr,"%s: Cannot set default engine: %s\n", my_progname,
mysql_error(mysql));
exit(1);
}
}
count= 0;
after_create= stmt;
limit_not_met:
for (ptr= after_create; ptr && ptr->length; ptr= ptr->next, count++)
{
if (auto_generate_sql && ( auto_generate_sql_number == count))
break;
if (engine_stmt && engine_stmt->option && ptr->type == CREATE_TABLE_TYPE)
{
char buffer[HUGE_STRING_LENGTH];
snprintf(buffer, HUGE_STRING_LENGTH, "%s %s", ptr->string,
engine_stmt->option);
if (run_query(mysql, buffer, strlen(buffer)))
{
fprintf(stderr,"%s: Cannot run query %.*s ERROR : %s\n",
my_progname, (uint)ptr->length, ptr->string, mysql_error(mysql));
exit(1);
}
}
else
{
if (run_query(mysql, ptr->string, ptr->length))
{
fprintf(stderr,"%s: Cannot run query %.*s ERROR : %s\n",
my_progname, (uint)ptr->length, ptr->string, mysql_error(mysql));
exit(1);
}
}
}
if (auto_generate_sql && (auto_generate_sql_number > count ))
{
/* Special case for auto create, we don't want to create tables twice */
after_create= stmt->next;
goto limit_not_met;
}
DBUG_RETURN(0);
}
static int
drop_schema(MYSQL *mysql, const char *db)
{
char query[HUGE_STRING_LENGTH];
int len;
DBUG_ENTER("drop_schema");
len= snprintf(query, HUGE_STRING_LENGTH, "DROP SCHEMA IF EXISTS `%s`", db);
if (run_query(mysql, query, len))
{
fprintf(stderr,"%s: Cannot drop database '%s' ERROR : %s\n",
my_progname, db, mysql_error(mysql));
exit(1);
}
DBUG_RETURN(0);
}
static int
run_statements(MYSQL *mysql, statement *stmt)
{
statement *ptr;
MYSQL_RES *result;
DBUG_ENTER("run_statements");
for (ptr= stmt; ptr && ptr->length; ptr= ptr->next)
{
if (run_query(mysql, ptr->string, ptr->length))
{
fprintf(stderr,"%s: Cannot run query %.*s ERROR : %s\n",
my_progname, (uint)ptr->length, ptr->string, mysql_error(mysql));
exit(1);
}
if (mysql_field_count(mysql))
{
result= mysql_store_result(mysql);
mysql_free_result(result);
}
}
DBUG_RETURN(0);
}
static int
run_scheduler(stats *sptr, statement *stmts, uint concur, ulonglong limit)
{
uint x;
struct timeval start_time, end_time;
thread_context con;
pthread_t mainthread; /* Thread descriptor */
pthread_attr_t attr; /* Thread attributes */
DBUG_ENTER("run_scheduler");
con.stmt= stmts;
con.limit= limit;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,
PTHREAD_CREATE_DETACHED);
pthread_mutex_lock(&counter_mutex);
thread_counter= 0;
pthread_mutex_lock(&sleeper_mutex);
master_wakeup= 1;
pthread_mutex_unlock(&sleeper_mutex);
for (x= 0; x < concur; x++)
{
/* now you create the thread */
if (pthread_create(&mainthread, &attr, run_task,
(void *)&con) != 0)
{
fprintf(stderr,"%s: Could not create thread\n",
my_progname);
exit(0);
}
thread_counter++;
}
pthread_mutex_unlock(&counter_mutex);
pthread_attr_destroy(&attr);
pthread_mutex_lock(&sleeper_mutex);
master_wakeup= 0;
pthread_mutex_unlock(&sleeper_mutex);
pthread_cond_broadcast(&sleep_threshhold);
gettimeofday(&start_time, NULL);
/*
We loop until we know that all children have cleaned up.
*/
pthread_mutex_lock(&counter_mutex);
while (thread_counter)
{
struct timespec abstime;
set_timespec(abstime, 3);
pthread_cond_timedwait(&count_threshhold, &counter_mutex, &abstime);
}
pthread_mutex_unlock(&counter_mutex);
gettimeofday(&end_time, NULL);
sptr->timing= timedif(end_time, start_time);
sptr->users= concur;
sptr->rows= limit;
DBUG_RETURN(0);
}
pthread_handler_t run_task(void *p)
{
ulonglong counter= 0, queries;
ulonglong detach_counter;
unsigned int commit_counter;
MYSQL *mysql;
MYSQL_RES *result;
MYSQL_ROW row;
statement *ptr;
thread_context *con= (thread_context *)p;
DBUG_ENTER("run_task");
DBUG_PRINT("info", ("task script \"%s\"", con->stmt ? con->stmt->string : ""));
pthread_mutex_lock(&sleeper_mutex);
while (master_wakeup)
{
pthread_cond_wait(&sleep_threshhold, &sleeper_mutex);
}
pthread_mutex_unlock(&sleeper_mutex);
if (!(mysql= mysql_init(NULL)))
{
fprintf(stderr,"%s: mysql_init() failed ERROR : %s\n",
my_progname, mysql_error(mysql));
exit(0);
}
if (mysql_thread_init())
{
fprintf(stderr,"%s: mysql_thread_init() failed ERROR : %s\n",
my_progname, mysql_error(mysql));
exit(0);
}
DBUG_PRINT("info", ("trying to connect to host %s as user %s", host, user));
if (!opt_only_print)
{
if (slap_connect(mysql))
goto end;
}
DBUG_PRINT("info", ("connected."));
if (verbose >= 3)
printf("connected!\n");
queries= 0;
commit_counter= 0;
if (commit_rate)
run_query(mysql, "SET AUTOCOMMIT=0", strlen("SET AUTOCOMMIT=0"));
limit_not_met:
for (ptr= con->stmt, detach_counter= 0;
ptr && ptr->length;
ptr= ptr->next, detach_counter++)
{
if (!opt_only_print && detach_rate && !(detach_counter % detach_rate))
{
mysql_close(mysql);
if (!(mysql= mysql_init(NULL)))
{
fprintf(stderr,"%s: mysql_init() failed ERROR : %s\n",
my_progname, mysql_error(mysql));
exit(0);
}
if (slap_connect(mysql))
goto end;
}
/*
We have to execute differently based on query type. This should become a function.
*/
if ((ptr->type == UPDATE_TYPE_REQUIRES_PREFIX) ||
(ptr->type == SELECT_TYPE_REQUIRES_PREFIX))
{
int length;
unsigned int key_val;
char *key;
char buffer[HUGE_STRING_LENGTH];
/*
This should only happen if some sort of new engine was
implemented that didn't properly handle UPDATEs.
Just in case someone runs this under an experimental engine we don't
want a crash so the if() is placed here.
*/
DBUG_ASSERT(primary_keys_number_of);
if (primary_keys_number_of)
{
key_val= (unsigned int)(random() % primary_keys_number_of);
key= primary_keys[key_val];
DBUG_ASSERT(key);
length= snprintf(buffer, HUGE_STRING_LENGTH, "%.*s '%s'",
(int)ptr->length, ptr->string, key);
if (run_query(mysql, buffer, length))
{
fprintf(stderr,"%s: Cannot run query %.*s ERROR : %s\n",
my_progname, (uint)length, buffer, mysql_error(mysql));
exit(0);
}
}
}
else
{
if (run_query(mysql, ptr->string, ptr->length))
{
fprintf(stderr,"%s: Cannot run query %.*s ERROR : %s\n",
my_progname, (uint)ptr->length, ptr->string, mysql_error(mysql));
exit(0);
}
}
do
{
if (mysql_field_count(mysql))
{
if (!(result= mysql_store_result(mysql)))
fprintf(stderr, "%s: Error when storing result: %d %s\n",
my_progname, mysql_errno(mysql), mysql_error(mysql));
else
{
while ((row= mysql_fetch_row(result)))
counter++;
mysql_free_result(result);
}
}
} while(mysql_next_result(mysql) == 0);
queries++;
if (commit_rate && (++commit_counter == commit_rate))
{
commit_counter= 0;
run_query(mysql, "COMMIT", strlen("COMMIT"));
}
if (con->limit && queries == con->limit)
goto end;
}
if (con->limit && queries < con->limit)
goto limit_not_met;
end:
if (commit_rate)
run_query(mysql, "COMMIT", strlen("COMMIT"));
if (!opt_only_print)
mysql_close(mysql);
mysql_thread_end();
pthread_mutex_lock(&counter_mutex);
thread_counter--;
pthread_cond_signal(&count_threshhold);
pthread_mutex_unlock(&counter_mutex);
DBUG_RETURN(0);
}
uint
parse_option(const char *origin, option_string **stmt, char delm)
{
char *retstr;
char *ptr= (char *)origin;
option_string **sptr= stmt;
option_string *tmp;
size_t length= strlen(origin);
uint count= 0; /* We know that there is always one */
for (tmp= *sptr= (option_string *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(option_string),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
(retstr= strchr(ptr, delm));
tmp->next= (option_string *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(option_string),
MYF(MY_ZEROFILL|MY_FAE|MY_WME)),
tmp= tmp->next)
{
char buffer[HUGE_STRING_LENGTH];
char *buffer_ptr;
count++;
strncpy(buffer, ptr, (size_t)(retstr - ptr));
if ((buffer_ptr= strchr(buffer, ':')))
{
char *option_ptr;
tmp->length= (size_t)(buffer_ptr - buffer);
tmp->string= my_strndup(PSI_NOT_INSTRUMENTED,
ptr, (uint)tmp->length, MYF(MY_FAE));
option_ptr= ptr + 1 + tmp->length;
/* Move past the : and the first string */
tmp->option_length= (size_t)(retstr - option_ptr);
tmp->option= my_strndup(PSI_NOT_INSTRUMENTED,
option_ptr, (uint)tmp->option_length,
MYF(MY_FAE));
}
else
{
tmp->string= my_strndup(PSI_NOT_INSTRUMENTED,
ptr, (size_t)(retstr - ptr), MYF(MY_FAE));
tmp->length= (size_t)(retstr - ptr);
}
ptr+= retstr - ptr + 1;
if (isspace(*ptr))
ptr++;
count++;
}
if (ptr != origin+length)
{
char *origin_ptr;
if ((origin_ptr= strchr(ptr, ':')))
{
char *option_ptr;
tmp->length= (size_t)(origin_ptr - ptr);
tmp->string= my_strndup(PSI_NOT_INSTRUMENTED,
origin, tmp->length, MYF(MY_FAE));
option_ptr= (char *)ptr + 1 + tmp->length;
/* Move past the : and the first string */
tmp->option_length= (size_t)((ptr + length) - option_ptr);
tmp->option= my_strndup(PSI_NOT_INSTRUMENTED,
option_ptr, tmp->option_length,
MYF(MY_FAE));
}
else
{
tmp->length= (size_t)((ptr + length) - ptr);
tmp->string= my_strndup(PSI_NOT_INSTRUMENTED,
ptr, tmp->length, MYF(MY_FAE));
}
count++;
}
return count;
}
uint
parse_delimiter(const char *script, statement **stmt, char delm)
{
char *retstr;
char *ptr= (char *)script;
statement **sptr= stmt;
statement *tmp;
uint length= strlen(script);
uint count= 0; /* We know that there is always one */
for (tmp= *sptr= (statement *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(statement),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
(retstr= strchr(ptr, delm));
tmp->next= (statement *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(statement),
MYF(MY_ZEROFILL|MY_FAE|MY_WME)),
tmp= tmp->next)
{
count++;
tmp->string= my_strndup(PSI_NOT_INSTRUMENTED,
ptr, (uint)(retstr - ptr), MYF(MY_FAE));
tmp->length= (size_t)(retstr - ptr);
ptr+= retstr - ptr + 1;
if (isspace(*ptr))
ptr++;
}
if (ptr != script+length)
{
tmp->string= my_strndup(PSI_NOT_INSTRUMENTED,
ptr, (uint)((script + length) - ptr),
MYF(MY_FAE));
tmp->length= (size_t)((script + length) - ptr);
count++;
}
return count;
}
uint
parse_comma(const char *string, uint **range)
{
uint count= 1,x; /* We know that there is always one */
char *retstr;
char *ptr= (char *)string;
uint *nptr;
for (;*ptr; ptr++)
if (*ptr == ',') count++;
/* One extra spot for the NULL */
nptr= *range= (uint *)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(uint) * (count + 1),
MYF(MY_ZEROFILL|MY_FAE|MY_WME));
ptr= (char *)string;
x= 0;
while ((retstr= strchr(ptr,',')))
{
nptr[x++]= atoi(ptr);
ptr+= retstr - ptr + 1;
}
nptr[x++]= atoi(ptr);
return count;
}
void
print_conclusions(conclusions *con)
{
printf("Benchmark\n");
if (con->engine)
printf("\tRunning for engine %s\n", con->engine);
printf("\tAverage number of seconds to run all queries: %ld.%03ld seconds\n",
con->avg_timing / 1000, con->avg_timing % 1000);
printf("\tMinimum number of seconds to run all queries: %ld.%03ld seconds\n",
con->min_timing / 1000, con->min_timing % 1000);
printf("\tMaximum number of seconds to run all queries: %ld.%03ld seconds\n",
con->max_timing / 1000, con->max_timing % 1000);
printf("\tNumber of clients running queries: %d\n", con->users);
printf("\tAverage number of queries per client: %llu\n", con->avg_rows);
printf("\n");
}
void
print_conclusions_csv(conclusions *con)
{
char buffer[HUGE_STRING_LENGTH];
const char *ptr= auto_generate_sql_type ? auto_generate_sql_type : "query";
snprintf(buffer, HUGE_STRING_LENGTH,
"%s,%s,%ld.%03ld,%ld.%03ld,%ld.%03ld,%d,%llu\n",
con->engine ? con->engine : "", /* Storage engine we ran against */
ptr, /* Load type */
con->avg_timing / 1000, con->avg_timing % 1000, /* Time to load */
con->min_timing / 1000, con->min_timing % 1000, /* Min time */
con->max_timing / 1000, con->max_timing % 1000, /* Max time */
con->users, /* Children used */
con->avg_rows /* Queries run */
);
my_write(csv_file, (uchar*) buffer, (uint)strlen(buffer), MYF(0));
}
void
generate_stats(conclusions *con, option_string *eng, stats *sptr)
{
stats *ptr;
unsigned int x;
con->min_timing= sptr->timing;
con->max_timing= sptr->timing;
con->min_rows= sptr->rows;
con->max_rows= sptr->rows;
/* At the moment we assume uniform */
con->users= sptr->users;
con->avg_rows= sptr->rows;
/* With no next, we know it is the last element that was malloced */
for (ptr= sptr, x= 0; x < iterations; ptr++, x++)
{
con->avg_timing+= ptr->timing;
if (ptr->timing > con->max_timing)
con->max_timing= ptr->timing;
if (ptr->timing < con->min_timing)
con->min_timing= ptr->timing;
}
con->avg_timing= con->avg_timing/iterations;
if (eng && eng->string)
con->engine= eng->string;
else
con->engine= NULL;
}
void
option_cleanup(option_string *stmt)
{
option_string *ptr, *nptr;
if (!stmt)
return;
for (ptr= stmt; ptr; ptr= nptr)
{
nptr= ptr->next;
my_free(ptr->string);
my_free(ptr->option);
my_free(ptr);
}
}
void
statement_cleanup(statement *stmt)
{
statement *ptr, *nptr;
if (!stmt)
return;
for (ptr= stmt; ptr; ptr= nptr)
{
nptr= ptr->next;
my_free(ptr->string);
my_free(ptr);
}
}
int
slap_connect(MYSQL *mysql)
{
/* Connect to server */
static ulong connection_retry_sleep= 100000; /* Microseconds */
int x, connect_error= 1;
for (x= 0; x < 10; x++)
{
if (mysql_real_connect(mysql, host, user, opt_password,
create_schema_string,
opt_mysql_port,
opt_mysql_unix_port,
connect_flags))
{
/* Connect suceeded */
connect_error= 0;
break;
}
my_sleep(connection_retry_sleep);
}
if (connect_error)
{
fprintf(stderr,"%s: Error when connecting to server: %d %s\n",
my_progname, mysql_errno(mysql), mysql_error(mysql));
return 1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-284/c/bad_1571_9 |
crossvul-cpp_data_good_4896_1 | /*
* Process version 3 NFSACL requests.
*
* Copyright (C) 2002-2003 Andreas Gruenbacher <agruen@suse.de>
*/
#include "nfsd.h"
/* FIXME: nfsacl.h is a broken header */
#include <linux/nfsacl.h>
#include <linux/gfp.h>
#include "cache.h"
#include "xdr3.h"
#include "vfs.h"
#define RETURN_STATUS(st) { resp->status = (st); return (st); }
/*
* NULL call.
*/
static __be32
nfsd3_proc_null(struct svc_rqst *rqstp, void *argp, void *resp)
{
return nfs_ok;
}
/*
* Get the Access and/or Default ACL of a file.
*/
static __be32 nfsd3_proc_getacl(struct svc_rqst * rqstp,
struct nfsd3_getaclargs *argp, struct nfsd3_getaclres *resp)
{
struct posix_acl *acl;
struct inode *inode;
svc_fh *fh;
__be32 nfserr = 0;
fh = fh_copy(&resp->fh, &argp->fh);
nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP);
if (nfserr)
RETURN_STATUS(nfserr);
inode = d_inode(fh->fh_dentry);
if (argp->mask & ~NFS_ACL_MASK)
RETURN_STATUS(nfserr_inval);
resp->mask = argp->mask;
if (resp->mask & (NFS_ACL|NFS_ACLCNT)) {
acl = get_acl(inode, ACL_TYPE_ACCESS);
if (acl == NULL) {
/* Solaris returns the inode's minimum ACL. */
acl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL);
}
if (IS_ERR(acl)) {
nfserr = nfserrno(PTR_ERR(acl));
goto fail;
}
resp->acl_access = acl;
}
if (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) {
/* Check how Solaris handles requests for the Default ACL
of a non-directory! */
acl = get_acl(inode, ACL_TYPE_DEFAULT);
if (IS_ERR(acl)) {
nfserr = nfserrno(PTR_ERR(acl));
goto fail;
}
resp->acl_default = acl;
}
/* resp->acl_{access,default} are released in nfs3svc_release_getacl. */
RETURN_STATUS(0);
fail:
posix_acl_release(resp->acl_access);
posix_acl_release(resp->acl_default);
RETURN_STATUS(nfserr);
}
/*
* Set the Access and/or Default ACL of a file.
*/
static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp,
struct nfsd3_setaclargs *argp,
struct nfsd3_attrstat *resp)
{
struct inode *inode;
svc_fh *fh;
__be32 nfserr = 0;
int error;
fh = fh_copy(&resp->fh, &argp->fh);
nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR);
if (nfserr)
goto out;
inode = d_inode(fh->fh_dentry);
error = fh_want_write(fh);
if (error)
goto out_errno;
fh_lock(fh);
error = set_posix_acl(inode, ACL_TYPE_ACCESS, argp->acl_access);
if (error)
goto out_drop_lock;
error = set_posix_acl(inode, ACL_TYPE_DEFAULT, argp->acl_default);
out_drop_lock:
fh_unlock(fh);
fh_drop_write(fh);
out_errno:
nfserr = nfserrno(error);
out:
/* argp->acl_{access,default} may have been allocated in
nfs3svc_decode_setaclargs. */
posix_acl_release(argp->acl_access);
posix_acl_release(argp->acl_default);
RETURN_STATUS(nfserr);
}
/*
* XDR decode functions
*/
static int nfs3svc_decode_getaclargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_getaclargs *args)
{
p = nfs3svc_decode_fh(p, &args->fh);
if (!p)
return 0;
args->mask = ntohl(*p); p++;
return xdr_argsize_check(rqstp, p);
}
static int nfs3svc_decode_setaclargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_setaclargs *args)
{
struct kvec *head = rqstp->rq_arg.head;
unsigned int base;
int n;
p = nfs3svc_decode_fh(p, &args->fh);
if (!p)
return 0;
args->mask = ntohl(*p++);
if (args->mask & ~NFS_ACL_MASK ||
!xdr_argsize_check(rqstp, p))
return 0;
base = (char *)p - (char *)head->iov_base;
n = nfsacl_decode(&rqstp->rq_arg, base, NULL,
(args->mask & NFS_ACL) ?
&args->acl_access : NULL);
if (n > 0)
n = nfsacl_decode(&rqstp->rq_arg, base + n, NULL,
(args->mask & NFS_DFACL) ?
&args->acl_default : NULL);
return (n > 0);
}
/*
* XDR encode functions
*/
/* GETACL */
static int nfs3svc_encode_getaclres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_getaclres *resp)
{
struct dentry *dentry = resp->fh.fh_dentry;
p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh);
if (resp->status == 0 && dentry && d_really_is_positive(dentry)) {
struct inode *inode = d_inode(dentry);
struct kvec *head = rqstp->rq_res.head;
unsigned int base;
int n;
int w;
*p++ = htonl(resp->mask);
if (!xdr_ressize_check(rqstp, p))
return 0;
base = (char *)p - (char *)head->iov_base;
rqstp->rq_res.page_len = w = nfsacl_size(
(resp->mask & NFS_ACL) ? resp->acl_access : NULL,
(resp->mask & NFS_DFACL) ? resp->acl_default : NULL);
while (w > 0) {
if (!*(rqstp->rq_next_page++))
return 0;
w -= PAGE_SIZE;
}
n = nfsacl_encode(&rqstp->rq_res, base, inode,
resp->acl_access,
resp->mask & NFS_ACL, 0);
if (n > 0)
n = nfsacl_encode(&rqstp->rq_res, base + n, inode,
resp->acl_default,
resp->mask & NFS_DFACL,
NFS_ACL_DEFAULT);
if (n <= 0)
return 0;
} else
if (!xdr_ressize_check(rqstp, p))
return 0;
return 1;
}
/* SETACL */
static int nfs3svc_encode_setaclres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_attrstat *resp)
{
p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh);
return xdr_ressize_check(rqstp, p);
}
/*
* XDR release functions
*/
static int nfs3svc_release_getacl(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_getaclres *resp)
{
fh_put(&resp->fh);
posix_acl_release(resp->acl_access);
posix_acl_release(resp->acl_default);
return 1;
}
#define nfs3svc_decode_voidargs NULL
#define nfs3svc_release_void NULL
#define nfsd3_setaclres nfsd3_attrstat
#define nfsd3_voidres nfsd3_voidargs
struct nfsd3_voidargs { int dummy; };
#define PROC(name, argt, rest, relt, cache, respsize) \
{ (svc_procfunc) nfsd3_proc_##name, \
(kxdrproc_t) nfs3svc_decode_##argt##args, \
(kxdrproc_t) nfs3svc_encode_##rest##res, \
(kxdrproc_t) nfs3svc_release_##relt, \
sizeof(struct nfsd3_##argt##args), \
sizeof(struct nfsd3_##rest##res), \
0, \
cache, \
respsize, \
}
#define ST 1 /* status*/
#define AT 21 /* attributes */
#define pAT (1+AT) /* post attributes - conditional */
#define ACL (1+NFS_ACL_MAX_ENTRIES*3) /* Access Control List */
static struct svc_procedure nfsd_acl_procedures3[] = {
PROC(null, void, void, void, RC_NOCACHE, ST),
PROC(getacl, getacl, getacl, getacl, RC_NOCACHE, ST+1+2*(1+ACL)),
PROC(setacl, setacl, setacl, fhandle, RC_NOCACHE, ST+pAT),
};
struct svc_version nfsd_acl_version3 = {
.vs_vers = 3,
.vs_nproc = 3,
.vs_proc = nfsd_acl_procedures3,
.vs_dispatch = nfsd_dispatch,
.vs_xdrsize = NFS3_SVC_XDRSIZE,
.vs_hidden = 0,
};
| ./CrossVul/dataset_final_sorted/CWE-284/c/good_4896_1 |
crossvul-cpp_data_good_4786_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M EEEEE M M OOO RRRR Y Y %
% MM MM E MM MM O O R R Y Y %
% M M M EEE M M M O O RRRR Y %
% M M E M M O O R R Y %
% M M EEEEE M M OOO R R Y %
% %
% %
% MagickCore Memory Allocation Methods %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Segregate our memory requirements from any program that calls our API. This
% should help reduce the risk of others changing our program state or causing
% memory corruption.
%
% Our custom memory allocation manager implements a best-fit allocation policy
% using segregated free lists. It uses a linear distribution of size classes
% for lower sizes and a power of two distribution of size classes at higher
% sizes. It is based on the paper, "Fast Memory Allocation using Lazy Fits."
% written by Yoo C. Chung.
%
% By default, ANSI memory methods are called (e.g. malloc). Use the
% custom memory allocator by defining MAGICKCORE_ZERO_CONFIGURATION_SUPPORT
% to allocate memory with private anonymous mapping rather than from the
% heap.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/string_.h"
#include "MagickCore/utility-private.h"
/*
Define declarations.
*/
#define BlockFooter(block,size) \
((size_t *) ((char *) (block)+(size)-2*sizeof(size_t)))
#define BlockHeader(block) ((size_t *) (block)-1)
#define BlockSize 4096
#define BlockThreshold 1024
#define MaxBlockExponent 16
#define MaxBlocks ((BlockThreshold/(4*sizeof(size_t)))+MaxBlockExponent+1)
#define MaxSegments 1024
#define MemoryGuard ((0xdeadbeef << 31)+0xdeafdeed)
#define NextBlock(block) ((char *) (block)+SizeOfBlock(block))
#define NextBlockInList(block) (*(void **) (block))
#define PreviousBlock(block) ((char *) (block)-(*((size_t *) (block)-2)))
#define PreviousBlockBit 0x01
#define PreviousBlockInList(block) (*((void **) (block)+1))
#define SegmentSize (2*1024*1024)
#define SizeMask (~0x01)
#define SizeOfBlock(block) (*BlockHeader(block) & SizeMask)
/*
Typedef declarations.
*/
typedef enum
{
UndefinedVirtualMemory,
AlignedVirtualMemory,
MapVirtualMemory,
UnalignedVirtualMemory
} VirtualMemoryType;
typedef struct _DataSegmentInfo
{
void
*allocation,
*bound;
MagickBooleanType
mapped;
size_t
length;
struct _DataSegmentInfo
*previous,
*next;
} DataSegmentInfo;
typedef struct _MagickMemoryMethods
{
AcquireMemoryHandler
acquire_memory_handler;
ResizeMemoryHandler
resize_memory_handler;
DestroyMemoryHandler
destroy_memory_handler;
} MagickMemoryMethods;
struct _MemoryInfo
{
char
filename[MagickPathExtent];
VirtualMemoryType
type;
size_t
length;
void
*blob;
size_t
signature;
};
typedef struct _MemoryPool
{
size_t
allocation;
void
*blocks[MaxBlocks+1];
size_t
number_segments;
DataSegmentInfo
*segments[MaxSegments],
segment_pool[MaxSegments];
} MemoryPool;
/*
Global declarations.
*/
#if defined _MSC_VER
static void* MSCMalloc(size_t size)
{
return malloc(size);
}
static void* MSCRealloc(void* ptr, size_t size)
{
return realloc(ptr, size);
}
static void MSCFree(void* ptr)
{
free(ptr);
}
#endif
static MagickMemoryMethods
memory_methods =
{
#if defined _MSC_VER
(AcquireMemoryHandler) MSCMalloc,
(ResizeMemoryHandler) MSCRealloc,
(DestroyMemoryHandler) MSCFree
#else
(AcquireMemoryHandler) malloc,
(ResizeMemoryHandler) realloc,
(DestroyMemoryHandler) free
#endif
};
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
static MemoryPool
memory_pool;
static SemaphoreInfo
*memory_semaphore = (SemaphoreInfo *) NULL;
static volatile DataSegmentInfo
*free_segments = (DataSegmentInfo *) NULL;
/*
Forward declarations.
*/
static MagickBooleanType
ExpandHeap(size_t);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e A l i g n e d M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireAlignedMemory() returns a pointer to a block of memory at least size
% bytes whose address is a multiple of 16*sizeof(void *).
%
% The format of the AcquireAlignedMemory method is:
%
% void *AcquireAlignedMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
static MagickBooleanType CheckMemoryOverflow(const size_t count,
const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
errno=ENOMEM;
return(MagickTrue);
}
return(MagickFalse);
}
MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum)
{
#define AlignedExtent(size,alignment) \
(((size)+((alignment)-1)) & ~((alignment)-1))
size_t
alignment,
extent,
size;
void
*memory;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((void *) NULL);
memory=NULL;
alignment=CACHE_LINE_SIZE;
size=count*quantum;
extent=AlignedExtent(size,alignment);
if ((size == 0) || (alignment < sizeof(void *)) || (extent < size))
return((void *) NULL);
#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
if (posix_memalign(&memory,alignment,extent) != 0)
memory=NULL;
#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
memory=_aligned_malloc(extent,alignment);
#else
{
void
*p;
extent=(size+alignment-1)+sizeof(void *);
if (extent > size)
{
p=malloc(extent);
if (p != NULL)
{
memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment);
*((void **) memory-1)=p;
}
}
}
#endif
return(memory);
}
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e B l o c k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireBlock() returns a pointer to a block of memory at least size bytes
% suitably aligned for any use.
%
% The format of the AcquireBlock method is:
%
% void *AcquireBlock(const size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes to allocate.
%
*/
static inline size_t AllocationPolicy(size_t size)
{
register size_t
blocksize;
/*
The linear distribution.
*/
assert(size != 0);
assert(size % (4*sizeof(size_t)) == 0);
if (size <= BlockThreshold)
return(size/(4*sizeof(size_t)));
/*
Check for the largest block size.
*/
if (size > (size_t) (BlockThreshold*(1L << (MaxBlockExponent-1L))))
return(MaxBlocks-1L);
/*
Otherwise use a power of two distribution.
*/
blocksize=BlockThreshold/(4*sizeof(size_t));
for ( ; size > BlockThreshold; size/=2)
blocksize++;
assert(blocksize > (BlockThreshold/(4*sizeof(size_t))));
assert(blocksize < (MaxBlocks-1L));
return(blocksize);
}
static inline void InsertFreeBlock(void *block,const size_t i)
{
register void
*next,
*previous;
size_t
size;
size=SizeOfBlock(block);
previous=(void *) NULL;
next=memory_pool.blocks[i];
while ((next != (void *) NULL) && (SizeOfBlock(next) < size))
{
previous=next;
next=NextBlockInList(next);
}
PreviousBlockInList(block)=previous;
NextBlockInList(block)=next;
if (previous != (void *) NULL)
NextBlockInList(previous)=block;
else
memory_pool.blocks[i]=block;
if (next != (void *) NULL)
PreviousBlockInList(next)=block;
}
static inline void RemoveFreeBlock(void *block,const size_t i)
{
register void
*next,
*previous;
next=NextBlockInList(block);
previous=PreviousBlockInList(block);
if (previous == (void *) NULL)
memory_pool.blocks[i]=next;
else
NextBlockInList(previous)=next;
if (next != (void *) NULL)
PreviousBlockInList(next)=previous;
}
static void *AcquireBlock(size_t size)
{
register size_t
i;
register void
*block;
/*
Find free block.
*/
size=(size_t) (size+sizeof(size_t)+6*sizeof(size_t)-1) & -(4U*sizeof(size_t));
i=AllocationPolicy(size);
block=memory_pool.blocks[i];
while ((block != (void *) NULL) && (SizeOfBlock(block) < size))
block=NextBlockInList(block);
if (block == (void *) NULL)
{
i++;
while (memory_pool.blocks[i] == (void *) NULL)
i++;
block=memory_pool.blocks[i];
if (i >= MaxBlocks)
return((void *) NULL);
}
assert((*BlockHeader(NextBlock(block)) & PreviousBlockBit) == 0);
assert(SizeOfBlock(block) >= size);
RemoveFreeBlock(block,AllocationPolicy(SizeOfBlock(block)));
if (SizeOfBlock(block) > size)
{
size_t
blocksize;
void
*next;
/*
Split block.
*/
next=(char *) block+size;
blocksize=SizeOfBlock(block)-size;
*BlockHeader(next)=blocksize;
*BlockFooter(next,blocksize)=blocksize;
InsertFreeBlock(next,AllocationPolicy(blocksize));
*BlockHeader(block)=size | (*BlockHeader(block) & ~SizeMask);
}
assert(size == SizeOfBlock(block));
*BlockHeader(NextBlock(block))|=PreviousBlockBit;
memory_pool.allocation+=size;
return(block);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireMagickMemory() returns a pointer to a block of memory at least size
% bytes suitably aligned for any use.
%
% The format of the AcquireMagickMemory method is:
%
% void *AcquireMagickMemory(const size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes to allocate.
%
*/
MagickExport void *AcquireMagickMemory(const size_t size)
{
register void
*memory;
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
memory=memory_methods.acquire_memory_handler(size == 0 ? 1UL : size);
#else
if (memory_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&memory_semaphore);
if (free_segments == (DataSegmentInfo *) NULL)
{
LockSemaphoreInfo(memory_semaphore);
if (free_segments == (DataSegmentInfo *) NULL)
{
register ssize_t
i;
assert(2*sizeof(size_t) > (size_t) (~SizeMask));
(void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
memory_pool.allocation=SegmentSize;
memory_pool.blocks[MaxBlocks]=(void *) (-1);
for (i=0; i < MaxSegments; i++)
{
if (i != 0)
memory_pool.segment_pool[i].previous=
(&memory_pool.segment_pool[i-1]);
if (i != (MaxSegments-1))
memory_pool.segment_pool[i].next=(&memory_pool.segment_pool[i+1]);
}
free_segments=(&memory_pool.segment_pool[0]);
}
UnlockSemaphoreInfo(memory_semaphore);
}
LockSemaphoreInfo(memory_semaphore);
memory=AcquireBlock(size == 0 ? 1UL : size);
if (memory == (void *) NULL)
{
if (ExpandHeap(size == 0 ? 1UL : size) != MagickFalse)
memory=AcquireBlock(size == 0 ? 1UL : size);
}
UnlockSemaphoreInfo(memory_semaphore);
#endif
return(memory);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e Q u a n t u m M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireQuantumMemory() returns a pointer to a block of memory at least
% count * quantum bytes suitably aligned for any use.
%
% The format of the AcquireQuantumMemory method is:
%
% void *AcquireQuantumMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum)
{
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((void *) NULL);
extent=count*quantum;
return(AcquireMagickMemory(extent));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e V i r t u a l M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireVirtualMemory() allocates a pointer to a block of memory at least size
% bytes suitably aligned for any use.
%
% The format of the AcquireVirtualMemory method is:
%
% MemoryInfo *AcquireVirtualMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((MemoryInfo *) NULL);
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
extent=count*quantum;
memory_info->length=extent;
memory_info->signature=MagickCoreSignature;
if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,extent);
if (memory_info->blob != NULL)
{
memory_info->type=AlignedVirtualMemory;
return(memory_info);
}
}
RelinquishMagickResource(MemoryResource,extent);
if (AcquireMagickResource(MapResource,extent) != MagickFalse)
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,extent);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
return(memory_info);
}
if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
If the MapResource request failed, there is no point in trying
file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
if ((lseek(file,extent-1,SEEK_SET) == (extent-1)) &&
(write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,extent);
if (memory_info->blob != NULL)
{
(void) close(file);
memory_info->type=MapVirtualMemory;
return(memory_info);
}
}
/*
File-backed memory mapping failed, delete the temporary file.
*/
(void) close(file);
(void) RelinquishUniqueFileResource(memory_info->filename);
*memory_info->filename = '\0';
}
}
RelinquishMagickResource(DiskResource,extent);
}
RelinquishMagickResource(MapResource,extent);
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(extent);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o p y M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CopyMagickMemory() copies size bytes from memory area source to the
% destination. Copying between objects that overlap will take place
% correctly. It returns destination.
%
% The format of the CopyMagickMemory method is:
%
% void *CopyMagickMemory(void *destination,const void *source,
% const size_t size)
%
% A description of each parameter follows:
%
% o destination: the destination.
%
% o source: the source.
%
% o size: the size of the memory in bytes to allocate.
%
*/
MagickExport void *CopyMagickMemory(void *destination,const void *source,
const size_t size)
{
register const unsigned char
*p;
register unsigned char
*q;
assert(destination != (void *) NULL);
assert(source != (const void *) NULL);
p=(const unsigned char *) source;
q=(unsigned char *) destination;
if (((q+size) < p) || (q > (p+size)))
switch (size)
{
default: return(memcpy(destination,source,size));
case 8: *q++=(*p++);
case 7: *q++=(*p++);
case 6: *q++=(*p++);
case 5: *q++=(*p++);
case 4: *q++=(*p++);
case 3: *q++=(*p++);
case 2: *q++=(*p++);
case 1: *q++=(*p++);
case 0: return(destination);
}
return(memmove(destination,source,size));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyMagickMemory() deallocates memory associated with the memory manager.
%
% The format of the DestroyMagickMemory method is:
%
% DestroyMagickMemory(void)
%
*/
MagickExport void DestroyMagickMemory(void)
{
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
register ssize_t
i;
if (memory_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&memory_semaphore);
LockSemaphoreInfo(memory_semaphore);
for (i=0; i < (ssize_t) memory_pool.number_segments; i++)
if (memory_pool.segments[i]->mapped == MagickFalse)
memory_methods.destroy_memory_handler(
memory_pool.segments[i]->allocation);
else
(void) UnmapBlob(memory_pool.segments[i]->allocation,
memory_pool.segments[i]->length);
free_segments=(DataSegmentInfo *) NULL;
(void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
UnlockSemaphoreInfo(memory_semaphore);
RelinquishSemaphoreInfo(&memory_semaphore);
#endif
}
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ E x p a n d H e a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExpandHeap() get more memory from the system. It returns MagickTrue on
% success otherwise MagickFalse.
%
% The format of the ExpandHeap method is:
%
% MagickBooleanType ExpandHeap(size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes we require.
%
*/
static MagickBooleanType ExpandHeap(size_t size)
{
DataSegmentInfo
*segment_info;
MagickBooleanType
mapped;
register ssize_t
i;
register void
*block;
size_t
blocksize;
void
*segment;
blocksize=((size+12*sizeof(size_t))+SegmentSize-1) & -SegmentSize;
assert(memory_pool.number_segments < MaxSegments);
segment=MapBlob(-1,IOMode,0,blocksize);
mapped=segment != (void *) NULL ? MagickTrue : MagickFalse;
if (segment == (void *) NULL)
segment=(void *) memory_methods.acquire_memory_handler(blocksize);
if (segment == (void *) NULL)
return(MagickFalse);
segment_info=(DataSegmentInfo *) free_segments;
free_segments=segment_info->next;
segment_info->mapped=mapped;
segment_info->length=blocksize;
segment_info->allocation=segment;
segment_info->bound=(char *) segment+blocksize;
i=(ssize_t) memory_pool.number_segments-1;
for ( ; (i >= 0) && (memory_pool.segments[i]->allocation > segment); i--)
memory_pool.segments[i+1]=memory_pool.segments[i];
memory_pool.segments[i+1]=segment_info;
memory_pool.number_segments++;
size=blocksize-12*sizeof(size_t);
block=(char *) segment_info->allocation+4*sizeof(size_t);
*BlockHeader(block)=size | PreviousBlockBit;
*BlockFooter(block,size)=size;
InsertFreeBlock(block,AllocationPolicy(size));
block=NextBlock(block);
assert(block < segment_info->bound);
*BlockHeader(block)=2*sizeof(size_t);
*BlockHeader(NextBlock(block))=PreviousBlockBit;
return(MagickTrue);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M a g i c k M e m o r y M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMagickMemoryMethods() gets the methods to acquire, resize, and destroy
% memory.
%
% The format of the GetMagickMemoryMethods() method is:
%
% void GetMagickMemoryMethods(AcquireMemoryHandler *acquire_memory_handler,
% ResizeMemoryHandler *resize_memory_handler,
% DestroyMemoryHandler *destroy_memory_handler)
%
% A description of each parameter follows:
%
% o acquire_memory_handler: method to acquire memory (e.g. malloc).
%
% o resize_memory_handler: method to resize memory (e.g. realloc).
%
% o destroy_memory_handler: method to destroy memory (e.g. free).
%
*/
MagickExport void GetMagickMemoryMethods(
AcquireMemoryHandler *acquire_memory_handler,
ResizeMemoryHandler *resize_memory_handler,
DestroyMemoryHandler *destroy_memory_handler)
{
assert(acquire_memory_handler != (AcquireMemoryHandler *) NULL);
assert(resize_memory_handler != (ResizeMemoryHandler *) NULL);
assert(destroy_memory_handler != (DestroyMemoryHandler *) NULL);
*acquire_memory_handler=memory_methods.acquire_memory_handler;
*resize_memory_handler=memory_methods.resize_memory_handler;
*destroy_memory_handler=memory_methods.destroy_memory_handler;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l M e m o r y B l o b %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualMemoryBlob() returns the virtual memory blob associated with the
% specified MemoryInfo structure.
%
% The format of the GetVirtualMemoryBlob method is:
%
% void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
%
% A description of each parameter follows:
%
% o memory_info: The MemoryInfo structure.
*/
MagickExport void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
{
assert(memory_info != (const MemoryInfo *) NULL);
assert(memory_info->signature == MagickCoreSignature);
return(memory_info->blob);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h A l i g n e d M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishAlignedMemory() frees memory acquired with AcquireAlignedMemory()
% or reuse.
%
% The format of the RelinquishAlignedMemory method is:
%
% void *RelinquishAlignedMemory(void *memory)
%
% A description of each parameter follows:
%
% o memory: A pointer to a block of memory to free for reuse.
%
*/
MagickExport void *RelinquishAlignedMemory(void *memory)
{
if (memory == (void *) NULL)
return((void *) NULL);
#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
free(memory);
#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
_aligned_free(memory);
#else
free(*((void **) memory-1));
#endif
return(NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishMagickMemory() frees memory acquired with AcquireMagickMemory()
% or AcquireQuantumMemory() for reuse.
%
% The format of the RelinquishMagickMemory method is:
%
% void *RelinquishMagickMemory(void *memory)
%
% A description of each parameter follows:
%
% o memory: A pointer to a block of memory to free for reuse.
%
*/
MagickExport void *RelinquishMagickMemory(void *memory)
{
if (memory == (void *) NULL)
return((void *) NULL);
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
memory_methods.destroy_memory_handler(memory);
#else
LockSemaphoreInfo(memory_semaphore);
assert((SizeOfBlock(memory) % (4*sizeof(size_t))) == 0);
assert((*BlockHeader(NextBlock(memory)) & PreviousBlockBit) != 0);
if ((*BlockHeader(memory) & PreviousBlockBit) == 0)
{
void
*previous;
/*
Coalesce with previous adjacent block.
*/
previous=PreviousBlock(memory);
RemoveFreeBlock(previous,AllocationPolicy(SizeOfBlock(previous)));
*BlockHeader(previous)=(SizeOfBlock(previous)+SizeOfBlock(memory)) |
(*BlockHeader(previous) & ~SizeMask);
memory=previous;
}
if ((*BlockHeader(NextBlock(NextBlock(memory))) & PreviousBlockBit) == 0)
{
void
*next;
/*
Coalesce with next adjacent block.
*/
next=NextBlock(memory);
RemoveFreeBlock(next,AllocationPolicy(SizeOfBlock(next)));
*BlockHeader(memory)=(SizeOfBlock(memory)+SizeOfBlock(next)) |
(*BlockHeader(memory) & ~SizeMask);
}
*BlockFooter(memory,SizeOfBlock(memory))=SizeOfBlock(memory);
*BlockHeader(NextBlock(memory))&=(~PreviousBlockBit);
InsertFreeBlock(memory,AllocationPolicy(SizeOfBlock(memory)));
UnlockSemaphoreInfo(memory_semaphore);
#endif
return((void *) NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h V i r t u a l M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishVirtualMemory() frees memory acquired with AcquireVirtualMemory().
%
% The format of the RelinquishVirtualMemory method is:
%
% MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
%
% A description of each parameter follows:
%
% o memory_info: A pointer to a block of memory to free for reuse.
%
*/
MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickCoreSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
{
(void) RelinquishUniqueFileResource(memory_info->filename);
RelinquishMagickResource(DiskResource,memory_info->length);
}
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickCoreSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetMagickMemory() fills the first size bytes of the memory area pointed to
% by memory with the constant byte c.
%
% The format of the ResetMagickMemory method is:
%
% void *ResetMagickMemory(void *memory,int byte,const size_t size)
%
% A description of each parameter follows:
%
% o memory: a pointer to a memory allocation.
%
% o byte: set the memory to this value.
%
% o size: size of the memory to reset.
%
*/
MagickExport void *ResetMagickMemory(void *memory,int byte,const size_t size)
{
assert(memory != (void *) NULL);
return(memset(memory,byte,size));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeMagickMemory() changes the size of the memory and returns a pointer to
% the (possibly moved) block. The contents will be unchanged up to the
% lesser of the new and old sizes.
%
% The format of the ResizeMagickMemory method is:
%
% void *ResizeMagickMemory(void *memory,const size_t size)
%
% A description of each parameter follows:
%
% o memory: A pointer to a memory allocation.
%
% o size: the new size of the allocated memory.
%
*/
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
static inline void *ResizeBlock(void *block,size_t size)
{
register void
*memory;
if (block == (void *) NULL)
return(AcquireBlock(size));
memory=AcquireBlock(size);
if (memory == (void *) NULL)
return((void *) NULL);
if (size <= (SizeOfBlock(block)-sizeof(size_t)))
(void) memcpy(memory,block,size);
else
(void) memcpy(memory,block,SizeOfBlock(block)-sizeof(size_t));
memory_pool.allocation+=size;
return(memory);
}
#endif
MagickExport void *ResizeMagickMemory(void *memory,const size_t size)
{
register void
*block;
if (memory == (void *) NULL)
return(AcquireMagickMemory(size));
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
block=memory_methods.resize_memory_handler(memory,size == 0 ? 1UL : size);
if (block == (void *) NULL)
memory=RelinquishMagickMemory(memory);
#else
LockSemaphoreInfo(memory_semaphore);
block=ResizeBlock(memory,size == 0 ? 1UL : size);
if (block == (void *) NULL)
{
if (ExpandHeap(size == 0 ? 1UL : size) == MagickFalse)
{
UnlockSemaphoreInfo(memory_semaphore);
memory=RelinquishMagickMemory(memory);
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
block=ResizeBlock(memory,size == 0 ? 1UL : size);
assert(block != (void *) NULL);
}
UnlockSemaphoreInfo(memory_semaphore);
memory=RelinquishMagickMemory(memory);
#endif
return(block);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e Q u a n t u m M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeQuantumMemory() changes the size of the memory and returns a pointer
% to the (possibly moved) block. The contents will be unchanged up to the
% lesser of the new and old sizes.
%
% The format of the ResizeQuantumMemory method is:
%
% void *ResizeQuantumMemory(void *memory,const size_t count,
% const size_t quantum)
%
% A description of each parameter follows:
%
% o memory: A pointer to a memory allocation.
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport void *ResizeQuantumMemory(void *memory,const size_t count,
const size_t quantum)
{
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
{
memory=RelinquishMagickMemory(memory);
return((void *) NULL);
}
extent=count*quantum;
return(ResizeMagickMemory(memory,extent));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t M a g i c k M e m o r y M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetMagickMemoryMethods() sets the methods to acquire, resize, and destroy
% memory. Your custom memory methods must be set prior to the
% MagickCoreGenesis() method.
%
% The format of the SetMagickMemoryMethods() method is:
%
% SetMagickMemoryMethods(AcquireMemoryHandler acquire_memory_handler,
% ResizeMemoryHandler resize_memory_handler,
% DestroyMemoryHandler destroy_memory_handler)
%
% A description of each parameter follows:
%
% o acquire_memory_handler: method to acquire memory (e.g. malloc).
%
% o resize_memory_handler: method to resize memory (e.g. realloc).
%
% o destroy_memory_handler: method to destroy memory (e.g. free).
%
*/
MagickExport void SetMagickMemoryMethods(
AcquireMemoryHandler acquire_memory_handler,
ResizeMemoryHandler resize_memory_handler,
DestroyMemoryHandler destroy_memory_handler)
{
/*
Set memory methods.
*/
if (acquire_memory_handler != (AcquireMemoryHandler) NULL)
memory_methods.acquire_memory_handler=acquire_memory_handler;
if (resize_memory_handler != (ResizeMemoryHandler) NULL)
memory_methods.resize_memory_handler=resize_memory_handler;
if (destroy_memory_handler != (DestroyMemoryHandler) NULL)
memory_methods.destroy_memory_handler=destroy_memory_handler;
}
| ./CrossVul/dataset_final_sorted/CWE-284/c/good_4786_0 |
crossvul-cpp_data_good_2421_0 | /*
* Copyright (c) 2005-2007 William Pitcock, et al.
* Rights to this code are as documented in doc/LICENSE.
*
* This file contains code for the CService FLAGS functions.
*
*/
#include "atheme.h"
#include "template.h"
DECLARE_MODULE_V1
(
"chanserv/flags", false, _modinit, _moddeinit,
PACKAGE_STRING,
"Atheme Development Group <http://www.atheme.org>"
);
static void cs_cmd_flags(sourceinfo_t *si, int parc, char *parv[]);
static void check_registration_keywords(hook_user_register_check_t *hdata);
command_t cs_flags = { "FLAGS", N_("Manipulates specific permissions on a channel."),
AC_NONE, 3, cs_cmd_flags, { .path = "cservice/flags" } };
static bool anope_flags_compat = true;
void _modinit(module_t *m)
{
service_named_bind_command("chanserv", &cs_flags);
add_bool_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table, 0, &anope_flags_compat, true);
hook_add_event("nick_can_register");
hook_add_nick_can_register(check_registration_keywords);
hook_add_event("user_can_register");
hook_add_user_can_register(check_registration_keywords);
}
void _moddeinit(module_unload_intent_t intent)
{
service_named_unbind_command("chanserv", &cs_flags);
hook_del_nick_can_register(check_registration_keywords);
hook_del_user_can_register(check_registration_keywords);
del_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table);
}
typedef struct {
const char *res;
unsigned int level;
} template_iter_t;
static int global_template_search(const char *key, void *data, void *privdata)
{
template_iter_t *iter = privdata;
default_template_t *def_t = data;
if (def_t->flags == iter->level)
iter->res = key;
return 0;
}
static const char *get_template_name(mychan_t *mc, unsigned int level)
{
metadata_t *md;
const char *p, *q, *r;
char *s;
char ss[40];
static char flagname[400];
template_iter_t iter;
md = metadata_find(mc, "private:templates");
if (md != NULL)
{
p = md->value;
while (p != NULL)
{
while (*p == ' ')
p++;
q = strchr(p, '=');
if (q == NULL)
break;
r = strchr(q, ' ');
if (r != NULL && r < q)
break;
mowgli_strlcpy(ss, q, sizeof ss);
if (r != NULL && r - q < (int)(sizeof ss - 1))
{
ss[r - q] = '\0';
}
if (level == flags_to_bitmask(ss, 0))
{
mowgli_strlcpy(flagname, p, sizeof flagname);
s = strchr(flagname, '=');
if (s != NULL)
*s = '\0';
return flagname;
}
p = r;
}
}
iter.res = NULL;
iter.level = level;
mowgli_patricia_foreach(global_template_dict, global_template_search, &iter);
return iter.res;
}
static void do_list(sourceinfo_t *si, mychan_t *mc, unsigned int flags)
{
chanacs_t *ca;
mowgli_node_t *n;
bool operoverride = false;
unsigned int i = 1;
if (!(mc->flags & MC_PUBACL) && !chanacs_source_has_flag(mc, si, CA_ACLVIEW))
{
if (has_priv(si, PRIV_CHAN_AUSPEX))
operoverride = true;
else
{
command_fail(si, fault_noprivs, _("You are not authorized to perform this operation."));
return;
}
}
command_success_nodata(si, _("Entry Nickname/Host Flags"));
command_success_nodata(si, "----- ---------------------- -----");
MOWGLI_ITER_FOREACH(n, mc->chanacs.head)
{
const char *template, *mod_ago;
struct tm tm;
char mod_date[64];
ca = n->data;
if (flags && !(ca->level & flags))
continue;
template = get_template_name(mc, ca->level);
mod_ago = ca->tmodified ? time_ago(ca->tmodified) : "?";
tm = *localtime(&ca->tmodified);
strftime(mod_date, sizeof mod_date, TIME_FORMAT, &tm);
if (template != NULL)
command_success_nodata(si, _("%-5d %-22s %-20s (%s) (%s) [modified %s ago, on %s]"),
i, ca->entity ? ca->entity->name : ca->host, bitmask_to_flags(ca->level), template, mc->name, mod_ago, mod_date);
else
command_success_nodata(si, _("%-5d %-22s %-20s (%s) [modified %s ago, on %s]"),
i, ca->entity ? ca->entity->name : ca->host, bitmask_to_flags(ca->level), mc->name, mod_ago, mod_date);
i++;
}
command_success_nodata(si, "----- ---------------------- -----");
command_success_nodata(si, _("End of \2%s\2 FLAGS listing."), mc->name);
if (operoverride)
logcommand(si, CMDLOG_ADMIN, "FLAGS: \2%s\2 (oper override)", mc->name);
else
logcommand(si, CMDLOG_GET, "FLAGS: \2%s\2", mc->name);
}
static void check_registration_keywords(hook_user_register_check_t *hdata)
{
if (hdata->approved || !anope_flags_compat)
{
return;
}
if (!strcasecmp(hdata->account, "LIST") || !strcasecmp(hdata->account, "CLEAR") || !strcasecmp(hdata->account, "MODIFY"))
{
command_fail(hdata->si, fault_badparams, "The nick \2%s\2 is reserved and cannot be registered.", hdata->account);
hdata->approved = 1;
}
}
/* FLAGS <channel> [user] [flags] */
static void cs_cmd_flags(sourceinfo_t *si, int parc, char *parv[])
{
chanacs_t *ca;
mowgli_node_t *n;
char *channel = parv[0];
char *target = sstrdup(parv[1]);
char *flagstr = parv[2];
const char *str1;
unsigned int addflags, removeflags, restrictflags;
hook_channel_acl_req_t req;
mychan_t *mc;
if (parc < 1)
{
command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "FLAGS");
command_fail(si, fault_needmoreparams, _("Syntax: FLAGS <channel> [target] [flags]"));
return;
}
mc = mychan_find(channel);
if (!mc)
{
command_fail(si, fault_nosuch_target, _("Channel \2%s\2 is not registered."), channel);
return;
}
if (metadata_find(mc, "private:close:closer") && (target || !has_priv(si, PRIV_CHAN_AUSPEX)))
{
command_fail(si, fault_noprivs, _("\2%s\2 is closed."), channel);
return;
}
if (!target || (target && target[0] == '+' && flagstr == NULL))
{
unsigned int flags = (target != NULL) ? flags_to_bitmask(target, 0) : 0;
do_list(si, mc, flags);
return;
}
/*
* following conditions are for compatibility with Anope just to avoid a whole clusterfuck
* of confused users caused by their 'innovation.' yeah, that's a word for it alright.
*
* anope 1.9's shiny new FLAGS command has:
*
* FLAGS #channel LIST
* FLAGS #channel MODIFY user flagspec
* FLAGS #channel CLEAR
*
* obviously they do not support the atheme syntax, because lets face it, they like to
* 'innovate.' this is, of course, hilarious for obvious reasons. never mind that we
* *invented* the FLAGS system for channel ACLs, so you would think they would find it
* worthwhile to be compatible here. i guess that would have been too obvious or something
* about their whole 'stealing our design' thing that they have been doing in 1.9 since the
* beginning... or do i mean 'innovating?'
*
* anyway we rewrite the commands as appropriate in the two if blocks below so that they
* are processed by the flags code as the user would intend. obviously, we're not really
* capable of handling the anope flag model (which makes honestly zero sense to me, and is
* extremely complex which kind of misses the entire point of the flags UI design...) so if
* some user tries passing anope flags, it will probably be hilarious. the good news is
* most of the anope flags tie up to atheme flags in some weird way anyway (probably because,
* i don't know, they copied the entire design and then fucked it up? yeah. probably that.)
*
* --nenolod
*/
else if (anope_flags_compat && !strcasecmp(target, "LIST") && myentity_find_ext(target) == NULL)
{
do_list(si, mc, 0);
free(target);
return;
}
else if (anope_flags_compat && !strcasecmp(target, "CLEAR") && myentity_find_ext(target) == NULL)
{
free(target);
if (!chanacs_source_has_flag(mc, si, CA_FOUNDER))
{
command_fail(si, fault_noprivs, "You are not authorized to perform this operation.");
return;
}
mowgli_node_t *tn;
MOWGLI_ITER_FOREACH_SAFE(n, tn, mc->chanacs.head)
{
ca = n->data;
if (ca->level & CA_FOUNDER)
continue;
object_unref(ca);
}
logcommand(si, CMDLOG_DO, "CLEAR:FLAGS: \2%s\2", mc->name);
command_success_nodata(si, _("Cleared flags in \2%s\2."), mc->name);
return;
}
else if (anope_flags_compat && !strcasecmp(target, "MODIFY") && myentity_find_ext(target) == NULL)
{
free(target);
if (parc < 3)
{
command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "FLAGS");
command_fail(si, fault_needmoreparams, _("Syntax: FLAGS <#channel> MODIFY [target] <flags>"));
return;
}
flagstr = strchr(parv[2], ' ');
if (flagstr)
*flagstr++ = '\0';
target = strdup(parv[2]);
}
{
myentity_t *mt;
if (!si->smu)
{
command_fail(si, fault_noprivs, _("You are not logged in."));
return;
}
if (!flagstr)
{
if (!(mc->flags & MC_PUBACL) && !chanacs_source_has_flag(mc, si, CA_ACLVIEW))
{
command_fail(si, fault_noprivs, _("You are not authorized to execute this command."));
return;
}
if (validhostmask(target))
ca = chanacs_find_host_literal(mc, target, 0);
else
{
if (!(mt = myentity_find_ext(target)))
{
command_fail(si, fault_nosuch_target, _("\2%s\2 is not registered."), target);
return;
}
free(target);
target = sstrdup(mt->name);
ca = chanacs_find_literal(mc, mt, 0);
}
if (ca != NULL)
{
str1 = bitmask_to_flags2(ca->level, 0);
command_success_string(si, str1, _("Flags for \2%s\2 in \2%s\2 are \2%s\2."),
target, channel,
str1);
}
else
command_success_string(si, "", _("No flags for \2%s\2 in \2%s\2."),
target, channel);
logcommand(si, CMDLOG_GET, "FLAGS: \2%s\2 on \2%s\2", mc->name, target);
return;
}
/* founder may always set flags -- jilles */
restrictflags = chanacs_source_flags(mc, si);
if (restrictflags & CA_FOUNDER)
restrictflags = ca_all;
else
{
if (!(restrictflags & CA_FLAGS))
{
/* allow a user to remove their own access
* even without +f */
if (restrictflags & CA_AKICK ||
si->smu == NULL ||
irccasecmp(target, entity(si->smu)->name) ||
strcmp(flagstr, "-*"))
{
command_fail(si, fault_noprivs, _("You are not authorized to execute this command."));
return;
}
}
if (irccasecmp(target, entity(si->smu)->name))
restrictflags = allow_flags(mc, restrictflags);
else
restrictflags |= allow_flags(mc, restrictflags);
}
if (*flagstr == '+' || *flagstr == '-' || *flagstr == '=')
{
flags_make_bitmasks(flagstr, &addflags, &removeflags);
if (addflags == 0 && removeflags == 0)
{
command_fail(si, fault_badparams, _("No valid flags given, use /%s%s HELP FLAGS for a list"), ircd->uses_rcommand ? "" : "msg ", chansvs.me->disp);
return;
}
}
else
{
addflags = get_template_flags(mc, flagstr);
if (addflags == 0)
{
/* Hack -- jilles */
if (*target == '+' || *target == '-' || *target == '=')
command_fail(si, fault_badparams, _("Usage: FLAGS %s [target] [flags]"), mc->name);
else
command_fail(si, fault_badparams, _("Invalid template name given, use /%s%s TEMPLATE %s for a list"), ircd->uses_rcommand ? "" : "msg ", chansvs.me->disp, mc->name);
return;
}
removeflags = ca_all & ~addflags;
}
if (!validhostmask(target))
{
if (!(mt = myentity_find_ext(target)))
{
command_fail(si, fault_nosuch_target, _("\2%s\2 is not registered."), target);
return;
}
free(target);
target = sstrdup(mt->name);
ca = chanacs_open(mc, mt, NULL, true, entity(si->smu));
if (ca->level & CA_FOUNDER && removeflags & CA_FLAGS && !(removeflags & CA_FOUNDER))
{
command_fail(si, fault_noprivs, _("You may not remove a founder's +f access."));
return;
}
if (ca->level & CA_FOUNDER && removeflags & CA_FOUNDER && mychan_num_founders(mc) == 1)
{
command_fail(si, fault_noprivs, _("You may not remove the last founder."));
return;
}
if (!(ca->level & CA_FOUNDER) && addflags & CA_FOUNDER)
{
if (mychan_num_founders(mc) >= chansvs.maxfounders)
{
command_fail(si, fault_noprivs, _("Only %d founders allowed per channel."), chansvs.maxfounders);
chanacs_close(ca);
return;
}
if (!myentity_can_register_channel(mt))
{
command_fail(si, fault_toomany, _("\2%s\2 has too many channels registered."), mt->name);
chanacs_close(ca);
return;
}
if (!myentity_allow_foundership(mt))
{
command_fail(si, fault_toomany, _("\2%s\2 cannot take foundership of a channel."), mt->name);
chanacs_close(ca);
return;
}
}
if (addflags & CA_FOUNDER)
addflags |= CA_FLAGS, removeflags &= ~CA_FLAGS;
/* If NEVEROP is set, don't allow adding new entries
* except sole +b. Adding flags if the current level
* is +b counts as adding an entry.
* -- jilles */
/* XXX: not all entities are users */
if (isuser(mt) && (MU_NEVEROP & user(mt)->flags && addflags != CA_AKICK && addflags != 0 && (ca->level == 0 || ca->level == CA_AKICK)))
{
command_fail(si, fault_noprivs, _("\2%s\2 does not wish to be added to channel access lists (NEVEROP set)."), mt->name);
chanacs_close(ca);
return;
}
if (ca->level == 0 && chanacs_is_table_full(ca))
{
command_fail(si, fault_toomany, _("Channel %s access list is full."), mc->name);
chanacs_close(ca);
return;
}
req.ca = ca;
req.oldlevel = ca->level;
if (!chanacs_modify(ca, &addflags, &removeflags, restrictflags))
{
command_fail(si, fault_noprivs, _("You are not allowed to set \2%s\2 on \2%s\2 in \2%s\2."), bitmask_to_flags2(addflags, removeflags), mt->name, mc->name);
chanacs_close(ca);
return;
}
req.newlevel = ca->level;
hook_call_channel_acl_change(&req);
chanacs_close(ca);
}
else
{
if (addflags & CA_FOUNDER)
{
command_fail(si, fault_badparams, _("You may not set founder status on a hostmask."));
return;
}
ca = chanacs_open(mc, NULL, target, true, entity(si->smu));
if (ca->level == 0 && chanacs_is_table_full(ca))
{
command_fail(si, fault_toomany, _("Channel %s access list is full."), mc->name);
chanacs_close(ca);
return;
}
req.ca = ca;
req.oldlevel = ca->level;
if (!chanacs_modify(ca, &addflags, &removeflags, restrictflags))
{
command_fail(si, fault_noprivs, _("You are not allowed to set \2%s\2 on \2%s\2 in \2%s\2."), bitmask_to_flags2(addflags, removeflags), target, mc->name);
chanacs_close(ca);
return;
}
req.newlevel = ca->level;
hook_call_channel_acl_change(&req);
chanacs_close(ca);
}
if ((addflags | removeflags) == 0)
{
command_fail(si, fault_nochange, _("Channel access to \2%s\2 for \2%s\2 unchanged."), channel, target);
return;
}
flagstr = bitmask_to_flags2(addflags, removeflags);
command_success_nodata(si, _("Flags \2%s\2 were set on \2%s\2 in \2%s\2."), flagstr, target, channel);
logcommand(si, CMDLOG_SET, "FLAGS: \2%s\2 \2%s\2 \2%s\2", mc->name, target, flagstr);
verbose(mc, "\2%s\2 set flags \2%s\2 on \2%s\2", get_source_name(si), flagstr, target);
}
free(target);
}
/* vim:cinoptions=>s,e0,n0,f0,{0,}0,^0,=s,ps,t0,c3,+s,(2s,us,)20,*30,gs,hs
* vim:ts=8
* vim:sw=8
* vim:noexpandtab
*/
| ./CrossVul/dataset_final_sorted/CWE-284/c/good_2421_0 |
crossvul-cpp_data_bad_1571_5 | /*
Copyright (c) 2001, 2013, Oracle and/or its affiliates. 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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define CHECK_VERSION "2.5.1"
#include "client_priv.h"
#include "my_default.h"
#include <m_ctype.h>
#include <mysql_version.h>
#include <mysqld_error.h>
#include <sslopt-vars.h>
#include <welcome_copyright_notice.h> /* ORACLE_WELCOME_COPYRIGHT_NOTICE */
/* Exit codes */
#define EX_USAGE 1
#define EX_MYSQLERR 2
/* ALTER instead of repair. */
#define MAX_ALTER_STR_SIZE 128 * 1024
#define KEY_PARTITIONING_CHANGED_STR "KEY () partitioning changed"
static MYSQL mysql_connection, *sock = 0;
static my_bool opt_alldbs = 0, opt_check_only_changed = 0, opt_extended = 0,
opt_compress = 0, opt_databases = 0, opt_fast = 0,
opt_medium_check = 0, opt_quick = 0, opt_all_in_1 = 0,
opt_silent = 0, opt_auto_repair = 0, ignore_errors = 0,
tty_password= 0, opt_frm= 0, debug_info_flag= 0, debug_check_flag= 0,
opt_fix_table_names= 0, opt_fix_db_names= 0, opt_upgrade= 0,
opt_write_binlog= 1;
static uint verbose = 0, opt_mysql_port=0;
static int my_end_arg;
static char * opt_mysql_unix_port = 0;
static char *opt_password = 0, *current_user = 0,
*default_charset= 0, *current_host= 0;
static char *opt_plugin_dir= 0, *opt_default_auth= 0;
static int first_error = 0;
static char *opt_skip_database;
DYNAMIC_ARRAY tables4repair, tables4rebuild, alter_table_cmds;
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
static char *shared_memory_base_name=0;
#endif
static uint opt_protocol=0;
static char *opt_bind_addr = NULL;
enum operations { DO_CHECK=1, DO_REPAIR, DO_ANALYZE, DO_OPTIMIZE, DO_UPGRADE };
static struct my_option my_long_options[] =
{
{"all-databases", 'A',
"Check all the databases. This is the same as --databases with all databases selected.",
&opt_alldbs, &opt_alldbs, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
0, 0},
{"analyze", 'a', "Analyze given tables.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0,
0, 0, 0, 0},
{"all-in-1", '1',
"Instead of issuing one query for each table, use one query per database, naming all tables in the database in a comma-separated list.",
&opt_all_in_1, &opt_all_in_1, 0, GET_BOOL, NO_ARG, 0, 0, 0,
0, 0, 0},
{"auto-repair", OPT_AUTO_REPAIR,
"If a checked table is corrupted, automatically fix it. Repairing will be done after all tables have been checked, if corrupted ones were found.",
&opt_auto_repair, &opt_auto_repair, 0, GET_BOOL, NO_ARG, 0,
0, 0, 0, 0, 0},
{"bind-address", 0, "IP address to bind to.",
(uchar**) &opt_bind_addr, (uchar**) &opt_bind_addr, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"character-sets-dir", OPT_CHARSETS_DIR,
"Directory for character set files.", &charsets_dir,
&charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"check", 'c', "Check table for errors.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0,
0, 0, 0, 0},
{"check-only-changed", 'C',
"Check only tables that have changed since last check or haven't been closed properly.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"check-upgrade", 'g',
"Check tables for version-dependent changes. May be used with --auto-repair to correct tables requiring version-dependent updates.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"compress", OPT_COMPRESS, "Use compression in server/client protocol.",
&opt_compress, &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
0, 0, 0},
{"databases", 'B',
"Check several databases. Note the difference in usage; in this case no tables are given. All name arguments are regarded as database names.",
&opt_databases, &opt_databases, 0, GET_BOOL, NO_ARG,
0, 0, 0, 0, 0, 0},
#ifdef DBUG_OFF
{"debug", '#', "This is a non-debug version. Catch this and exit.",
0, 0, 0, GET_DISABLED, OPT_ARG, 0, 0, 0, 0, 0, 0},
#else
{"debug", '#', "Output debug log. Often this is 'd:t:o,filename'.",
0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"debug-check", OPT_DEBUG_CHECK, "Check memory and open file usage at exit.",
&debug_check_flag, &debug_check_flag, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"debug-info", OPT_DEBUG_INFO, "Print some debug info at exit.",
&debug_info_flag, &debug_info_flag,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"default-character-set", OPT_DEFAULT_CHARSET,
"Set the default character set.", &default_charset,
&default_charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"default_auth", OPT_DEFAULT_AUTH,
"Default authentication client-side plugin to use.",
&opt_default_auth, &opt_default_auth, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"fast",'F', "Check only tables that haven't been closed properly.",
&opt_fast, &opt_fast, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
0},
{"fix-db-names", OPT_FIX_DB_NAMES, "Fix database names.",
&opt_fix_db_names, &opt_fix_db_names,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"fix-table-names", OPT_FIX_TABLE_NAMES, "Fix table names.",
&opt_fix_table_names, &opt_fix_table_names,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"force", 'f', "Continue even if we get an SQL error.",
&ignore_errors, &ignore_errors, 0, GET_BOOL, NO_ARG, 0, 0,
0, 0, 0, 0},
{"extended", 'e',
"If you are using this option with CHECK TABLE, it will ensure that the table is 100 percent consistent, but will take a long time. If you are using this option with REPAIR TABLE, it will force using old slow repair with keycache method, instead of much faster repair by sorting.",
&opt_extended, &opt_extended, 0, GET_BOOL, NO_ARG, 0, 0, 0,
0, 0, 0},
{"help", '?', "Display this help message and exit.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"host",'h', "Connect to host.", ¤t_host,
¤t_host, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"medium-check", 'm',
"Faster than extended-check, but only finds 99.99 percent of all errors. Should be good enough for most cases.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"write-binlog", OPT_WRITE_BINLOG,
"Log ANALYZE, OPTIMIZE and REPAIR TABLE commands. Use --skip-write-binlog "
"when commands should not be sent to replication slaves.",
&opt_write_binlog, &opt_write_binlog, 0, GET_BOOL, NO_ARG,
1, 0, 0, 0, 0, 0},
{"optimize", 'o', "Optimize table.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0,
0, 0},
{"password", 'p',
"Password to use when connecting to server. If password is not given, it's solicited on the tty.",
0, 0, 0, GET_PASSWORD, OPT_ARG, 0, 0, 0, 0, 0, 0},
#ifdef _WIN32
{"pipe", 'W', "Use named pipes to connect to server.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"plugin_dir", OPT_PLUGIN_DIR, "Directory for client-side plugins.",
&opt_plugin_dir, &opt_plugin_dir, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"port", 'P', "Port number to use for connection or 0 for default to, in "
"order of preference, my.cnf, $MYSQL_TCP_PORT, "
#if MYSQL_PORT_DEFAULT == 0
"/etc/services, "
#endif
"built-in default (" STRINGIFY_ARG(MYSQL_PORT) ").",
&opt_mysql_port, &opt_mysql_port, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0,
0},
{"protocol", OPT_MYSQL_PROTOCOL, "The protocol to use for connection (tcp, socket, pipe, memory).",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"quick", 'q',
"If you are using this option with CHECK TABLE, it prevents the check from scanning the rows to check for wrong links. This is the fastest check. If you are using this option with REPAIR TABLE, it will try to repair only the index tree. This is the fastest repair method for a table.",
&opt_quick, &opt_quick, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
0},
{"repair", 'r',
"Can fix almost anything except unique keys that aren't unique.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
{"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
"Base name of shared memory.", &shared_memory_base_name, &shared_memory_base_name,
0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"silent", 's', "Print only error messages.", &opt_silent,
&opt_silent, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"skip_database", 0, "Don't process the database specified as argument",
&opt_skip_database, &opt_skip_database, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"socket", 'S', "The socket file to use for connection.",
&opt_mysql_unix_port, &opt_mysql_unix_port, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#include <sslopt-longopts.h>
{"tables", OPT_TABLES, "Overrides option --databases (-B).", 0, 0, 0,
GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"use-frm", OPT_FRM,
"When used with REPAIR, get table structure from .frm file, so the table can be repaired even if .MYI header is corrupted.",
&opt_frm, &opt_frm, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
0},
{"user", 'u', "User for login if not current user.", ¤t_user,
¤t_user, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"verbose", 'v', "Print info about the various stages.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"version", 'V', "Output version information and exit.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
static const char *load_default_groups[] = { "mysqlcheck", "client", 0 };
static void print_version(void);
static void usage(void);
static int get_options(int *argc, char ***argv);
static int process_all_databases();
static int process_databases(char **db_names);
static int process_selected_tables(char *db, char **table_names, int tables);
static int process_all_tables_in_db(char *database);
static int process_one_db(char *database);
static int use_db(char *database);
static int handle_request_for_tables(char *tables, uint length);
static int dbConnect(char *host, char *user,char *passwd);
static void dbDisconnect(char *host);
static void DBerror(MYSQL *mysql, const char *when);
static void safe_exit(int error);
static void print_result();
static uint fixed_name_length(const char *name);
static char *fix_table_name(char *dest, char *src);
int what_to_do = 0;
static void print_version(void)
{
printf("%s Ver %s Distrib %s, for %s (%s)\n", my_progname, CHECK_VERSION,
MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE);
} /* print_version */
static void usage(void)
{
print_version();
puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000"));
puts("This program can be used to CHECK (-c, -m, -C), REPAIR (-r), ANALYZE (-a),");
puts("or OPTIMIZE (-o) tables. Some of the options (like -e or -q) can be");
puts("used at the same time. Not all options are supported by all storage engines.");
puts("Please consult the MySQL manual for latest information about the");
puts("above. The options -c, -r, -a, and -o are exclusive to each other, which");
puts("means that the last option will be used, if several was specified.\n");
puts("The option -c will be used by default, if none was specified. You");
puts("can change the default behavior by making a symbolic link, or");
puts("copying this file somewhere with another name, the alternatives are:");
puts("mysqlrepair: The default option will be -r");
puts("mysqlanalyze: The default option will be -a");
puts("mysqloptimize: The default option will be -o\n");
printf("Usage: %s [OPTIONS] database [tables]\n", my_progname);
printf("OR %s [OPTIONS] --databases DB1 [DB2 DB3...]\n",
my_progname);
printf("OR %s [OPTIONS] --all-databases\n", my_progname);
print_defaults("my", load_default_groups);
my_print_help(my_long_options);
my_print_variables(my_long_options);
} /* usage */
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
char *argument)
{
int orig_what_to_do= what_to_do;
switch(optid) {
case 'a':
what_to_do = DO_ANALYZE;
break;
case 'c':
what_to_do = DO_CHECK;
break;
case 'C':
what_to_do = DO_CHECK;
opt_check_only_changed = 1;
break;
case 'I': /* Fall through */
case '?':
usage();
exit(0);
case 'm':
what_to_do = DO_CHECK;
opt_medium_check = 1;
break;
case 'o':
what_to_do = DO_OPTIMIZE;
break;
case OPT_FIX_DB_NAMES:
what_to_do= DO_UPGRADE;
opt_databases= 1;
break;
case OPT_FIX_TABLE_NAMES:
what_to_do= DO_UPGRADE;
break;
case 'p':
if (argument == disabled_my_option)
argument= (char*) ""; /* Don't require password */
if (argument)
{
char *start = argument;
my_free(opt_password);
opt_password = my_strdup(PSI_NOT_INSTRUMENTED,
argument, MYF(MY_FAE));
while (*argument) *argument++= 'x'; /* Destroy argument */
if (*start)
start[1] = 0; /* Cut length of argument */
tty_password= 0;
}
else
tty_password = 1;
break;
case 'r':
what_to_do = DO_REPAIR;
break;
case 'g':
what_to_do= DO_CHECK;
opt_upgrade= 1;
break;
case 'W':
#ifdef _WIN32
opt_protocol = MYSQL_PROTOCOL_PIPE;
#endif
break;
case '#':
DBUG_PUSH(argument ? argument : "d:t:o");
debug_check_flag= 1;
break;
#include <sslopt-case.h>
case OPT_TABLES:
opt_databases = 0;
break;
case 'v':
verbose++;
break;
case 'V': print_version(); exit(0);
case OPT_MYSQL_PROTOCOL:
opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
opt->name);
break;
}
if (orig_what_to_do && (what_to_do != orig_what_to_do))
{
fprintf(stderr, "Error: %s doesn't support multiple contradicting commands.\n",
my_progname);
return 1;
}
return 0;
}
static int get_options(int *argc, char ***argv)
{
int ho_error;
if (*argc == 1)
{
usage();
exit(0);
}
my_getopt_use_args_separator= TRUE;
if ((ho_error= load_defaults("my", load_default_groups, argc, argv)) ||
(ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
exit(ho_error);
my_getopt_use_args_separator= FALSE;
if (!what_to_do)
{
size_t pnlen= strlen(my_progname);
if (pnlen < 6) /* name too short */
what_to_do = DO_CHECK;
else if (!strcmp("repair", my_progname + pnlen - 6))
what_to_do = DO_REPAIR;
else if (!strcmp("analyze", my_progname + pnlen - 7))
what_to_do = DO_ANALYZE;
else if (!strcmp("optimize", my_progname + pnlen - 8))
what_to_do = DO_OPTIMIZE;
else
what_to_do = DO_CHECK;
}
/*
If there's no --default-character-set option given with
--fix-table-name or --fix-db-name set the default character set to "utf8".
*/
if (!default_charset)
{
if (opt_fix_db_names || opt_fix_table_names)
default_charset= (char*) "utf8";
else
default_charset= (char*) MYSQL_AUTODETECT_CHARSET_NAME;
}
if (strcmp(default_charset, MYSQL_AUTODETECT_CHARSET_NAME) &&
!get_charset_by_csname(default_charset, MY_CS_PRIMARY, MYF(MY_WME)))
{
printf("Unsupported character set: %s\n", default_charset);
return 1;
}
if (*argc > 0 && opt_alldbs)
{
printf("You should give only options, no arguments at all, with option\n");
printf("--all-databases. Please see %s --help for more information.\n",
my_progname);
return 1;
}
if (*argc < 1 && !opt_alldbs)
{
printf("You forgot to give the arguments! Please see %s --help\n",
my_progname);
printf("for more information.\n");
return 1;
}
if (tty_password)
opt_password = get_tty_password(NullS);
if (debug_info_flag)
my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
if (debug_check_flag)
my_end_arg= MY_CHECK_ERROR;
return(0);
} /* get_options */
static int process_all_databases()
{
MYSQL_ROW row;
MYSQL_RES *tableres;
int result = 0;
if (mysql_query(sock, "SHOW DATABASES") ||
!(tableres = mysql_store_result(sock)))
{
my_printf_error(0, "Error: Couldn't execute 'SHOW DATABASES': %s",
MYF(0), mysql_error(sock));
return 1;
}
while ((row = mysql_fetch_row(tableres)))
{
if (process_one_db(row[0]))
result = 1;
}
return result;
}
/* process_all_databases */
static int process_databases(char **db_names)
{
int result = 0;
for ( ; *db_names ; db_names++)
{
if (process_one_db(*db_names))
result = 1;
}
return result;
} /* process_databases */
static int process_selected_tables(char *db, char **table_names, int tables)
{
if (use_db(db))
return 1;
if (opt_all_in_1 && what_to_do != DO_UPGRADE)
{
/*
We need table list in form `a`, `b`, `c`
that's why we need 2 more chars added to to each table name
space is for more readable output in logs and in case of error
*/
char *table_names_comma_sep, *end;
size_t tot_length= 0;
int i= 0;
for (i = 0; i < tables; i++)
tot_length+= fixed_name_length(*(table_names + i)) + 2;
if (!(table_names_comma_sep = (char *)
my_malloc(PSI_NOT_INSTRUMENTED,
(sizeof(char) * tot_length) + 4, MYF(MY_WME))))
return 1;
for (end = table_names_comma_sep + 1; tables > 0;
tables--, table_names++)
{
end= fix_table_name(end, *table_names);
*end++= ',';
}
*--end = 0;
handle_request_for_tables(table_names_comma_sep + 1, (uint) (tot_length - 1));
my_free(table_names_comma_sep);
}
else
for (; tables > 0; tables--, table_names++)
handle_request_for_tables(*table_names, fixed_name_length(*table_names));
return 0;
} /* process_selected_tables */
static uint fixed_name_length(const char *name)
{
const char *p;
uint extra_length= 2; /* count the first/last backticks */
for (p= name; *p; p++)
{
if (*p == '`')
extra_length++;
else if (*p == '.')
extra_length+= 2;
}
return (uint) ((p - name) + extra_length);
}
static char *fix_table_name(char *dest, char *src)
{
*dest++= '`';
for (; *src; src++)
{
switch (*src) {
case '.': /* add backticks around '.' */
*dest++= '`';
*dest++= '.';
*dest++= '`';
break;
case '`': /* escape backtick character */
*dest++= '`';
/* fall through */
default:
*dest++= *src;
}
}
*dest++= '`';
return dest;
}
static int process_all_tables_in_db(char *database)
{
MYSQL_RES *res;
MYSQL_ROW row;
uint num_columns;
LINT_INIT(res);
if (use_db(database))
return 1;
if ((mysql_query(sock, "SHOW /*!50002 FULL*/ TABLES") &&
mysql_query(sock, "SHOW TABLES")) ||
!(res= mysql_store_result(sock)))
{
my_printf_error(0, "Error: Couldn't get table list for database %s: %s",
MYF(0), database, mysql_error(sock));
return 1;
}
num_columns= mysql_num_fields(res);
if (opt_all_in_1 && what_to_do != DO_UPGRADE)
{
/*
We need table list in form `a`, `b`, `c`
that's why we need 2 more chars added to to each table name
space is for more readable output in logs and in case of error
*/
char *tables, *end;
uint tot_length = 0;
while ((row = mysql_fetch_row(res)))
tot_length+= fixed_name_length(row[0]) + 2;
mysql_data_seek(res, 0);
if (!(tables=(char *) my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(char)*tot_length+4, MYF(MY_WME))))
{
mysql_free_result(res);
return 1;
}
for (end = tables + 1; (row = mysql_fetch_row(res)) ;)
{
if ((num_columns == 2) && (strcmp(row[1], "VIEW") == 0))
continue;
end= fix_table_name(end, row[0]);
*end++= ',';
}
*--end = 0;
if (tot_length)
handle_request_for_tables(tables + 1, tot_length - 1);
my_free(tables);
}
else
{
while ((row = mysql_fetch_row(res)))
{
/* Skip views if we don't perform renaming. */
if ((what_to_do != DO_UPGRADE) && (num_columns == 2) && (strcmp(row[1], "VIEW") == 0))
continue;
handle_request_for_tables(row[0], fixed_name_length(row[0]));
}
}
mysql_free_result(res);
return 0;
} /* process_all_tables_in_db */
static int run_query(const char *query)
{
if (mysql_query(sock, query))
{
fprintf(stderr, "Failed to %s\n", query);
fprintf(stderr, "Error: %s\n", mysql_error(sock));
return 1;
}
return 0;
}
static int fix_table_storage_name(const char *name)
{
char qbuf[100 + NAME_LEN*4];
int rc= 0;
if (strncmp(name, "#mysql50#", 9))
return 1;
sprintf(qbuf, "RENAME TABLE `%s` TO `%s`", name, name + 9);
rc= run_query(qbuf);
if (verbose)
printf("%-50s %s\n", name, rc ? "FAILED" : "OK");
return rc;
}
static int fix_database_storage_name(const char *name)
{
char qbuf[100 + NAME_LEN*4];
int rc= 0;
if (strncmp(name, "#mysql50#", 9))
return 1;
sprintf(qbuf, "ALTER DATABASE `%s` UPGRADE DATA DIRECTORY NAME", name);
rc= run_query(qbuf);
if (verbose)
printf("%-50s %s\n", name, rc ? "FAILED" : "OK");
return rc;
}
static int rebuild_table(char *name)
{
char *query, *ptr;
int rc= 0;
query= (char*)my_malloc(PSI_NOT_INSTRUMENTED,
sizeof(char) * (12 + fixed_name_length(name) + 6 + 1),
MYF(MY_WME));
if (!query)
return 1;
ptr= my_stpcpy(query, "ALTER TABLE ");
ptr= fix_table_name(ptr, name);
ptr= strxmov(ptr, " FORCE", NullS);
if (mysql_real_query(sock, query, (uint)(ptr - query)))
{
fprintf(stderr, "Failed to %s\n", query);
fprintf(stderr, "Error: %s\n", mysql_error(sock));
rc= 1;
}
my_free(query);
return rc;
}
static int process_one_db(char *database)
{
if (opt_skip_database && opt_alldbs &&
!strcmp(database, opt_skip_database))
return 0;
if (what_to_do == DO_UPGRADE)
{
int rc= 0;
if (opt_fix_db_names && !strncmp(database,"#mysql50#", 9))
{
rc= fix_database_storage_name(database);
database+= 9;
}
if (rc || !opt_fix_table_names)
return rc;
}
return process_all_tables_in_db(database);
}
static int use_db(char *database)
{
if (mysql_get_server_version(sock) >= FIRST_INFORMATION_SCHEMA_VERSION &&
!my_strcasecmp(&my_charset_latin1, database, INFORMATION_SCHEMA_DB_NAME))
return 1;
if (mysql_get_server_version(sock) >= FIRST_PERFORMANCE_SCHEMA_VERSION &&
!my_strcasecmp(&my_charset_latin1, database, PERFORMANCE_SCHEMA_DB_NAME))
return 1;
if (mysql_select_db(sock, database))
{
DBerror(sock, "when selecting the database");
return 1;
}
return 0;
} /* use_db */
static int disable_binlog()
{
const char *stmt= "SET SQL_LOG_BIN=0";
return run_query(stmt);
}
static int handle_request_for_tables(char *tables, uint length)
{
char *query, *end, options[100], message[100];
uint query_length= 0;
const char *op = 0;
options[0] = 0;
end = options;
switch (what_to_do) {
case DO_CHECK:
op = "CHECK";
if (opt_quick) end = my_stpcpy(end, " QUICK");
if (opt_fast) end = my_stpcpy(end, " FAST");
if (opt_medium_check) end = my_stpcpy(end, " MEDIUM"); /* Default */
if (opt_extended) end = my_stpcpy(end, " EXTENDED");
if (opt_check_only_changed) end = my_stpcpy(end, " CHANGED");
if (opt_upgrade) end = my_stpcpy(end, " FOR UPGRADE");
break;
case DO_REPAIR:
op= (opt_write_binlog) ? "REPAIR" : "REPAIR NO_WRITE_TO_BINLOG";
if (opt_quick) end = my_stpcpy(end, " QUICK");
if (opt_extended) end = my_stpcpy(end, " EXTENDED");
if (opt_frm) end = my_stpcpy(end, " USE_FRM");
break;
case DO_ANALYZE:
op= (opt_write_binlog) ? "ANALYZE" : "ANALYZE NO_WRITE_TO_BINLOG";
break;
case DO_OPTIMIZE:
op= (opt_write_binlog) ? "OPTIMIZE" : "OPTIMIZE NO_WRITE_TO_BINLOG";
break;
case DO_UPGRADE:
return fix_table_storage_name(tables);
}
if (!(query =(char *) my_malloc(PSI_NOT_INSTRUMENTED,
(sizeof(char)*(length+110)), MYF(MY_WME))))
return 1;
if (opt_all_in_1)
{
/* No backticks here as we added them before */
query_length= sprintf(query, "%s TABLE %s %s", op, tables, options);
}
else
{
char *ptr;
ptr= my_stpcpy(my_stpcpy(query, op), " TABLE ");
ptr= fix_table_name(ptr, tables);
ptr= strxmov(ptr, " ", options, NullS);
query_length= (uint) (ptr - query);
}
if (mysql_real_query(sock, query, query_length))
{
sprintf(message, "when executing '%s TABLE ... %s'", op, options);
DBerror(sock, message);
return 1;
}
print_result();
my_free(query);
return 0;
}
static void print_result()
{
MYSQL_RES *res;
MYSQL_ROW row;
char prev[NAME_LEN*2+2];
char prev_alter[MAX_ALTER_STR_SIZE];
uint i;
my_bool found_error=0, table_rebuild=0;
res = mysql_use_result(sock);
prev[0] = '\0';
prev_alter[0]= 0;
for (i = 0; (row = mysql_fetch_row(res)); i++)
{
int changed = strcmp(prev, row[0]);
my_bool status = !strcmp(row[2], "status");
if (status)
{
/*
if there was an error with the table, we have --auto-repair set,
and this isn't a repair op, then add the table to the tables4repair
list
*/
if (found_error && opt_auto_repair && what_to_do != DO_REPAIR &&
strcmp(row[3],"OK"))
{
if (table_rebuild)
{
if (prev_alter[0])
insert_dynamic(&alter_table_cmds, (uchar*) prev_alter);
else
insert_dynamic(&tables4rebuild, (uchar*) prev);
}
else
insert_dynamic(&tables4repair, prev);
}
found_error=0;
table_rebuild=0;
prev_alter[0]= 0;
if (opt_silent)
continue;
}
if (status && changed)
printf("%-50s %s", row[0], row[3]);
else if (!status && changed)
{
printf("%s\n%-9s: %s", row[0], row[2], row[3]);
if (opt_auto_repair && strcmp(row[2],"note"))
{
const char *alter_txt= strstr(row[3], "ALTER TABLE");
found_error=1;
if (alter_txt)
{
table_rebuild=1;
if (!strncmp(row[3], KEY_PARTITIONING_CHANGED_STR,
strlen(KEY_PARTITIONING_CHANGED_STR)) &&
strstr(alter_txt, "PARTITION BY"))
{
if (strlen(alter_txt) >= MAX_ALTER_STR_SIZE)
{
printf("Error: Alter command too long (>= %d),"
" please do \"%s\" or dump/reload to fix it!\n",
MAX_ALTER_STR_SIZE,
alter_txt);
table_rebuild= 0;
prev_alter[0]= 0;
}
else
strcpy(prev_alter, alter_txt);
}
}
}
}
else
printf("%-9s: %s", row[2], row[3]);
my_stpcpy(prev, row[0]);
putchar('\n');
}
/* add the last table to be repaired to the list */
if (found_error && opt_auto_repair && what_to_do != DO_REPAIR)
{
if (table_rebuild)
{
if (prev_alter[0])
insert_dynamic(&alter_table_cmds, (uchar*) prev_alter);
else
insert_dynamic(&tables4rebuild, (uchar*) prev);
}
else
insert_dynamic(&tables4repair, prev);
}
mysql_free_result(res);
}
static int dbConnect(char *host, char *user, char *passwd)
{
DBUG_ENTER("dbConnect");
if (verbose)
{
fprintf(stderr, "# Connecting to %s...\n", host ? host : "localhost");
}
mysql_init(&mysql_connection);
if (opt_compress)
mysql_options(&mysql_connection, MYSQL_OPT_COMPRESS, NullS);
#ifdef HAVE_OPENSSL
if (opt_use_ssl)
{
mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
}
#endif
if (opt_protocol)
mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
if (opt_bind_addr)
mysql_options(&mysql_connection, MYSQL_OPT_BIND, opt_bind_addr);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
if (shared_memory_base_name)
mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth);
mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset);
mysql_options(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_ADD,
"program_name", "mysqlcheck");
if (!(sock = mysql_real_connect(&mysql_connection, host, user, passwd,
NULL, opt_mysql_port, opt_mysql_unix_port, 0)))
{
DBerror(&mysql_connection, "when trying to connect");
DBUG_RETURN(1);
}
mysql_connection.reconnect= 1;
DBUG_RETURN(0);
} /* dbConnect */
static void dbDisconnect(char *host)
{
if (verbose)
fprintf(stderr, "# Disconnecting from %s...\n", host ? host : "localhost");
mysql_close(sock);
} /* dbDisconnect */
static void DBerror(MYSQL *mysql, const char *when)
{
DBUG_ENTER("DBerror");
my_printf_error(0,"Got error: %d: %s %s", MYF(0),
mysql_errno(mysql), mysql_error(mysql), when);
safe_exit(EX_MYSQLERR);
DBUG_VOID_RETURN;
} /* DBerror */
static void safe_exit(int error)
{
if (!first_error)
first_error= error;
if (ignore_errors)
return;
if (sock)
mysql_close(sock);
exit(error);
}
int main(int argc, char **argv)
{
MY_INIT(argv[0]);
/*
** Check out the args
*/
if (get_options(&argc, &argv))
{
my_end(my_end_arg);
exit(EX_USAGE);
}
if (dbConnect(current_host, current_user, opt_password))
exit(EX_MYSQLERR);
if (!opt_write_binlog)
{
if (disable_binlog()) {
first_error= 1;
goto end;
}
}
if (opt_auto_repair &&
(my_init_dynamic_array(&tables4repair, sizeof(char)*(NAME_LEN*2+2),16,64) ||
my_init_dynamic_array(&tables4rebuild, sizeof(char)*(NAME_LEN*2+2),16,64) ||
my_init_dynamic_array(&alter_table_cmds, MAX_ALTER_STR_SIZE, 0, 1)))
{
first_error = 1;
goto end;
}
if (opt_alldbs)
process_all_databases();
/* Only one database and selected table(s) */
else if (argc > 1 && !opt_databases)
process_selected_tables(*argv, (argv + 1), (argc - 1));
/* One or more databases, all tables */
else
process_databases(argv);
if (opt_auto_repair)
{
uint i;
if (!opt_silent && (tables4repair.elements || tables4rebuild.elements))
puts("\nRepairing tables");
what_to_do = DO_REPAIR;
for (i = 0; i < tables4repair.elements ; i++)
{
char *name= (char*) dynamic_array_ptr(&tables4repair, i);
handle_request_for_tables(name, fixed_name_length(name));
}
for (i = 0; i < tables4rebuild.elements ; i++)
rebuild_table((char*) dynamic_array_ptr(&tables4rebuild, i));
for (i = 0; i < alter_table_cmds.elements ; i++)
run_query((char*) dynamic_array_ptr(&alter_table_cmds, i));
}
end:
dbDisconnect(current_host);
if (opt_auto_repair)
{
delete_dynamic(&tables4repair);
delete_dynamic(&tables4rebuild);
}
my_free(opt_password);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
my_free(shared_memory_base_name);
#endif
my_end(my_end_arg);
return(first_error!=0);
} /* main */
| ./CrossVul/dataset_final_sorted/CWE-284/c/bad_1571_5 |
crossvul-cpp_data_bad_5396_2 | /*
* The Python Imaging Library
* $Id$
*
* imaging storage object
*
* This baseline implementation is designed to efficiently handle
* large images, provided they fit into the available memory.
*
* history:
* 1995-06-15 fl Created
* 1995-09-12 fl Updated API, compiles silently under ANSI C++
* 1995-11-26 fl Compiles silently under Borland 4.5 as well
* 1996-05-05 fl Correctly test status from Prologue
* 1997-05-12 fl Increased THRESHOLD (to speed up Tk interface)
* 1997-05-30 fl Added support for floating point images
* 1997-11-17 fl Added support for "RGBX" images
* 1998-01-11 fl Added support for integer images
* 1998-03-05 fl Exported Prologue/Epilogue functions
* 1998-07-01 fl Added basic "YCrCb" support
* 1998-07-03 fl Attach palette in prologue for "P" images
* 1998-07-09 hk Don't report MemoryError on zero-size images
* 1998-07-12 fl Change "YCrCb" to "YCbCr" (!)
* 1998-10-26 fl Added "I;16" and "I;16B" storage modes (experimental)
* 1998-12-29 fl Fixed allocation bug caused by previous fix
* 1999-02-03 fl Added "RGBa" and "BGR" modes (experimental)
* 2001-04-22 fl Fixed potential memory leak in ImagingCopyInfo
* 2003-09-26 fl Added "LA" and "PA" modes (experimental)
* 2005-10-02 fl Added image counter
*
* Copyright (c) 1998-2005 by Secret Labs AB
* Copyright (c) 1995-2005 by Fredrik Lundh
*
* See the README file for information on usage and redistribution.
*/
#include "Imaging.h"
#include <string.h>
int ImagingNewCount = 0;
/* --------------------------------------------------------------------
* Standard image object.
*/
Imaging
ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize,
int size)
{
Imaging im;
ImagingSectionCookie cookie;
im = (Imaging) calloc(1, size);
if (!im)
return (Imaging) ImagingError_MemoryError();
/* linesize overflow check, roughly the current largest space req'd */
if (xsize > (INT_MAX / 4) - 1) {
return (Imaging) ImagingError_MemoryError();
}
/* Setup image descriptor */
im->xsize = xsize;
im->ysize = ysize;
im->type = IMAGING_TYPE_UINT8;
if (strcmp(mode, "1") == 0) {
/* 1-bit images */
im->bands = im->pixelsize = 1;
im->linesize = xsize;
} else if (strcmp(mode, "P") == 0) {
/* 8-bit palette mapped images */
im->bands = im->pixelsize = 1;
im->linesize = xsize;
im->palette = ImagingPaletteNew("RGB");
} else if (strcmp(mode, "PA") == 0) {
/* 8-bit palette with alpha */
im->bands = 2;
im->pixelsize = 4; /* store in image32 memory */
im->linesize = xsize * 4;
im->palette = ImagingPaletteNew("RGB");
} else if (strcmp(mode, "L") == 0) {
/* 8-bit greyscale (luminance) images */
im->bands = im->pixelsize = 1;
im->linesize = xsize;
} else if (strcmp(mode, "LA") == 0) {
/* 8-bit greyscale (luminance) with alpha */
im->bands = 2;
im->pixelsize = 4; /* store in image32 memory */
im->linesize = xsize * 4;
} else if (strcmp(mode, "La") == 0) {
/* 8-bit greyscale (luminance) with premultiplied alpha */
im->bands = 2;
im->pixelsize = 4; /* store in image32 memory */
im->linesize = xsize * 4;
} else if (strcmp(mode, "F") == 0) {
/* 32-bit floating point images */
im->bands = 1;
im->pixelsize = 4;
im->linesize = xsize * 4;
im->type = IMAGING_TYPE_FLOAT32;
} else if (strcmp(mode, "I") == 0) {
/* 32-bit integer images */
im->bands = 1;
im->pixelsize = 4;
im->linesize = xsize * 4;
im->type = IMAGING_TYPE_INT32;
} else if (strcmp(mode, "I;16") == 0 || strcmp(mode, "I;16L") == 0 \
|| strcmp(mode, "I;16B") == 0 || strcmp(mode, "I;16N") == 0) {
/* EXPERIMENTAL */
/* 16-bit raw integer images */
im->bands = 1;
im->pixelsize = 2;
im->linesize = xsize * 2;
im->type = IMAGING_TYPE_SPECIAL;
} else if (strcmp(mode, "RGB") == 0) {
/* 24-bit true colour images */
im->bands = 3;
im->pixelsize = 4;
im->linesize = xsize * 4;
} else if (strcmp(mode, "BGR;15") == 0) {
/* EXPERIMENTAL */
/* 15-bit true colour */
im->bands = 1;
im->pixelsize = 2;
im->linesize = (xsize*2 + 3) & -4;
im->type = IMAGING_TYPE_SPECIAL;
} else if (strcmp(mode, "BGR;16") == 0) {
/* EXPERIMENTAL */
/* 16-bit reversed true colour */
im->bands = 1;
im->pixelsize = 2;
im->linesize = (xsize*2 + 3) & -4;
im->type = IMAGING_TYPE_SPECIAL;
} else if (strcmp(mode, "BGR;24") == 0) {
/* EXPERIMENTAL */
/* 24-bit reversed true colour */
im->bands = 1;
im->pixelsize = 3;
im->linesize = (xsize*3 + 3) & -4;
im->type = IMAGING_TYPE_SPECIAL;
} else if (strcmp(mode, "BGR;32") == 0) {
/* EXPERIMENTAL */
/* 32-bit reversed true colour */
im->bands = 1;
im->pixelsize = 4;
im->linesize = (xsize*4 + 3) & -4;
im->type = IMAGING_TYPE_SPECIAL;
} else if (strcmp(mode, "RGBX") == 0) {
/* 32-bit true colour images with padding */
im->bands = im->pixelsize = 4;
im->linesize = xsize * 4;
} else if (strcmp(mode, "RGBA") == 0) {
/* 32-bit true colour images with alpha */
im->bands = im->pixelsize = 4;
im->linesize = xsize * 4;
} else if (strcmp(mode, "RGBa") == 0) {
/* EXPERIMENTAL */
/* 32-bit true colour images with premultiplied alpha */
im->bands = im->pixelsize = 4;
im->linesize = xsize * 4;
} else if (strcmp(mode, "CMYK") == 0) {
/* 32-bit colour separation */
im->bands = im->pixelsize = 4;
im->linesize = xsize * 4;
} else if (strcmp(mode, "YCbCr") == 0) {
/* 24-bit video format */
im->bands = 3;
im->pixelsize = 4;
im->linesize = xsize * 4;
} else if (strcmp(mode, "LAB") == 0) {
/* 24-bit color, luminance, + 2 color channels */
/* L is uint8, a,b are int8 */
im->bands = 3;
im->pixelsize = 4;
im->linesize = xsize * 4;
} else if (strcmp(mode, "HSV") == 0) {
/* 24-bit color, luminance, + 2 color channels */
/* L is uint8, a,b are int8 */
im->bands = 3;
im->pixelsize = 4;
im->linesize = xsize * 4;
} else {
free(im);
return (Imaging) ImagingError_ValueError("unrecognized mode");
}
/* Setup image descriptor */
strcpy(im->mode, mode);
ImagingSectionEnter(&cookie);
/* Pointer array (allocate at least one line, to avoid MemoryError
exceptions on platforms where calloc(0, x) returns NULL) */
im->image = (char **) calloc((ysize > 0) ? ysize : 1, sizeof(void *));
ImagingSectionLeave(&cookie);
if (!im->image) {
free(im);
return (Imaging) ImagingError_MemoryError();
}
ImagingNewCount++;
return im;
}
Imaging
ImagingNewPrologue(const char *mode, int xsize, int ysize)
{
return ImagingNewPrologueSubtype(
mode, xsize, ysize, sizeof(struct ImagingMemoryInstance)
);
}
Imaging
ImagingNewEpilogue(Imaging im)
{
/* If the raster data allocator didn't setup a destructor,
assume that it couldn't allocate the required amount of
memory. */
if (!im->destroy)
return (Imaging) ImagingError_MemoryError();
/* Initialize alias pointers to pixel data. */
switch (im->pixelsize) {
case 1: case 2: case 3:
im->image8 = (UINT8 **) im->image;
break;
case 4:
im->image32 = (INT32 **) im->image;
break;
}
return im;
}
void
ImagingDelete(Imaging im)
{
if (!im)
return;
if (im->palette)
ImagingPaletteDelete(im->palette);
if (im->destroy)
im->destroy(im);
if (im->image)
free(im->image);
free(im);
}
/* Array Storage Type */
/* ------------------ */
/* Allocate image as an array of line buffers. */
static void
ImagingDestroyArray(Imaging im)
{
int y;
if (im->image)
for (y = 0; y < im->ysize; y++)
if (im->image[y])
free(im->image[y]);
}
Imaging
ImagingNewArray(const char *mode, int xsize, int ysize)
{
Imaging im;
ImagingSectionCookie cookie;
int y;
char* p;
im = ImagingNewPrologue(mode, xsize, ysize);
if (!im)
return NULL;
ImagingSectionEnter(&cookie);
/* Allocate image as an array of lines */
for (y = 0; y < im->ysize; y++) {
/* malloc check linesize checked in prologue */
p = (char *) calloc(1, im->linesize);
if (!p) {
ImagingDestroyArray(im);
break;
}
im->image[y] = p;
}
ImagingSectionLeave(&cookie);
if (y == im->ysize)
im->destroy = ImagingDestroyArray;
return ImagingNewEpilogue(im);
}
/* Block Storage Type */
/* ------------------ */
/* Allocate image as a single block. */
static void
ImagingDestroyBlock(Imaging im)
{
if (im->block)
free(im->block);
}
Imaging
ImagingNewBlock(const char *mode, int xsize, int ysize)
{
Imaging im;
Py_ssize_t y, i;
im = ImagingNewPrologue(mode, xsize, ysize);
if (!im)
return NULL;
/* We shouldn't overflow, since the threshold defined
below says that we're only going to allocate max 4M
here before going to the array allocator. Check anyway.
*/
if (im->linesize &&
im->ysize > INT_MAX / im->linesize) {
/* punt if we're going to overflow */
return NULL;
}
if (im->ysize * im->linesize <= 0) {
/* some platforms return NULL for malloc(0); this fix
prevents MemoryError on zero-sized images on such
platforms */
im->block = (char *) malloc(1);
} else {
/* malloc check ok, overflow check above */
im->block = (char *) calloc(im->ysize, im->linesize);
}
if (im->block) {
for (y = i = 0; y < im->ysize; y++) {
im->image[y] = im->block + i;
i += im->linesize;
}
im->destroy = ImagingDestroyBlock;
}
return ImagingNewEpilogue(im);
}
/* --------------------------------------------------------------------
* Create a new, internally allocated, image.
*/
#if defined(IMAGING_SMALL_MODEL)
#define THRESHOLD 16384L
#else
#define THRESHOLD (2048*2048*4L)
#endif
Imaging
ImagingNew(const char* mode, int xsize, int ysize)
{
int bytes;
Imaging im;
if (strlen(mode) == 1) {
if (mode[0] == 'F' || mode[0] == 'I')
bytes = 4;
else
bytes = 1;
} else
bytes = strlen(mode); /* close enough */
if ((int64_t) xsize * (int64_t) ysize <= THRESHOLD / bytes) {
im = ImagingNewBlock(mode, xsize, ysize);
if (im)
return im;
/* assume memory error; try allocating in array mode instead */
ImagingError_Clear();
}
return ImagingNewArray(mode, xsize, ysize);
}
Imaging
ImagingNew2(const char* mode, Imaging imOut, Imaging imIn)
{
/* allocate or validate output image */
if (imOut) {
/* make sure images match */
if (strcmp(imOut->mode, mode) != 0
|| imOut->xsize != imIn->xsize
|| imOut->ysize != imIn->ysize) {
return ImagingError_Mismatch();
}
} else {
/* create new image */
imOut = ImagingNew(mode, imIn->xsize, imIn->ysize);
if (!imOut)
return NULL;
}
return imOut;
}
void
ImagingCopyInfo(Imaging destination, Imaging source)
{
if (source->palette) {
if (destination->palette)
ImagingPaletteDelete(destination->palette);
destination->palette = ImagingPaletteDuplicate(source->palette);
}
}
| ./CrossVul/dataset_final_sorted/CWE-284/c/bad_5396_2 |
crossvul-cpp_data_bad_4810_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef GIT_WINHTTP
#include "git2.h"
#include "http_parser.h"
#include "buffer.h"
#include "netops.h"
#include "global.h"
#include "remote.h"
#include "smart.h"
#include "auth.h"
#include "auth_negotiate.h"
#include "tls_stream.h"
#include "socket_stream.h"
#include "curl_stream.h"
git_http_auth_scheme auth_schemes[] = {
{ GIT_AUTHTYPE_NEGOTIATE, "Negotiate", GIT_CREDTYPE_DEFAULT, git_http_auth_negotiate },
{ GIT_AUTHTYPE_BASIC, "Basic", GIT_CREDTYPE_USERPASS_PLAINTEXT, git_http_auth_basic },
};
static const char *upload_pack_service = "upload-pack";
static const char *upload_pack_ls_service_url = "/info/refs?service=git-upload-pack";
static const char *upload_pack_service_url = "/git-upload-pack";
static const char *receive_pack_service = "receive-pack";
static const char *receive_pack_ls_service_url = "/info/refs?service=git-receive-pack";
static const char *receive_pack_service_url = "/git-receive-pack";
static const char *get_verb = "GET";
static const char *post_verb = "POST";
#define OWNING_SUBTRANSPORT(s) ((http_subtransport *)(s)->parent.subtransport)
#define PARSE_ERROR_GENERIC -1
#define PARSE_ERROR_REPLAY -2
/** Look at the user field */
#define PARSE_ERROR_EXT -3
#define CHUNK_SIZE 4096
enum last_cb {
NONE,
FIELD,
VALUE
};
typedef struct {
git_smart_subtransport_stream parent;
const char *service;
const char *service_url;
char *redirect_url;
const char *verb;
char *chunk_buffer;
unsigned chunk_buffer_len;
unsigned sent_request : 1,
received_response : 1,
chunked : 1,
redirect_count : 3;
} http_stream;
typedef struct {
git_smart_subtransport parent;
transport_smart *owner;
git_stream *io;
gitno_connection_data connection_data;
bool connected;
/* Parser structures */
http_parser parser;
http_parser_settings settings;
gitno_buffer parse_buffer;
git_buf parse_header_name;
git_buf parse_header_value;
char parse_buffer_data[NETIO_BUFSIZE];
char *content_type;
char *location;
git_vector www_authenticate;
enum last_cb last_cb;
int parse_error;
int error;
unsigned parse_finished : 1;
/* Authentication */
git_cred *cred;
git_cred *url_cred;
git_vector auth_contexts;
} http_subtransport;
typedef struct {
http_stream *s;
http_subtransport *t;
/* Target buffer details from read() */
char *buffer;
size_t buf_size;
size_t *bytes_read;
} parser_context;
static bool credtype_match(git_http_auth_scheme *scheme, void *data)
{
unsigned int credtype = *(unsigned int *)data;
return !!(scheme->credtypes & credtype);
}
static bool challenge_match(git_http_auth_scheme *scheme, void *data)
{
const char *scheme_name = scheme->name;
const char *challenge = (const char *)data;
size_t scheme_len;
scheme_len = strlen(scheme_name);
return (strncasecmp(challenge, scheme_name, scheme_len) == 0 &&
(challenge[scheme_len] == '\0' || challenge[scheme_len] == ' '));
}
static int auth_context_match(
git_http_auth_context **out,
http_subtransport *t,
bool (*scheme_match)(git_http_auth_scheme *scheme, void *data),
void *data)
{
git_http_auth_scheme *scheme = NULL;
git_http_auth_context *context = NULL, *c;
size_t i;
*out = NULL;
for (i = 0; i < ARRAY_SIZE(auth_schemes); i++) {
if (scheme_match(&auth_schemes[i], data)) {
scheme = &auth_schemes[i];
break;
}
}
if (!scheme)
return 0;
/* See if authentication has already started for this scheme */
git_vector_foreach(&t->auth_contexts, i, c) {
if (c->type == scheme->type) {
context = c;
break;
}
}
if (!context) {
if (scheme->init_context(&context, &t->connection_data) < 0)
return -1;
else if (!context)
return 0;
else if (git_vector_insert(&t->auth_contexts, context) < 0)
return -1;
}
*out = context;
return 0;
}
static int apply_credentials(git_buf *buf, http_subtransport *t)
{
git_cred *cred = t->cred;
git_http_auth_context *context;
/* Apply the credentials given to us in the URL */
if (!cred && t->connection_data.user && t->connection_data.pass) {
if (!t->url_cred &&
git_cred_userpass_plaintext_new(&t->url_cred,
t->connection_data.user, t->connection_data.pass) < 0)
return -1;
cred = t->url_cred;
}
if (!cred)
return 0;
/* Get or create a context for the best scheme for this cred type */
if (auth_context_match(&context, t, credtype_match, &cred->credtype) < 0)
return -1;
return context->next_token(buf, context, cred);
}
static const char *user_agent(void)
{
const char *custom = git_libgit2__user_agent();
if (custom)
return custom;
return "libgit2 " LIBGIT2_VERSION;
}
static int gen_request(
git_buf *buf,
http_stream *s,
size_t content_length)
{
http_subtransport *t = OWNING_SUBTRANSPORT(s);
const char *path = t->connection_data.path ? t->connection_data.path : "/";
size_t i;
git_buf_printf(buf, "%s %s%s HTTP/1.1\r\n", s->verb, path, s->service_url);
git_buf_printf(buf, "User-Agent: git/2.0 (%s)\r\n", user_agent());
git_buf_printf(buf, "Host: %s\r\n", t->connection_data.host);
if (s->chunked || content_length > 0) {
git_buf_printf(buf, "Accept: application/x-git-%s-result\r\n", s->service);
git_buf_printf(buf, "Content-Type: application/x-git-%s-request\r\n", s->service);
if (s->chunked)
git_buf_puts(buf, "Transfer-Encoding: chunked\r\n");
else
git_buf_printf(buf, "Content-Length: %"PRIuZ "\r\n", content_length);
} else
git_buf_puts(buf, "Accept: */*\r\n");
for (i = 0; i < t->owner->custom_headers.count; i++) {
if (t->owner->custom_headers.strings[i])
git_buf_printf(buf, "%s\r\n", t->owner->custom_headers.strings[i]);
}
/* Apply credentials to the request */
if (apply_credentials(buf, t) < 0)
return -1;
git_buf_puts(buf, "\r\n");
if (git_buf_oom(buf))
return -1;
return 0;
}
static int parse_authenticate_response(
git_vector *www_authenticate,
http_subtransport *t,
int *allowed_types)
{
git_http_auth_context *context;
char *challenge;
size_t i;
git_vector_foreach(www_authenticate, i, challenge) {
if (auth_context_match(&context, t, challenge_match, challenge) < 0)
return -1;
else if (!context)
continue;
if (context->set_challenge &&
context->set_challenge(context, challenge) < 0)
return -1;
*allowed_types |= context->credtypes;
}
return 0;
}
static int on_header_ready(http_subtransport *t)
{
git_buf *name = &t->parse_header_name;
git_buf *value = &t->parse_header_value;
if (!strcasecmp("Content-Type", git_buf_cstr(name))) {
if (!t->content_type) {
t->content_type = git__strdup(git_buf_cstr(value));
GITERR_CHECK_ALLOC(t->content_type);
}
}
else if (!strcasecmp("WWW-Authenticate", git_buf_cstr(name))) {
char *dup = git__strdup(git_buf_cstr(value));
GITERR_CHECK_ALLOC(dup);
git_vector_insert(&t->www_authenticate, dup);
}
else if (!strcasecmp("Location", git_buf_cstr(name))) {
if (!t->location) {
t->location = git__strdup(git_buf_cstr(value));
GITERR_CHECK_ALLOC(t->location);
}
}
return 0;
}
static int on_header_field(http_parser *parser, const char *str, size_t len)
{
parser_context *ctx = (parser_context *) parser->data;
http_subtransport *t = ctx->t;
/* Both parse_header_name and parse_header_value are populated
* and ready for consumption */
if (VALUE == t->last_cb)
if (on_header_ready(t) < 0)
return t->parse_error = PARSE_ERROR_GENERIC;
if (NONE == t->last_cb || VALUE == t->last_cb)
git_buf_clear(&t->parse_header_name);
if (git_buf_put(&t->parse_header_name, str, len) < 0)
return t->parse_error = PARSE_ERROR_GENERIC;
t->last_cb = FIELD;
return 0;
}
static int on_header_value(http_parser *parser, const char *str, size_t len)
{
parser_context *ctx = (parser_context *) parser->data;
http_subtransport *t = ctx->t;
assert(NONE != t->last_cb);
if (FIELD == t->last_cb)
git_buf_clear(&t->parse_header_value);
if (git_buf_put(&t->parse_header_value, str, len) < 0)
return t->parse_error = PARSE_ERROR_GENERIC;
t->last_cb = VALUE;
return 0;
}
static int on_headers_complete(http_parser *parser)
{
parser_context *ctx = (parser_context *) parser->data;
http_subtransport *t = ctx->t;
http_stream *s = ctx->s;
git_buf buf = GIT_BUF_INIT;
int error = 0, no_callback = 0, allowed_auth_types = 0;
/* Both parse_header_name and parse_header_value are populated
* and ready for consumption. */
if (VALUE == t->last_cb)
if (on_header_ready(t) < 0)
return t->parse_error = PARSE_ERROR_GENERIC;
/* Capture authentication headers which may be a 401 (authentication
* is not complete) or a 200 (simply informing us that auth *is*
* complete.)
*/
if (parse_authenticate_response(&t->www_authenticate, t,
&allowed_auth_types) < 0)
return t->parse_error = PARSE_ERROR_GENERIC;
/* Check for an authentication failure. */
if (parser->status_code == 401 && get_verb == s->verb) {
if (!t->owner->cred_acquire_cb) {
no_callback = 1;
} else {
if (allowed_auth_types) {
if (t->cred) {
t->cred->free(t->cred);
t->cred = NULL;
}
error = t->owner->cred_acquire_cb(&t->cred,
t->owner->url,
t->connection_data.user,
allowed_auth_types,
t->owner->cred_acquire_payload);
if (error == GIT_PASSTHROUGH) {
no_callback = 1;
} else if (error < 0) {
t->error = error;
return t->parse_error = PARSE_ERROR_EXT;
} else {
assert(t->cred);
if (!(t->cred->credtype & allowed_auth_types)) {
giterr_set(GITERR_NET, "credentials callback returned an invalid cred type");
return t->parse_error = PARSE_ERROR_GENERIC;
}
/* Successfully acquired a credential. */
t->parse_error = PARSE_ERROR_REPLAY;
return 0;
}
}
}
if (no_callback) {
giterr_set(GITERR_NET, "authentication required but no callback set");
return t->parse_error = PARSE_ERROR_GENERIC;
}
}
/* Check for a redirect.
* Right now we only permit a redirect to the same hostname. */
if ((parser->status_code == 301 ||
parser->status_code == 302 ||
(parser->status_code == 303 && get_verb == s->verb) ||
parser->status_code == 307) &&
t->location) {
if (s->redirect_count >= 7) {
giterr_set(GITERR_NET, "Too many redirects");
return t->parse_error = PARSE_ERROR_GENERIC;
}
if (gitno_connection_data_from_url(&t->connection_data, t->location, s->service_url) < 0)
return t->parse_error = PARSE_ERROR_GENERIC;
/* Set the redirect URL on the stream. This is a transfer of
* ownership of the memory. */
if (s->redirect_url)
git__free(s->redirect_url);
s->redirect_url = t->location;
t->location = NULL;
t->connected = 0;
s->redirect_count++;
t->parse_error = PARSE_ERROR_REPLAY;
return 0;
}
/* Check for a 200 HTTP status code. */
if (parser->status_code != 200) {
giterr_set(GITERR_NET,
"Unexpected HTTP status code: %d",
parser->status_code);
return t->parse_error = PARSE_ERROR_GENERIC;
}
/* The response must contain a Content-Type header. */
if (!t->content_type) {
giterr_set(GITERR_NET, "No Content-Type header in response");
return t->parse_error = PARSE_ERROR_GENERIC;
}
/* The Content-Type header must match our expectation. */
if (get_verb == s->verb)
git_buf_printf(&buf,
"application/x-git-%s-advertisement",
ctx->s->service);
else
git_buf_printf(&buf,
"application/x-git-%s-result",
ctx->s->service);
if (git_buf_oom(&buf))
return t->parse_error = PARSE_ERROR_GENERIC;
if (strcmp(t->content_type, git_buf_cstr(&buf))) {
git_buf_free(&buf);
giterr_set(GITERR_NET,
"Invalid Content-Type: %s",
t->content_type);
return t->parse_error = PARSE_ERROR_GENERIC;
}
git_buf_free(&buf);
return 0;
}
static int on_message_complete(http_parser *parser)
{
parser_context *ctx = (parser_context *) parser->data;
http_subtransport *t = ctx->t;
t->parse_finished = 1;
return 0;
}
static int on_body_fill_buffer(http_parser *parser, const char *str, size_t len)
{
parser_context *ctx = (parser_context *) parser->data;
http_subtransport *t = ctx->t;
/* If our goal is to replay the request (either an auth failure or
* a redirect) then don't bother buffering since we're ignoring the
* content anyway.
*/
if (t->parse_error == PARSE_ERROR_REPLAY)
return 0;
if (ctx->buf_size < len) {
giterr_set(GITERR_NET, "Can't fit data in the buffer");
return t->parse_error = PARSE_ERROR_GENERIC;
}
memcpy(ctx->buffer, str, len);
*(ctx->bytes_read) += len;
ctx->buffer += len;
ctx->buf_size -= len;
return 0;
}
static void clear_parser_state(http_subtransport *t)
{
http_parser_init(&t->parser, HTTP_RESPONSE);
gitno_buffer_setup_fromstream(t->io,
&t->parse_buffer,
t->parse_buffer_data,
sizeof(t->parse_buffer_data));
t->last_cb = NONE;
t->parse_error = 0;
t->parse_finished = 0;
git_buf_free(&t->parse_header_name);
git_buf_init(&t->parse_header_name, 0);
git_buf_free(&t->parse_header_value);
git_buf_init(&t->parse_header_value, 0);
git__free(t->content_type);
t->content_type = NULL;
git__free(t->location);
t->location = NULL;
git_vector_free_deep(&t->www_authenticate);
}
static int write_chunk(git_stream *io, const char *buffer, size_t len)
{
git_buf buf = GIT_BUF_INIT;
/* Chunk header */
git_buf_printf(&buf, "%" PRIxZ "\r\n", len);
if (git_buf_oom(&buf))
return -1;
if (git_stream_write(io, buf.ptr, buf.size, 0) < 0) {
git_buf_free(&buf);
return -1;
}
git_buf_free(&buf);
/* Chunk body */
if (len > 0 && git_stream_write(io, buffer, len, 0) < 0)
return -1;
/* Chunk footer */
if (git_stream_write(io, "\r\n", 2, 0) < 0)
return -1;
return 0;
}
static int apply_proxy_config(http_subtransport *t)
{
int error;
git_proxy_t proxy_type;
if (!git_stream_supports_proxy(t->io))
return 0;
proxy_type = t->owner->proxy.type;
if (proxy_type == GIT_PROXY_NONE)
return 0;
if (proxy_type == GIT_PROXY_AUTO) {
char *url;
git_proxy_options opts = GIT_PROXY_OPTIONS_INIT;
if ((error = git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &url)) < 0)
return error;
opts.type = GIT_PROXY_SPECIFIED;
opts.url = url;
error = git_stream_set_proxy(t->io, &opts);
git__free(url);
return error;
}
return git_stream_set_proxy(t->io, &t->owner->proxy);
}
static int http_connect(http_subtransport *t)
{
int error;
if (t->connected &&
http_should_keep_alive(&t->parser) &&
t->parse_finished)
return 0;
if (t->io) {
git_stream_close(t->io);
git_stream_free(t->io);
t->io = NULL;
t->connected = 0;
}
if (t->connection_data.use_ssl) {
error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
} else {
#ifdef GIT_CURL
error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#else
error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#endif
}
if (error < 0)
return error;
GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream");
apply_proxy_config(t);
error = git_stream_connect(t->io);
if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL &&
git_stream_is_encrypted(t->io)) {
git_cert *cert;
int is_valid;
if ((error = git_stream_certificate(&cert, t->io)) < 0)
return error;
giterr_clear();
is_valid = error != GIT_ECERTIFICATE;
error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload);
if (error < 0) {
if (!giterr_last())
giterr_set(GITERR_NET, "user cancelled certificate check");
return error;
}
}
if (error < 0)
return error;
t->connected = 1;
return 0;
}
static int http_stream_read(
git_smart_subtransport_stream *stream,
char *buffer,
size_t buf_size,
size_t *bytes_read)
{
http_stream *s = (http_stream *)stream;
http_subtransport *t = OWNING_SUBTRANSPORT(s);
parser_context ctx;
size_t bytes_parsed;
replay:
*bytes_read = 0;
assert(t->connected);
if (!s->sent_request) {
git_buf request = GIT_BUF_INIT;
clear_parser_state(t);
if (gen_request(&request, s, 0) < 0)
return -1;
if (git_stream_write(t->io, request.ptr, request.size, 0) < 0) {
git_buf_free(&request);
return -1;
}
git_buf_free(&request);
s->sent_request = 1;
}
if (!s->received_response) {
if (s->chunked) {
assert(s->verb == post_verb);
/* Flush, if necessary */
if (s->chunk_buffer_len > 0 &&
write_chunk(t->io, s->chunk_buffer, s->chunk_buffer_len) < 0)
return -1;
s->chunk_buffer_len = 0;
/* Write the final chunk. */
if (git_stream_write(t->io, "0\r\n\r\n", 5, 0) < 0)
return -1;
}
s->received_response = 1;
}
while (!*bytes_read && !t->parse_finished) {
size_t data_offset;
int error;
/*
* Make the parse_buffer think it's as full of data as
* the buffer, so it won't try to recv more data than
* we can put into it.
*
* data_offset is the actual data offset from which we
* should tell the parser to start reading.
*/
if (buf_size >= t->parse_buffer.len) {
t->parse_buffer.offset = 0;
} else {
t->parse_buffer.offset = t->parse_buffer.len - buf_size;
}
data_offset = t->parse_buffer.offset;
if (gitno_recv(&t->parse_buffer) < 0)
return -1;
/* This call to http_parser_execute will result in invocations of the
* on_* family of callbacks. The most interesting of these is
* on_body_fill_buffer, which is called when data is ready to be copied
* into the target buffer. We need to marshal the buffer, buf_size, and
* bytes_read parameters to this callback. */
ctx.t = t;
ctx.s = s;
ctx.buffer = buffer;
ctx.buf_size = buf_size;
ctx.bytes_read = bytes_read;
/* Set the context, call the parser, then unset the context. */
t->parser.data = &ctx;
bytes_parsed = http_parser_execute(&t->parser,
&t->settings,
t->parse_buffer.data + data_offset,
t->parse_buffer.offset - data_offset);
t->parser.data = NULL;
/* If there was a handled authentication failure, then parse_error
* will have signaled us that we should replay the request. */
if (PARSE_ERROR_REPLAY == t->parse_error) {
s->sent_request = 0;
if ((error = http_connect(t)) < 0)
return error;
goto replay;
}
if (t->parse_error == PARSE_ERROR_EXT) {
return t->error;
}
if (t->parse_error < 0)
return -1;
if (bytes_parsed != t->parse_buffer.offset - data_offset) {
giterr_set(GITERR_NET,
"HTTP parser error: %s",
http_errno_description((enum http_errno)t->parser.http_errno));
return -1;
}
}
return 0;
}
static int http_stream_write_chunked(
git_smart_subtransport_stream *stream,
const char *buffer,
size_t len)
{
http_stream *s = (http_stream *)stream;
http_subtransport *t = OWNING_SUBTRANSPORT(s);
assert(t->connected);
/* Send the request, if necessary */
if (!s->sent_request) {
git_buf request = GIT_BUF_INIT;
clear_parser_state(t);
if (gen_request(&request, s, 0) < 0)
return -1;
if (git_stream_write(t->io, request.ptr, request.size, 0) < 0) {
git_buf_free(&request);
return -1;
}
git_buf_free(&request);
s->sent_request = 1;
}
if (len > CHUNK_SIZE) {
/* Flush, if necessary */
if (s->chunk_buffer_len > 0) {
if (write_chunk(t->io, s->chunk_buffer, s->chunk_buffer_len) < 0)
return -1;
s->chunk_buffer_len = 0;
}
/* Write chunk directly */
if (write_chunk(t->io, buffer, len) < 0)
return -1;
}
else {
/* Append as much to the buffer as we can */
int count = min(CHUNK_SIZE - s->chunk_buffer_len, len);
if (!s->chunk_buffer)
s->chunk_buffer = git__malloc(CHUNK_SIZE);
memcpy(s->chunk_buffer + s->chunk_buffer_len, buffer, count);
s->chunk_buffer_len += count;
buffer += count;
len -= count;
/* Is the buffer full? If so, then flush */
if (CHUNK_SIZE == s->chunk_buffer_len) {
if (write_chunk(t->io, s->chunk_buffer, s->chunk_buffer_len) < 0)
return -1;
s->chunk_buffer_len = 0;
if (len > 0) {
memcpy(s->chunk_buffer, buffer, len);
s->chunk_buffer_len = len;
}
}
}
return 0;
}
static int http_stream_write_single(
git_smart_subtransport_stream *stream,
const char *buffer,
size_t len)
{
http_stream *s = (http_stream *)stream;
http_subtransport *t = OWNING_SUBTRANSPORT(s);
git_buf request = GIT_BUF_INIT;
assert(t->connected);
if (s->sent_request) {
giterr_set(GITERR_NET, "Subtransport configured for only one write");
return -1;
}
clear_parser_state(t);
if (gen_request(&request, s, len) < 0)
return -1;
if (git_stream_write(t->io, request.ptr, request.size, 0) < 0)
goto on_error;
if (len && git_stream_write(t->io, buffer, len, 0) < 0)
goto on_error;
git_buf_free(&request);
s->sent_request = 1;
return 0;
on_error:
git_buf_free(&request);
return -1;
}
static void http_stream_free(git_smart_subtransport_stream *stream)
{
http_stream *s = (http_stream *)stream;
if (s->chunk_buffer)
git__free(s->chunk_buffer);
if (s->redirect_url)
git__free(s->redirect_url);
git__free(s);
}
static int http_stream_alloc(http_subtransport *t,
git_smart_subtransport_stream **stream)
{
http_stream *s;
if (!stream)
return -1;
s = git__calloc(sizeof(http_stream), 1);
GITERR_CHECK_ALLOC(s);
s->parent.subtransport = &t->parent;
s->parent.read = http_stream_read;
s->parent.write = http_stream_write_single;
s->parent.free = http_stream_free;
*stream = (git_smart_subtransport_stream *)s;
return 0;
}
static int http_uploadpack_ls(
http_subtransport *t,
git_smart_subtransport_stream **stream)
{
http_stream *s;
if (http_stream_alloc(t, stream) < 0)
return -1;
s = (http_stream *)*stream;
s->service = upload_pack_service;
s->service_url = upload_pack_ls_service_url;
s->verb = get_verb;
return 0;
}
static int http_uploadpack(
http_subtransport *t,
git_smart_subtransport_stream **stream)
{
http_stream *s;
if (http_stream_alloc(t, stream) < 0)
return -1;
s = (http_stream *)*stream;
s->service = upload_pack_service;
s->service_url = upload_pack_service_url;
s->verb = post_verb;
return 0;
}
static int http_receivepack_ls(
http_subtransport *t,
git_smart_subtransport_stream **stream)
{
http_stream *s;
if (http_stream_alloc(t, stream) < 0)
return -1;
s = (http_stream *)*stream;
s->service = receive_pack_service;
s->service_url = receive_pack_ls_service_url;
s->verb = get_verb;
return 0;
}
static int http_receivepack(
http_subtransport *t,
git_smart_subtransport_stream **stream)
{
http_stream *s;
if (http_stream_alloc(t, stream) < 0)
return -1;
s = (http_stream *)*stream;
/* Use Transfer-Encoding: chunked for this request */
s->chunked = 1;
s->parent.write = http_stream_write_chunked;
s->service = receive_pack_service;
s->service_url = receive_pack_service_url;
s->verb = post_verb;
return 0;
}
static int http_action(
git_smart_subtransport_stream **stream,
git_smart_subtransport *subtransport,
const char *url,
git_smart_service_t action)
{
http_subtransport *t = (http_subtransport *)subtransport;
int ret;
if (!stream)
return -1;
if ((!t->connection_data.host || !t->connection_data.port || !t->connection_data.path) &&
(ret = gitno_connection_data_from_url(&t->connection_data, url, NULL)) < 0)
return ret;
if ((ret = http_connect(t)) < 0)
return ret;
switch (action) {
case GIT_SERVICE_UPLOADPACK_LS:
return http_uploadpack_ls(t, stream);
case GIT_SERVICE_UPLOADPACK:
return http_uploadpack(t, stream);
case GIT_SERVICE_RECEIVEPACK_LS:
return http_receivepack_ls(t, stream);
case GIT_SERVICE_RECEIVEPACK:
return http_receivepack(t, stream);
}
*stream = NULL;
return -1;
}
static int http_close(git_smart_subtransport *subtransport)
{
http_subtransport *t = (http_subtransport *) subtransport;
git_http_auth_context *context;
size_t i;
clear_parser_state(t);
t->connected = 0;
if (t->io) {
git_stream_close(t->io);
git_stream_free(t->io);
t->io = NULL;
}
if (t->cred) {
t->cred->free(t->cred);
t->cred = NULL;
}
if (t->url_cred) {
t->url_cred->free(t->url_cred);
t->url_cred = NULL;
}
git_vector_foreach(&t->auth_contexts, i, context) {
if (context->free)
context->free(context);
}
git_vector_clear(&t->auth_contexts);
gitno_connection_data_free_ptrs(&t->connection_data);
memset(&t->connection_data, 0x0, sizeof(gitno_connection_data));
return 0;
}
static void http_free(git_smart_subtransport *subtransport)
{
http_subtransport *t = (http_subtransport *) subtransport;
http_close(subtransport);
git_vector_free(&t->auth_contexts);
git__free(t);
}
int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner, void *param)
{
http_subtransport *t;
GIT_UNUSED(param);
if (!out)
return -1;
t = git__calloc(sizeof(http_subtransport), 1);
GITERR_CHECK_ALLOC(t);
t->owner = (transport_smart *)owner;
t->parent.action = http_action;
t->parent.close = http_close;
t->parent.free = http_free;
t->settings.on_header_field = on_header_field;
t->settings.on_header_value = on_header_value;
t->settings.on_headers_complete = on_headers_complete;
t->settings.on_body = on_body_fill_buffer;
t->settings.on_message_complete = on_message_complete;
*out = (git_smart_subtransport *) t;
return 0;
}
#endif /* !GIT_WINHTTP */
| ./CrossVul/dataset_final_sorted/CWE-284/c/bad_4810_0 |
crossvul-cpp_data_bad_2409_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-284/c/bad_2409_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.